"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 isolation_exports = {};
__export(isolation_exports, {
  isolatePackage: () => isolatePackage,
  mergePackageJson: () => mergePackageJson,
  resolveRealPath: () => resolveRealPath
});
module.exports = __toCommonJS(isolation_exports);
var import_npm_package_arg = __toESM(require("../external/npm-package-arg"));
var import_platform = require("../constants/platform");
var import_message = require("../errors/message");
var import_normalize = require("../paths/normalize");
var import_socket = require("../paths/socket");
var import_spawn = require("../spawn/spawn");
var import_operations = require("./operations");
var import_error = require("../primordials/error");
var import_json = require("../primordials/json");
var import_object = require("../primordials/object");
var import_string = require("../primordials/string");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
const FS_CP_OPTIONS = {
  dereference: true,
  errorOnExist: false,
  filter: (src) => !src.includes("node_modules") && !(0, import_string.StringPrototypeEndsWith)(src, ".DS_Store"),
  force: true,
  recursive: true,
  ...import_platform.WIN32 ? { maxRetries: 3, retryDelay: 100 } : {}
};
async function isolatePackage(packageSpec, options) {
  const fs = (0, import_fs.getNodeFs)();
  const path = (0, import_path.getNodePath)();
  const opts = { __proto__: null, ...options };
  const { imports, install, onPackageJson, sourcePath: optSourcePath } = opts;
  let sourcePath = optSourcePath;
  let packageName;
  let spec;
  if ((0, import_normalize.isPath)(packageSpec)) {
    const trimmedPath = (0, import_normalize.trimLeadingDotSlash)(packageSpec);
    const pathToResolve = (0, import_normalize.isAbsolute)(trimmedPath) ? trimmedPath : packageSpec;
    sourcePath = path.resolve(pathToResolve);
    if (!fs.existsSync(sourcePath)) {
      throw new import_error.ErrorCtor(`Source path does not exist: ${sourcePath}`);
    }
    const pkgJson = await (0, import_operations.readPackageJson)(sourcePath, { normalize: true });
    if (!pkgJson) {
      throw new import_error.ErrorCtor(`Could not read package.json from: ${sourcePath}`);
    }
    packageName = pkgJson.name;
  } else {
    const parsed = (0, import_npm_package_arg.default)(packageSpec);
    packageName = parsed.name;
    if (parsed.type === "directory" || parsed.type === "file") {
      sourcePath = parsed.fetchSpec;
      if (!sourcePath || !fs.existsSync(sourcePath)) {
        throw new import_error.ErrorCtor(`Source path does not exist: ${sourcePath}`);
      }
      if (!packageName) {
        const pkgJson = await (0, import_operations.readPackageJson)(sourcePath, { normalize: true });
        if (!pkgJson) {
          throw new import_error.ErrorCtor(`Could not read package.json from: ${sourcePath}`);
        }
        packageName = pkgJson.name;
      }
    } else {
      spec = parsed.fetchSpec || parsed.rawSpec;
    }
  }
  if (!packageName) {
    throw new import_error.ErrorCtor(`Could not determine package name from: ${packageSpec}`);
  }
  const sanitizedName = packageName.replace(/[@/]/g, "-");
  const tempDir = await fs.promises.mkdtemp(
    path.join((0, import_socket.getOsTmpDir)(), `socket-test-${sanitizedName}-`)
  );
  const packageTempDir = path.join(tempDir, sanitizedName);
  await fs.promises.mkdir(packageTempDir, { recursive: true });
  let installedPath;
  let originalPackageJson;
  if (spec) {
    await fs.promises.writeFile(
      path.join(packageTempDir, "package.json"),
      (0, import_json.JSONStringify)(
        {
          name: "test-temp",
          private: true,
          version: "1.0.0"
        },
        null,
        2
      )
    );
    if (install) {
      await install(packageTempDir);
    } else {
      const packageInstallSpec = (0, import_string.StringPrototypeStartsWith)(spec, "https://") ? spec : `${packageName}@${spec}`;
      await (0, import_spawn.spawn)("pnpm", ["add", packageInstallSpec], {
        cwd: packageTempDir,
        shell: import_platform.WIN32,
        stdio: "pipe"
      });
    }
    installedPath = path.join(packageTempDir, "node_modules", packageName);
    originalPackageJson = await (0, import_operations.readPackageJson)(installedPath, {
      normalize: true
    });
    if (sourcePath) {
      const realInstalledPath = await resolveRealPath(installedPath);
      const realSourcePath = await resolveRealPath(sourcePath);
      if (realSourcePath !== realInstalledPath) {
        await fs.promises.cp(sourcePath, installedPath, FS_CP_OPTIONS);
      }
    }
  } else {
    if (!sourcePath) {
      throw new import_error.ErrorCtor(
        "sourcePath is required when no version spec provided"
      );
    }
    const scopedPath = (0, import_string.StringPrototypeStartsWith)(packageName, "@") ? path.join(
      packageTempDir,
      "node_modules",
      packageName.split("/")[0] ?? ""
    ) : path.join(packageTempDir, "node_modules");
    await fs.promises.mkdir(scopedPath, { recursive: true });
    installedPath = path.join(packageTempDir, "node_modules", packageName);
    await fs.promises.cp(sourcePath, installedPath, FS_CP_OPTIONS);
  }
  if (onPackageJson || originalPackageJson) {
    const pkgJsonPath = path.join(installedPath, "package.json");
    const mergedPkgJson = await mergePackageJson(
      pkgJsonPath,
      originalPackageJson
    );
    const finalPkgJson = onPackageJson ? await onPackageJson(mergedPkgJson) : mergedPkgJson;
    await fs.promises.writeFile(
      pkgJsonPath,
      (0, import_json.JSONStringify)(finalPkgJson, null, 2)
    );
  }
  if (install) {
    await install(installedPath);
  } else {
    await (0, import_spawn.spawn)("pnpm", ["install"], {
      cwd: installedPath,
      shell: import_platform.WIN32,
      stdio: "pipe"
    });
  }
  const exports2 = imports ? { __proto__: null } : void 0;
  if (imports) {
    for (const { 0: key, 1: specifier } of (0, import_object.ObjectEntries)(imports)) {
      const fullPath = path.join(installedPath, specifier);
      exports2[key] = require(fullPath);
    }
  }
  return {
    exports: exports2,
    tmpdir: installedPath
  };
}
async function mergePackageJson(pkgJsonPath, originalPkgJson) {
  const fs = (0, import_fs.getNodeFs)();
  let pkgJson;
  try {
    pkgJson = (0, import_json.JSONParse)(await fs.promises.readFile(pkgJsonPath, "utf8"));
  } catch (e) {
    throw new import_error.ErrorCtor(`Failed to parse ${pkgJsonPath}: ${(0, import_message.errorMessage)(e)}`, {
      cause: e
    });
  }
  const mergedPkgJson = originalPkgJson ? { ...originalPkgJson, ...pkgJson } : pkgJson;
  return mergedPkgJson;
}
async function resolveRealPath(pathStr) {
  const fs = (0, import_fs.getNodeFs)();
  const path = (0, import_path.getNodePath)();
  try {
    return await fs.promises.realpath(pathStr);
  } catch {
    return path.resolve(pathStr);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  isolatePackage,
  mergePackageJson,
  resolveRealPath
});
