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 {
  __commonJS,
  __name,
  __require,
  require_extras,
  require_files,
  require_logger,
  require_options,
  require_tokens,
  require_util
} from "./chunk-LY4UAG7A.js";

// lib/parsing/parser.js
var require_parser = __commonJS({
  "lib/parsing/parser.js"(exports) {
    "use strict";
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseAndDesugar = parseAndDesugar;
    var logger_1 = __importDefault(require_logger());
    var core_1 = __require("@babel/core");
    var parser_1 = __require("@babel/parser");
    var extras_1 = require_extras();
    var transformOptions = [false, true].map((fragmentStateDefined) => (0, core_1.loadOptions)({
      cloneInputAst: false,
      plugins: [
        extras_1.replaceTypeScriptImportExportAssignmentsAndAddConstructors,
        ["@babel/plugin-transform-typescript", {
          onlyRemoveTypeImports: fragmentStateDefined,
          allowDeclareFields: fragmentStateDefined
        }],
        ["@babel/plugin-transform-template-literals", { loose: true }]
      ],
      cwd: __dirname,
      babelrc: false,
      configFile: false,
      ast: true
    }));
    function parseAndDesugar(str, file, f) {
      let originalAst;
      try {
        const options = {
          sourceFilename: file,
          allowImportExportEverywhere: true,
          allowAwaitOutsideFunction: true,
          allowReturnOutsideFunction: true,
          allowSuperOutsideMethod: true,
          allowUndeclaredExports: true,
          errorRecovery: true,
          attachComment: false,
          createParenthesizedExpressions: true,
          sourceType: "unambiguous",
          tokens: true,
          plugins: [
            "typescript",
            "exportDefaultFrom",
            ["decorators", { decoratorsBeforeExport: false }]
          ]
        };
        try {
          originalAst = (0, parser_1.parse)(str, options);
        } catch (e) {
          if (logger_1.default.isVerboseEnabled())
            logger_1.default.verbose(`Parse error for ${file}${e instanceof Error ? `: ${e.message}` : ""}, retrying with JSX and Flow enabled`);
          options.plugins.push("jsx");
          if (file.endsWith(".jsx") || file.endsWith(".js")) {
            options.plugins.push("flow");
            options.plugins.splice(options.plugins?.indexOf("typescript"), 1);
          }
          originalAst = (0, parser_1.parse)(str, options);
        }
      } catch (e) {
        f?.error(`Unrecoverable parse error for ${file}${e instanceof Error ? `: ${e.message}` : ""}`);
        return null;
      }
      let res;
      const p = Error.prepareStackTrace;
      const cw = console.warn;
      console.warn = function() {
      };
      try {
        const opts = transformOptions[f ? 1 : 0];
        res = (0, core_1.transformFromAstSync)(originalAst, str, logger_1.default.isDebugEnabled() ? { ...opts, code: true } : opts);
      } catch (e) {
        f?.error(`Babel transformation failed for ${file}${e instanceof Error ? `: ${e.message}` : ""}`);
        return null;
      } finally {
        Error.prepareStackTrace = p;
        console.warn = cw;
      }
      if (!res) {
        f?.error(`Babel transformation failed silently for ${file}`);
        return null;
      }
      if (res.code) {
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug("Desugared code:\n" + res.code);
      }
      return res.ast;
    }
    __name(parseAndDesugar, "parseAndDesugar");
  }
});

// lib/approx/patching.js
var require_patching = __commonJS({
  "lib/approx/patching.js"(exports) {
    "use strict";
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Patching = exports.APPROX_DEVEL = exports.APPROX_ONLY_EMPTY = exports.APPROX_WRITE = exports.APPROX_READ = void 0;
    var util_1 = require_util();
    var tokens_1 = require_tokens();
    var types_1 = __require("@babel/types");
    var assert_1 = __importDefault(__require("assert"));
    var logger_1 = __importDefault(require_logger());
    var options_1 = require_options();
    exports.APPROX_READ = true;
    exports.APPROX_WRITE = true;
    exports.APPROX_ONLY_EMPTY = false;
    exports.APPROX_DEVEL = false;
    var Patching = class {
      static {
        __name(this, "Patching");
      }
      hints;
      allocToToken = /* @__PURE__ */ new Map();
      dynamicReads = [];
      usedHints = /* @__PURE__ */ new Set();
      constructor(hints) {
        this.hints = hints;
        (0, assert_1.default)(!options_1.options.widening, "Option --widening is not supported with approximate interpretation patching");
        (0, assert_1.default)(!options_1.options.oldobj, "Option --oldobj is not supported with approximate interpretation patching");
      }
      registerAllocationSite(t) {
        (0, assert_1.default)(t instanceof tokens_1.AllocationSiteToken || t instanceof tokens_1.FunctionToken || t instanceof tokens_1.NativeObjectToken);
        let loc;
        if (t instanceof tokens_1.AllocationSiteToken) {
          if (t.kind === "PromiseResolve" || t.kind === "PromiseReject")
            return;
          loc = (0, util_1.locationToStringWithFileAndEnd)(t.allocSite.loc, true);
        } else if (t instanceof tokens_1.FunctionToken)
          loc = (0, util_1.locationToStringWithFileAndEnd)(t.fun.loc, true);
        else {
          (0, assert_1.default)(t.moduleInfo);
          loc = `${t.moduleInfo.toString()}:-1:-1:-1:-1`;
        }
        let type;
        if (t instanceof tokens_1.PrototypeToken)
          type = "Prototype";
        else if (t instanceof tokens_1.FunctionToken) {
          if ((0, types_1.isClassMethod)(t.fun) && t.fun.kind === "constructor")
            type = "Class";
          else
            type = "Function";
        } else if (t instanceof tokens_1.ArrayToken)
          type = "Array";
        else
          type = "Object";
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`Registering token ${type}[${loc}]`);
        const key = `${loc}:${type}`;
        const q = this.allocToToken.get(key);
        if (q && q !== t)
          logger_1.default.error(`Error: token conflict for ${key}: ${q} !== ${t}`);
        this.allocToToken.set(key, t);
      }
      recordDynamicRead(node, dstVar) {
        if (!exports.APPROX_READ || !dstVar)
          return;
        this.dynamicReads.push({ node, dstVar });
      }
      getRequireHints(mod, loc) {
        if (mod !== void 0) {
          const i = this.hints.moduleIndex.get(mod);
          if (i !== void 0) {
            const hints = this.hints.requires.get(`${i}:${loc}`);
            if (hints) {
              const s = hints.map((h) => {
                this.usedHints.add(h);
                return h.str;
              });
              if (logger_1.default.isVerboseEnabled())
                logger_1.default.verbose(`Patching dynamic require/import: ${mod}:${loc} <- [${s.join(",")}]`);
              return s;
            }
          }
        }
        return void 0;
      }
      patch(solver) {
        const d = solver.diagnostics.patching;
        d.totalHints = (0, util_1.mapArraySize)(this.hints.reads) + (0, util_1.mapArraySize)(this.hints.writes) + (0, util_1.mapArraySize)(this.hints.requires) + (0, util_1.mapArraySize)(this.hints.evals);
        d.modulesNotAnalyzed = 0;
        const mods = new Set(solver.globalState.moduleInfos.values().filter((m) => m.loc));
        const fileToModule = this.hints.modules.map((m) => {
          const mod = solver.globalState.moduleInfos.get(m);
          if (!mod) {
            if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
              logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Module has been analyzed dynamically but not statically: ${m} (possibly excluded from analysis)`);
            d.modulesNotAnalyzed++;
          } else
            mods.delete(mod);
          if (mod && !mod.loc)
            return void 0;
          return mod?.toString();
        });
        if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
          for (const m of mods)
            logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Module analyzed statically but not dynamically: ${m}`);
        d.modulesNotInHints = mods.size;
        const canonicalizeDynamicLocation = /* @__PURE__ */ __name((loc) => {
          const i = loc.indexOf(":");
          if (i === -1)
            assert_1.default.fail(`Unable to parse location: ${loc}`);
          const m = fileToModule[parseInt(loc)];
          if (m !== void 0)
            return `${m}:${loc.substring(i + 1)}`;
          else
            return void 0;
        }, "canonicalizeDynamicLocation");
        const visitedFunctions = /* @__PURE__ */ new Set();
        for (const fun of this.hints.functions) {
          const loc = canonicalizeDynamicLocation(fun);
          if (loc)
            visitedFunctions.add(loc);
        }
        d.functionsNotVisited = 0;
        function checkFunctionVisited(fun) {
          if (!visitedFunctions.has((0, util_1.locationToStringWithFileAndEnd)(fun.loc, true)) && !fun.isDummyConstructor) {
            if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
              logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Function analyzed statically but not dynamically: ${fun}`);
            d.functionsNotVisited++;
          }
          for (const fun2 of fun.functions)
            checkFunctionVisited(fun2);
        }
        __name(checkFunctionVisited, "checkFunctionVisited");
        for (const mod of solver.globalState.moduleInfos.values())
          for (const fun of mod.functions)
            checkFunctionVisited(fun);
        const patch = /* @__PURE__ */ __name((dstVar, valToken, hint) => {
          if (options_1.options.diagnostics || options_1.options.diagnosticsJson)
            this.usedHints.add(hint);
          const repVar = solver.fragmentState.getRepresentative(dstVar);
          if (!solver.fragmentState.hasToken(repVar, valToken) && (!exports.APPROX_ONLY_EMPTY || solver.fragmentState.getTokensSize(repVar)[0] === 0)) {
            solver.addToken(valToken, repVar);
            return true;
          }
          return false;
        }, "patch");
        if (exports.APPROX_READ) {
          const locationToHints = /* @__PURE__ */ new Map();
          for (const hs of this.hints.reads.values())
            for (const hint of hs) {
              const dl = canonicalizeDynamicLocation(hint.loc);
              if (dl !== void 0)
                (0, util_1.mapArrayAdd)(dl, hint, locationToHints);
            }
          for (const { node, dstVar } of this.dynamicReads) {
            const nodeLoc = (0, util_1.locationToStringWithFileAndEnd)(node.loc, true);
            const hints = locationToHints.get(nodeLoc);
            if (hints)
              for (const hint of hints) {
                const valLoc = canonicalizeDynamicLocation(hint.valLoc);
                if (valLoc !== void 0) {
                  const valToken = this.allocToToken.get(`${valLoc}:${hint.valType}`);
                  if (!valToken) {
                    if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                      logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Token not found: ${hint.valType}[${valLoc}] for value at read`);
                    d.tokensNotFound++;
                    continue;
                  }
                  if (logger_1.default.isVerboseEnabled())
                    logger_1.default.verbose(`Patching dynamic read: ${dstVar} <- ${valToken}`);
                  if (patch(dstVar, valToken, hint)) {
                    d.readTokensAdded++;
                    if (solver.fragmentState.unhandledDynamicPropertyReads.has(node)) {
                      solver.fragmentState.unhandledDynamicPropertyReads.delete(node);
                      d.patchedReads++;
                    }
                  }
                }
              }
          }
        }
        if (exports.APPROX_WRITE) {
          const nodes = /* @__PURE__ */ new Map();
          for (const node of solver.fragmentState.unhandledDynamicPropertyWrites.keys()) {
            const nodeLoc = (0, util_1.locationToStringWithFileAndEnd)(node.loc, true);
            (0, util_1.mapArrayAdd)(nodeLoc, node, nodes);
          }
          for (const hs of this.hints.writes.values())
            for (const hint of hs) {
              const baseLoc = hint.baseLoc ? canonicalizeDynamicLocation(hint.baseLoc) : void 0;
              const valLoc = hint.valLoc ? canonicalizeDynamicLocation(hint.valLoc) : void 0;
              if (baseLoc !== void 0 && valLoc !== void 0) {
                const baseToken = this.allocToToken.get(`${baseLoc}:${hint.baseType}`);
                if (!baseToken) {
                  if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                    logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Token not found: ${hint.baseType}[${baseLoc}] for base at write`);
                  d.tokensNotFound++;
                  continue;
                }
                const valToken = this.allocToToken.get(`${valLoc}:${hint.valType}`);
                if (!valToken) {
                  if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                    logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Token not found: ${hint.valType}[${valLoc}] for value at write`);
                  d.tokensNotFound++;
                  continue;
                }
                const dstVar = solver.varProducer.objPropVar(baseToken, hint.prop, hint.type);
                if (logger_1.default.isVerboseEnabled())
                  logger_1.default.verbose(`Patching dynamic write: ${dstVar.obj}["${hint.prop}"] <- ${valToken}`);
                if (patch(dstVar, valToken, hint)) {
                  d.writeTokensAdded++;
                  const hintLoc = canonicalizeDynamicLocation(hint.loc);
                  if (hintLoc) {
                    const ns = nodes.get(hintLoc);
                    if (ns) {
                      for (const node of ns)
                        if (solver.fragmentState.unhandledDynamicPropertyWrites.has(node)) {
                          solver.fragmentState.unhandledDynamicPropertyWrites.delete(node);
                          d.patchedWrites++;
                        }
                    }
                  }
                }
              }
            }
        }
        if (options_1.options.diagnostics || options_1.options.diagnosticsJson) {
          for (const hs of this.hints.reads.values())
            for (const hint of hs)
              if (!this.usedHints.has(hint)) {
                const loc = canonicalizeDynamicLocation(hint.loc);
                const valLoc = canonicalizeDynamicLocation(hint.valLoc);
                if (loc && valLoc) {
                  if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                    logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Unused read hint: ${loc} <- ${valLoc}:${hint.valType}[${hint.prop ? `"${hint.prop}"` : "?"}]`);
                  d.unusedHints++;
                }
              }
          for (const hs of this.hints.writes.values())
            for (const hint of hs)
              if (!this.usedHints.has(hint)) {
                const baseLoc = canonicalizeDynamicLocation(hint.baseLoc);
                const valLoc = canonicalizeDynamicLocation(hint.valLoc);
                if (baseLoc && valLoc) {
                  if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                    logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Unused write hint: ${baseLoc}:${hint.baseType}["${hint.prop}"] <- ${valLoc}:${hint.valType}`);
                  d.unusedHints++;
                }
              }
          for (const hs of this.hints.requires.values())
            for (const hint of hs)
              if (!this.usedHints.has(hint)) {
                const loc = canonicalizeDynamicLocation(hint.loc);
                if (loc) {
                  if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                    logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Unused require hint: ${loc} "${hint.str}"`);
                  d.unusedHints++;
                }
              }
          for (const hs of this.hints.evals.values())
            for (const hint of hs)
              if (!this.usedHints.has(hint)) {
                const loc = canonicalizeDynamicLocation(hint.loc);
                if (loc) {
                  if (logger_1.default.isVerboseEnabled() || exports.APPROX_DEVEL)
                    logger_1.default[exports.APPROX_DEVEL ? "warn" : "verbose"](`Unused eval hint: ${loc} "${hint.str.substring(0, 40).replaceAll("\n", "\u2424")}${hint.str.length > 40 ? "..." : ""}"`);
                  d.unusedHints++;
                }
              }
        }
      }
      printDiagnostics(solver) {
        const p = solver.diagnostics.patching;
        logger_1.default.info(`Patching tokens added: ${p.readTokensAdded} reads, ${p.writeTokensAdded} writes`);
        logger_1.default.info(`Dynamic reads patched: ${p.patchedReads}, remaining unpatched: ${solver.fragmentState.unhandledDynamicPropertyReads.size}`);
        logger_1.default.info(`Dynamic writes patched: ${p.patchedWrites}, remaining unpatched: ${solver.fragmentState.unhandledDynamicPropertyWrites.size}`);
        logger_1.default.info(`Modules analyzed statically but not dynamically: ${p.modulesNotInHints}, dynamically but not statically: ${p.modulesNotAnalyzed}`);
        logger_1.default.info(`Functions analyzed statically but not dynamically: ${p.functionsNotVisited}/${solver.globalState.functionInfos.size}`);
        logger_1.default.info(`Tokens not found: ${p.tokensNotFound}`);
        logger_1.default.info(`Unused hints: ${p.unusedHints}/${p.totalHints}`);
      }
    };
    exports.Patching = Patching;
  }
});

// lib/approx/hints.js
var require_hints = __commonJS({
  "lib/approx/hints.js"(exports) {
    "use strict";
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Hints = void 0;
    var util_1 = require_util();
    var patching_1 = require_patching();
    var fs_1 = __require("fs");
    var files_1 = require_files();
    var logger_1 = __importDefault(require_logger());
    var Hints = class {
      static {
        __name(this, "Hints");
      }
      modules = [];
      moduleIndex = /* @__PURE__ */ new Map();
      functions = /* @__PURE__ */ new Set();
      reads = /* @__PURE__ */ new Map();
      writes = /* @__PURE__ */ new Map();
      requires = /* @__PURE__ */ new Map();
      evals = /* @__PURE__ */ new Map();
      addModule(m) {
        return (0, util_1.getOrSet)(this.moduleIndex, m, () => {
          this.modules.push(m);
          return this.modules.length - 1;
        });
      }
      addFunction(f) {
        this.functions.add(f);
      }
      addReadHint(h) {
        if (patching_1.APPROX_READ)
          (0, util_1.mapArrayAddNoDuplicates)(h.loc, h, this.reads, (v1, v2) => v1.prop === v2.prop && v1.valLoc === v2.valLoc && v1.valType === v2.valType);
      }
      addWriteHint(h) {
        if (patching_1.APPROX_WRITE)
          (0, util_1.mapArrayAddNoDuplicates)(h.loc, h, this.writes, (v1, v2) => v1.type === v2.type && v1.baseLoc === v2.baseLoc && v1.baseType === v2.baseType && v1.prop === v2.prop && v1.valLoc === v2.valLoc && v1.valType === v2.valType);
      }
      addRequireHint(h) {
        (0, util_1.mapArrayAddNoDuplicates)(h.loc, h, this.requires, (v1, v2) => v1.str === v2.str);
      }
      addEvalHint(h) {
        (0, util_1.mapArrayAddNoDuplicates)(h.loc, h, this.evals, (v1, v2) => v1.str === v2.str);
      }
      add(newHints) {
        const moduleReindex = /* @__PURE__ */ new Map();
        for (const [i, s] of newHints.modules.entries())
          moduleReindex.set(i, this.addModule(s));
        const convert = /* @__PURE__ */ __name((loc) => `${moduleReindex.get(parseInt(loc))}${loc.substring(loc.indexOf(":"))}`, "convert");
        for (const f of newHints.functions)
          this.addFunction(convert(f));
        for (const { loc, prop, valLoc, valType } of newHints.reads) {
          this.addReadHint({
            loc: convert(loc),
            prop,
            valLoc: convert(valLoc),
            valType
          });
        }
        for (const { type, loc, baseLoc, baseType, prop, valLoc, valType } of newHints.writes) {
          this.addWriteHint({
            type,
            loc: convert(loc),
            baseLoc: convert(baseLoc),
            baseType,
            prop,
            valLoc: convert(valLoc),
            valType
          });
        }
        for (const { loc, str } of newHints.requires)
          this.addRequireHint({
            loc: convert(loc),
            str
          });
        for (const { loc, str } of newHints.evals)
          this.addEvalHint({
            loc: convert(loc),
            str
          });
      }
      toJSON() {
        return {
          modules: this.modules,
          functions: Array.from(this.functions),
          reads: Array.from(this.reads.values()).flat(),
          writes: Array.from(this.writes.values()).flat(),
          requires: Array.from(this.requires.values()).flat(),
          evals: Array.from(this.evals.values()).flat()
        };
      }
      saveToFile(file) {
        const fd = (0, fs_1.openSync)(file, "w");
        (0, files_1.writeStreamedStringify)(this.toJSON(), fd);
        (0, fs_1.closeSync)(fd);
        logger_1.default.info(`Approximate interpretation hints written to ${file}`);
      }
      clearHints() {
        this.reads.clear();
        this.writes.clear();
        this.requires.clear();
        this.evals.clear();
      }
    };
    exports.Hints = Hints;
  }
});

export {
  require_parser,
  require_patching,
  require_hints
};
//# sourceMappingURL=chunk-VD62II65.js.map
