// esbuild has a bug in its sourcemap chaining logic. When it bundles the host
// app and encounters @bigbinary packages built with Rollup (which code-splits
// shared code into chunks like lodash-CAzW54WT.js, slicedToArray-BcL7fKuL.js),
// esbuild tries to chain through the upstream .map files. During this chaining,
// it corrupts source indices in the mappings — causing code from one package
// file (e.g. FinderModal/Body.jsx) to be attributed to a completely unrelated
// host app file (e.g. apis/s3.js). The line/column numbers are correct, but
// they point to the wrong file. This is a known class of esbuild issues
// (evanw/esbuild#3553, evanw/esbuild#3460).
//
// To work around this, we strip `//# sourceMappingURL=...` comments from
// @bigbinary package files before esbuild sees them, preventing it from
// attempting the broken chaining. After the build, `fixSourcemaps` in utils.js
// correctly re-composes sourcemaps using @jridgewell/remapping.
//
// Files handled by other onLoad plugins (e.g. preval handles i18n.js) are
// skipped since esbuild only allows one onLoad handler per file — those plugins
// strip the comment themselves.

/* eslint-disable @bigbinary/neeto/no-dangling-constants */
const fs = require("fs").promises;

const SKIP_RE = /(v2\/)?initializers\/i18n\.js$/;
const SOURCEMAP_URL_RE = /\/\/[#@] sourceMappingURL=[^\n]+/gm;

const stripSourcemapsPlugin = () => ({
  name: "strip-node-modules-sourcemaps",
  setup(build) {
    build.onLoad(
      { filter: /node_modules\/@bigbinary\/.*\.js$/ },
      async args => {
        if (SKIP_RE.test(args.path)) return null;

        const contents = await fs.readFile(args.path, "utf8");
        if (!SOURCEMAP_URL_RE.test(contents)) return null;

        return {
          contents: contents.replace(SOURCEMAP_URL_RE, ""),
          loader: "js",
        };
      }
    );
  },
});

module.exports = { stripSourcemapsPlugin };
