"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var binary_exports = {};
__export(binary_exports, {
  cleanDlxCache: () => import_binary_cache2.cleanDlxCache,
  dlxBinary: () => dlxBinary,
  downloadBinary: () => import_binary_download2.downloadBinary,
  downloadBinaryFile: () => import_binary_download2.downloadBinaryFile,
  executeBinary: () => executeBinary,
  getBinaryCacheMetadataPath: () => import_binary_cache2.getBinaryCacheMetadataPath,
  getDlxCachePath: () => import_binary_cache2.getDlxCachePath,
  isBinaryCacheValid: () => import_binary_cache2.isBinaryCacheValid,
  listDlxCache: () => import_binary_cache2.listDlxCache,
  writeBinaryCacheMetadata: () => import_binary_cache2.writeBinaryCacheMetadata
});
module.exports = __toCommonJS(binary_exports);
var import_node_process = __toESM(require("node:process"));
var import_platform = require("../constants/platform");
var import_time = require("../constants/time");
var import_read_json = require("../fs/read-json");
var import_safe = require("../fs/safe");
var import_normalize = require("../paths/normalize");
var import_spawn = require("../spawn/spawn");
var import_cache = require("./cache");
var import_integrity = require("../integrity");
var import_array = require("../primordials/array");
var import_error = require("../primordials/error");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
var import_binary_cache = require("./binary-cache");
var import_binary_download = require("./binary-download");
var import_binary_cache2 = require("./binary-cache");
var import_binary_download2 = require("./binary-download");
async function dlxBinary(args, options, spawnExtra) {
  const {
    cacheTtl = import_time.DLX_BINARY_CACHE_TTL,
    force: userForce = false,
    hash,
    integrity: rawIntegrity,
    name,
    sha256: rawSha256,
    spawnOptions,
    url,
    yes
  } = { __proto__: null, ...options };
  let integrity = rawIntegrity;
  let sha256 = rawSha256;
  if (hash !== void 0) {
    const normalized = (0, import_integrity.normalizeHash)(hash);
    if (normalized.type === "integrity") {
      integrity = normalized.value;
    } else {
      sha256 = normalized.value;
    }
  }
  const fs = (0, import_fs.getNodeFs)();
  const path = (0, import_path.getNodePath)();
  const force = yes === true ? true : userForce;
  const cacheDir = (0, import_binary_cache.getDlxCachePath)();
  const binaryName = name || `binary-${import_node_process.default.platform}-${(0, import_platform.getArch)()}`;
  const spec = `${url}:${binaryName}`;
  const cacheKey = (0, import_cache.generateCacheKey)(spec);
  const cacheEntryDir = path.join(cacheDir, cacheKey);
  const binaryPath = (0, import_normalize.normalizePath)(path.join(cacheEntryDir, binaryName));
  let downloaded = false;
  let computedIntegrity = integrity;
  if (!force && fs.existsSync(cacheEntryDir) && await (0, import_binary_cache.isBinaryCacheValid)(cacheEntryDir, cacheTtl)) {
    try {
      const metaPath = (0, import_binary_cache.getBinaryCacheMetadataPath)(cacheEntryDir);
      const metadata = await (0, import_read_json.readJson)(metaPath, { throws: false });
      if (metadata && typeof metadata === "object" && !(0, import_array.ArrayIsArray)(metadata) && typeof metadata["integrity"] === "string") {
        computedIntegrity = metadata["integrity"];
        if (!fs.existsSync(binaryPath)) {
          downloaded = true;
        }
      } else {
        downloaded = true;
      }
    } catch {
      downloaded = true;
    }
  } else {
    downloaded = true;
  }
  if (downloaded) {
    try {
      await (0, import_safe.safeMkdir)(cacheEntryDir);
    } catch (e) {
      const code = e.code;
      if (code === "EACCES" || code === "EPERM") {
        throw new import_error.ErrorCtor(
          `Permission denied creating binary cache directory: ${cacheEntryDir}
Please check directory permissions or run with appropriate access.`,
          { cause: e }
        );
      }
      if (code === "EROFS") {
        throw new import_error.ErrorCtor(
          `Cannot create binary cache directory on read-only filesystem: ${cacheEntryDir}
Ensure the filesystem is writable or set SOCKET_DLX_DIR to a writable location.`,
          { cause: e }
        );
      }
      throw new import_error.ErrorCtor(
        `Failed to create binary cache directory: ${cacheEntryDir}`,
        { cause: e }
      );
    }
    computedIntegrity = await (0, import_binary_download.downloadBinaryFile)(
      url,
      binaryPath,
      integrity,
      sha256
    );
    const stats = await fs.promises.stat(binaryPath);
    await (0, import_binary_cache.writeBinaryCacheMetadata)(
      cacheEntryDir,
      cacheKey,
      url,
      computedIntegrity || "",
      stats.size
    );
  }
  const needsShell = import_platform.WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath);
  const finalSpawnOptions = needsShell ? {
    ...spawnOptions,
    env: {
      ...spawnOptions?.env,
      PATH: `${cacheEntryDir}${path.delimiter}${import_node_process.default.env["PATH"] || ""}`
    },
    shell: true
  } : spawnOptions;
  const spawnPromise = (0, import_spawn.spawn)(binaryPath, args, finalSpawnOptions, spawnExtra);
  return {
    binaryPath,
    downloaded,
    spawnPromise
  };
}
function executeBinary(binaryPath, args, spawnOptions, spawnExtra) {
  const needsShell = import_platform.WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath);
  const path = (0, import_path.getNodePath)();
  const cacheEntryDir = path.dirname(binaryPath);
  const finalSpawnOptions = needsShell ? {
    ...spawnOptions,
    env: {
      ...spawnOptions?.env,
      PATH: `${cacheEntryDir}${path.delimiter}${import_node_process.default.env["PATH"] || ""}`
    },
    shell: true
  } : spawnOptions;
  return (0, import_spawn.spawn)(binaryPath, args, finalSpawnOptions, spawnExtra);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cleanDlxCache,
  dlxBinary,
  downloadBinary,
  downloadBinaryFile,
  executeBinary,
  getBinaryCacheMetadataPath,
  getDlxCachePath,
  isBinaryCacheValid,
  listDlxCache,
  writeBinaryCacheMetadata
});
