"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);

// src/auto-instrumentations/loader/cjs-patch.ts
var cjs_patch_exports = {};
__export(cjs_patch_exports, {
  ModulePatch: () => ModulePatch
});
module.exports = __toCommonJS(cjs_patch_exports);
var import_code_transformer = require("@apm-js-collab/code-transformer");
var Module = __toESM(require("module"));
var import_node_path2 = require("path");
var import_module_details_from_path = __toESM(require("module-details-from-path"));

// src/auto-instrumentations/loader/get-package-version.ts
var import_node_fs = require("fs");
var import_node_path = require("path");
var packageVersions = /* @__PURE__ */ new Map();
var packageNames = /* @__PURE__ */ new Map();
function readPackageJson(baseDir) {
  try {
    const packageJsonPath = (0, import_node_path.join)(baseDir, "package.json");
    const jsonFile = (0, import_node_fs.readFileSync)(packageJsonPath, "utf8");
    return JSON.parse(jsonFile);
  } catch {
    return void 0;
  }
}
function getPackageVersion(baseDir) {
  if (packageVersions.has(baseDir)) {
    return packageVersions.get(baseDir);
  }
  const packageJson = readPackageJson(baseDir);
  if (typeof packageJson?.version === "string") {
    packageVersions.set(baseDir, packageJson.version);
    return packageJson.version;
  }
  return process.version.slice(1);
}
function getPackageName(baseDir) {
  if (packageNames.has(baseDir)) {
    return packageNames.get(baseDir);
  }
  const packageJson = readPackageJson(baseDir);
  if (typeof packageJson?.name === "string") {
    packageNames.set(baseDir, packageJson.name);
    return packageJson.name;
  }
  return void 0;
}

// src/auto-instrumentations/loader/cjs-patch.ts
var ModulePatch = class {
  packages;
  instrumentator;
  originalCompile;
  constructor({
    instrumentations = []
  } = {}) {
    this.packages = new Set(instrumentations.map((i) => i.module.name));
    this.instrumentator = (0, import_code_transformer.create)(instrumentations);
    this.originalCompile = Module.prototype._compile;
  }
  /**
   * Patches the Node.js module class method that is responsible for compiling code.
   * If a module is found that has an instrumentator, it will transform the code before compiling it
   * with tracing channel methods.
   */
  patch() {
    const self = this;
    Module.prototype._compile = function wrappedCompile(...args) {
      const [content, filename] = args;
      const normalizedForPlatform = filename.split("/").join(import_node_path2.sep);
      const resolvedModule = (0, import_module_details_from_path.default)(normalizedForPlatform);
      if (resolvedModule) {
        const packageName = getPackageName(resolvedModule.basedir) ?? resolvedModule.name;
        if (!self.packages.has(packageName)) {
          return self.originalCompile.apply(this, args);
        }
        const version = getPackageVersion(resolvedModule.basedir);
        const normalizedModulePath = resolvedModule.path.replace(/\\/g, "/");
        const transformer = self.instrumentator.getTransformer(
          packageName,
          version,
          normalizedModulePath
        );
        if (transformer) {
          try {
            const transformedCode = transformer.transform(content, "unknown");
            args[0] = transformedCode?.code;
          } catch (error) {
            console.warn(`Error transforming module ${filename}:`, error);
          } finally {
            transformer.free();
          }
        }
      }
      return self.originalCompile.apply(this, args);
    };
  }
  /**
   * Restores the original Module.prototype._compile method
   * **Note**: This is intended to be used in testing only.
   */
  unpatch() {
    Module.prototype._compile = this.originalCompile;
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ModulePatch
});
