import { createRequire } from 'module'; const require = createRequire(import.meta.url);
let [__dirname, __filename] = typeof import.meta.url === 'string'
          ? ((url) => [url.fileURLToPath(new URL('.', import.meta.url)), url.fileURLToPath(import.meta.url)])(require('node:url'))
          : ['', ''];
import "./iterator-helpers-polyfill.js";

import {
  require_moduleresolver
} from "./chunk-QVZRZ7F3.js";
import {
  require_sandbox
} from "./chunk-GSPO4CLX.js";
import {
  __commonJS,
  __name,
  __require,
  require_files,
  require_options,
  require_transform
} from "./chunk-LY4UAG7A.js";

// lib/approx/hooks.js
var require_hooks = __commonJS({
  "lib/approx/hooks.js"(exports) {
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.initialize = initialize;
    exports.resolve = resolve;
    exports.load = load;
    var module_1 = __importDefault(__require("module"));
    var options_1 = require_options();
    var path_1 = __require("path");
    var sandbox_1 = require_sandbox();
    var moduleresolver_1 = require_moduleresolver();
    var node_url_1 = __require("node:url");
    var transform_1 = require_transform();
    var files_1 = require_files();
    var url_1 = __require("url");
    var tsModuleResolver = new moduleresolver_1.TSModuleResolver();
    var port2;
    var responsePromiseResolves = /* @__PURE__ */ new Map();
    async function initialize({ opts, port2: p2 }) {
      (0, options_1.setOptions)(opts);
      port2 = p2;
      port2.on("message", ({ filename, transformed }) => {
        const resolve2 = responsePromiseResolves.get(filename);
        if (!resolve2)
          log("error", `Error: Unexpected response for ${filename}`);
        else {
          resolve2(transformed);
          responsePromiseResolves.delete(filename);
        }
      });
    }
    __name(initialize, "initialize");
    async function resolve(specifier, context, nextResolve) {
      if (context.parentURL === `file://${__dirname}/approx.js`)
        context.parentURL = void 0;
      log("verbose", `Resolving ${specifier}${context.parentURL ? ` from ${context.parentURL}` : " (entry)"}`);
      const str = specifier.startsWith("node:") ? specifier.substring(5) : specifier;
      if (module_1.default.isBuiltin(str) && !sandbox_1.WHITELISTED.has(str))
        return {
          format: "commonjs",
          url: `node:${str}`,
          shortCircuit: true
        };
      if (context.parentURL && context.parentURL.startsWith("file://") && str.startsWith(".") && [".ts", ".tsx", ".mts", ".cts"].includes((0, path_1.extname)(context.parentURL))) {
        const parentFile = (0, node_url_1.fileURLToPath)(context.parentURL);
        const r = tsModuleResolver.resolveModuleName(specifier, parentFile);
        log("debug", `Resolved as TypeScript: ${r}`);
        try {
          return {
            format: "module",
            url: (0, url_1.pathToFileURL)(r).toString(),
            shortCircuit: true
          };
        } catch (ex) {
          log("verbose", `TypeScript module resolution failed: ${ex}`);
        }
      }
      return nextResolve(str);
    }
    __name(resolve, "resolve");
    async function load(url, context, nextLoad) {
      try {
        const ext = (0, path_1.extname)(url);
        if ([".ts", ".tsx", ".mts", ".cts", ".jsx"].includes(ext))
          context.format = "module";
        else if (ext === "" && url.startsWith("file://") && (0, files_1.isShebang)((0, node_url_1.fileURLToPath)(url)))
          context.format = "commonjs";
        const sandboxedBuiltin = url.startsWith("node:");
        log("verbose", `Loading ${url} (ESM loader, format: ${sandboxedBuiltin ? "sandboxed builtin" : context.format})`);
        const res = await nextLoad(url, context);
        if (sandboxedBuiltin) {
          const m = url.substring(5);
          log("verbose", `Intercepting import "${m}"`);
          res.source = `const m = globalThis.${transform_1.PREFIX}builtin["${m}"];`;
          for (const p of Object.getOwnPropertyNames(__require(m)))
            res.source += `module.exports["${p}"] = m["${p}"];`;
          return res;
        }
        if (res.format === "builtin" || res.format === "commonjs" || res.format === "json")
          return res;
        if (res.format !== "module")
          log("warn", `Ignoring ${url} (format: ${res.format})`);
        else if (!url.startsWith("file://"))
          log("error", `Error: Unsupported URL scheme ${url}`);
        else if (!(res.source instanceof Uint8Array))
          log("error", `Error: Unexpected source type for ${url}`);
        else {
          const filename = (0, node_url_1.fileURLToPath)(url);
          const transformPromise = new Promise((resolve2) => {
            if (responsePromiseResolves.has(filename))
              log("error", `Error: Loading conflict for ${filename}`);
            responsePromiseResolves.set(filename, resolve2);
          });
          port2.postMessage({ type: "transform", filename, source: new TextDecoder().decode(res.source) });
          const transformed = await transformPromise;
          return {
            format: "module",
            shortCircuit: true,
            source: transformed
          };
        }
      } catch (err) {
        log("error", `Suppressed exception at module load: ${err instanceof Error ? err.stack : err}`);
      }
      return {
        format: "commonjs",
        shortCircuit: true,
        source: `module.exports = ${transform_1.PREFIX}proxy`
      };
    }
    __name(load, "load");
    function log(level, str) {
      port2.postMessage({ type: "log", level, str });
    }
    __name(log, "log");
  }
});
export default require_hooks();
//# sourceMappingURL=hooks.js.map
