import { readFileSync as b } from "fs";
import { resolve as h } from "path";
const g = (l) => {
  const r = l.join("|");
  return new RegExp(`^(${r})(\\/.*)?$`);
}, y = ({
  externals: l
}) => {
  const r = g(l);
  return {
    name: "externalize",
    setup(e) {
      e.onResolve({ filter: r }, (t) => ({
        path: t.path,
        namespace: "externalize"
      })), e.onLoad({ filter: r }, () => ({
        contents: ""
      }));
    }
  };
}, z = (l) => {
  const r = "/@id/", e = new RegExp(
    `${r}(${l.join("|")})`,
    "g"
  );
  return {
    name: "vite-plugin-remove-prefix",
    transform: (t) => e.test(t) ? t.replace(
      e,
      (p, c) => c
    ) : t
  };
}, O = (l) => {
  const { externals: r } = l;
  return {
    name: "vite-plugin-externalize",
    enforce: "pre",
    apply: "serve",
    config: (e) => {
      var t;
      const p = { ...e };
      return p.optimizeDeps && p.optimizeDeps.esbuildOptions && ((t = p.optimizeDeps.esbuildOptions).plugins ?? (t.plugins = []), p.optimizeDeps.esbuildOptions.plugins.push(
        y({ externals: r })
      )), p;
    },
    configResolved: (e) => {
      if (e.optimizeDeps && e.optimizeDeps.include) {
        const p = e.optimizeDeps.include.filter(
          (c) => !r.includes(c)
        );
        e.optimizeDeps.include = p;
      }
      e.optimizeDeps && (e.optimizeDeps.exclude = e.optimizeDeps.exclude || [], e.optimizeDeps.exclude.push(...r));
      const t = z(r);
      e.plugins.push(t);
    },
    // Supresses the following warning:
    // Failed to resolve import [dependency] from [sourceFile]. Does the file exist?
    resolveId: (e) => r.includes(e) ? { id: e, external: !0 } : null,
    // Supresses the following warning:
    // The following dependencies are imported but could not be resolved:
    // [dependency] (imported by [sourceFile])
    load: (e) => r.includes(e) ? "export default {};" : null
  };
}, k = "@feedmepos/mf-", P = async (l, { command: r, mode: e }, t = {}) => {
  var f, j, x;
  const p = JSON.parse(
    b(h(process.cwd(), "package.json"), "utf-8")
  ), c = Object.keys(p.dependencies).filter((s) => s.startsWith(k)).reduce((s, i) => (s[i] = p.dependencies[i], s), {});
  (f = t.includeFmmfPackages) == null || f.forEach((s) => {
    c[s] = p.dependencies[s] ?? "latest";
  }), (j = t.excludeFmmfPackages) == null || j.forEach((s) => {
    delete c[s];
  });
  const a = {
    "@feedmepos/ui-library": "https://cdn.jsdelivr.net/npm/@feedmepos/ui-library@latest/dist/feedmepos-ui-library.js",
    // Conditionally externalize core packages to share business logic
    ...t.externalizeCore ? {
      "@feedmepos/core": "https://cdn.jsdelivr.net/npm/@feedmepos/core@latest/es/index.js",
      "@feedmepos/core/fn": "https://cdn.jsdelivr.net/npm/@feedmepos/core@latest/es/fn.js",
      "@feedmepos/core/entity": "https://cdn.jsdelivr.net/npm/@feedmepos/core@latest/es/entity.js",
      "@feedmepos/core/modules": "https://cdn.jsdelivr.net/npm/@feedmepos/core@latest/es/modules.js"
    } : {}
  }, o = {
    "@vue/devtools-api": "6.5.0/lib/esm/index.js",
    vue: "3.5.16/dist/vue.esm-browser.prod.min.js",
    "vue-router": "4.2.5/dist/vue-router.esm-browser.min.js",
    pinia: "2.1.7/+esm"
  };
  let m = [
    ...Object.keys(o),
    ...Object.keys(c),
    ...Object.keys(a)
  ];
  const n = { ...l };
  if (r == "build" && e.startsWith("fmmf") && (m = [
    ...Object.keys(c),
    ...Object.keys(o),
    ...Object.keys(a)
  ], n.build = {
    emptyOutDir: !0,
    lib: {
      entry: {
        app: h(process.cwd(), "src/app.ts")
        // Entry must export routers, FmApp, etc.
      },
      formats: ["es"]
      // ES module format for native browser import
    }
  }), n.plugins ?? (n.plugins = []), t.externalize) {
    const s = t.externalize === !0 ? m : t.externalize;
    n.plugins.push(O({ externals: s }));
  }
  n.build ?? (n.build = {}), (x = n.build).rollupOptions ?? (x.rollupOptions = {}), n.build.rollupOptions.external = m.concat(
    ...n.build.rollupOptions.external ?? []
  );
  const d = c;
  await Promise.all(
    Object.keys(d).map(async (s) => {
      const i = "latest";
      return d[s] = `https://cdn.jsdelivr.net/npm/${s}@${i}/dist/app.js`;
    })
  );
  const u = {
    imports: {
      // Microfrontend applications
      ...d,
      // Common dependencies (Vue ecosystem)
      ...Object.keys(o).reduce((s, i) => (s[i] = `https://cdn.jsdelivr.net/npm/${i}@${o[i]}`, s), {}),
      // Specific external packages (UI library, core packages)
      ...a
    },
    // Scopes allow different module resolution in specific contexts
    scopes: t.importMapScopes ?? {}
  };
  t.replaceFmmfPackages && Object.entries(t.replaceFmmfPackages).forEach(([s, i]) => {
    if (s.startsWith("@feedmepos/mf-") || s === "@feedmepos/ui-library")
      u.imports[s] = i;
    else
      throw new Error(`Invalid replaceFmmfPackages key: ${s}, must start with @feedmepos/mf-`);
  });
  const v = {
    name: "vite-plugin-feedme-microfrontend",
    enforce: "pre",
    // Run before other plugins
    config: async () => {
    },
    transformIndexHtml: {
      enforce: "pre",
      // Transform HTML early in the pipeline
      transform(s) {
        return {
          html: s,
          tags: [
            // Inject the importmap script tag containing module mappings
            {
              tag: "script",
              attrs: {
                type: "importmap"
                // Special script type for ES module imports
              },
              children: JSON.stringify(u, null, 2),
              injectTo: "head-prepend"
              // Add at the beginning of <head>
            },
            // Inject es-module-shims for browsers without native importmap support
            {
              tag: "script",
              attrs: {
                src: "https://cdn.jsdelivr.net/npm/es-module-shims@1.8.0/dist/es-module-shims.min.js"
              },
              injectTo: "head-prepend"
              // Load before importmap
            }
          ]
        };
      }
    }
  };
  return n.plugins.push(v), n;
};
export {
  P as fmmfVitePresent
};
