import slash from "slash";
import {fileURLToPath} from "url";
import {createRequire} from "module";
import vite from "./vite.js";
import astroVitePlugin from "../vite-plugin-astro/index.js";
import astroPostprocessVitePlugin from "../vite-plugin-astro-postprocess/index.js";
import markdownVitePlugin from "../vite-plugin-markdown/index.js";
import jsxVitePlugin from "../vite-plugin-jsx/index.js";
import fetchVitePlugin from "../vite-plugin-fetch/index.js";
import {getPackageJSON, parseNpmName} from "./util.js";
const require2 = createRequire(import.meta.url);
const ALWAYS_EXTERNAL = new Set(["@sveltejs/vite-plugin-svelte", "micromark-util-events-to-acorn", "estree-util-value-to-estree", "shorthash", "unified"]);
process.env.TAILWIND_MODE = "watch";
async function createVite(inlineConfig, {astroConfig, logging, devServer}) {
  const packageJSON = await getPackageJSON(astroConfig.projectRoot) || {};
  const userDeps = Object.keys((packageJSON == null ? void 0 : packageJSON.dependencies) || {});
  const userDevDeps = Object.keys((packageJSON == null ? void 0 : packageJSON.devDependencies) || {});
  const {external, noExternal} = await viteSSRDeps([...userDeps, ...userDevDeps]);
  let viteConfig = {
    cacheDir: fileURLToPath(new URL("./node_modules/.vite/", astroConfig.projectRoot)),
    clearScreen: false,
    logLevel: "error",
    optimizeDeps: {
      entries: ["src/**/*"],
      include: [...userDeps]
    },
    plugins: [
      astroVitePlugin({config: astroConfig, devServer}),
      markdownVitePlugin({config: astroConfig, devServer}),
      jsxVitePlugin({config: astroConfig, logging}),
      astroPostprocessVitePlugin({config: astroConfig, devServer}),
      fetchVitePlugin()
    ],
    publicDir: fileURLToPath(astroConfig.public),
    root: fileURLToPath(astroConfig.projectRoot),
    server: {
      hmr: process.env.NODE_ENV === "test" || process.env.NODE_ENV === "production" ? false : void 0,
      proxy: {}
    },
    ssr: {
      external: [...external, ...ALWAYS_EXTERNAL],
      noExternal: [...noExternal]
    }
  };
  for (const name of astroConfig.renderers) {
    try {
      const {default: renderer} = await import(name);
      if (!renderer)
        continue;
      if (renderer.viteConfig) {
        if (typeof renderer.viteConfig !== "function") {
          throw new Error(`${name}: viteConfig(options) must be a function! Got ${typeof renderer.viteConfig}.`);
        }
        const rendererConfig = await renderer.viteConfig({mode: inlineConfig.mode, command: inlineConfig.mode === "production" ? "build" : "serve"});
        viteConfig = vite.mergeConfig(viteConfig, rendererConfig);
      }
    } catch (err) {
      throw new Error(`${name}: ${err}`);
    }
  }
  viteConfig = vite.mergeConfig(viteConfig, astroConfig.vite || {});
  viteConfig = vite.mergeConfig(viteConfig, inlineConfig);
  return viteConfig;
}
async function viteSSRDeps(deps) {
  const skip = new Set();
  const external = new Set();
  const noExternal = new Set();
  async function sortPkg(spec) {
    if (external.has(spec) || noExternal.has(spec) || skip.has(spec))
      return;
    const pkg = parseNpmName(spec);
    if (!pkg) {
      skip.add(spec);
      return;
    }
    try {
      const moduleLoc = require2.resolve(spec);
      if (!moduleLoc) {
        skip.add(spec);
        return;
      }
      let cwd = new URL("../", `file://${slash(moduleLoc)}/`);
      let packageJSON = await getPackageJSON(cwd);
      while (!packageJSON) {
        const next = new URL("../", cwd);
        if (next.href === cwd.href)
          return;
        cwd = next;
        packageJSON = await getPackageJSON(cwd);
      }
      if (!packageJSON) {
        skip.add(spec);
        return;
      }
      if (packageJSON.type === "module") {
        noExternal.add(spec);
      } else {
        external.add(spec);
      }
      await Promise.all(Object.keys(packageJSON.dependencies || {}).map(sortPkg));
    } catch (err) {
      skip.add(spec);
      return;
    }
  }
  await Promise.all(deps.map(sortPkg));
  const externalSorted = [...external];
  externalSorted.sort((a, b) => a.localeCompare(b, "en-us", {numeric: true}));
  const noExternalSorted = [...noExternal];
  noExternalSorted.sort((a, b) => a.localeCompare(b, "en-us", {numeric: true}));
  return {
    external: new Set([...externalSorted]),
    noExternal: new Set([...noExternalSorted])
  };
}
export {
  createVite
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL2NvcmUvY3JlYXRlLXZpdGUudHMiXSwKICAibWFwcGluZ3MiOiAiQUFJQTtB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