import {
  getPackageVersion
} from "../chunk-EVUKFMHG.mjs";

// src/auto-instrumentations/loader/esm-hook.mts
import { readFile } from "fs/promises";
import { fileURLToPath } from "url";
import { sep } from "path";
import {
  create
} from "@apm-js-collab/code-transformer";
import moduleDetailsFromPath from "module-details-from-path";
var instrumentator;
var packages;
var transformers = /* @__PURE__ */ new Map();
async function initialize(data = {}) {
  const configs = data.instrumentations || [];
  instrumentator = create(configs);
  packages = new Set(configs.map((i) => i.module.name));
}
async function resolve(specifier, context, nextResolve) {
  const url = await nextResolve(specifier, context);
  const filePath = url.url.startsWith("file:") ? fileURLToPath(url.url) : url.url;
  const normalizedForPlatform = filePath.split("/").join(sep);
  const resolvedModule = moduleDetailsFromPath(normalizedForPlatform);
  if (resolvedModule && packages?.has(resolvedModule.name)) {
    const version = getPackageVersion(resolvedModule.basedir);
    const normalizedModulePath = resolvedModule.path.replace(/\\/g, "/");
    const transformer = instrumentator.getTransformer(
      resolvedModule.name,
      version,
      normalizedModulePath
    );
    if (transformer) {
      transformers.set(url.url, transformer);
    }
  }
  return url;
}
async function load(url, context, nextLoad) {
  const result = await nextLoad(url, context);
  if (!transformers.has(url)) {
    return result;
  }
  if (result.format === "commonjs") {
    const parsedUrl = new URL(result.responseURL ?? url);
    result.source ??= await readFile(parsedUrl);
  }
  const code = result.source;
  if (code) {
    const transformer = transformers.get(url);
    try {
      const transformedCode = transformer.transform(
        code.toString("utf8"),
        "unknown"
      );
      result.source = transformedCode?.code;
      result.shortCircuit = true;
    } catch (err) {
      console.warn(`Error transforming module ${url}:`, err);
    } finally {
      transformer.free();
    }
  }
  return result;
}
export {
  initialize,
  load,
  resolve
};
