import fs from "fs";
import * as colors from "kleur/colors";
import { polyfill } from "@astropub/webapi";
import { performance } from "perf_hooks";
import vite from "../vite.js";
import { createVite } from "../create-vite.js";
import { debug, defaultLogOptions, info, levels, timerMessage, warn } from "../logger.js";
import { createRouteManifest } from "../ssr/routing.js";
import { generateSitemap } from "../ssr/sitemap.js";
import { collectPagesData } from "./page-data.js";
import { build as scanBasedBuild } from "./scan-based-build.js";
import { staticBuild } from "./static-build.js";
async function build(config, options = { logging: defaultLogOptions }) {
  polyfill(globalThis, {
    exclude: "window document"
  });
  const builder = new AstroBuilder(config, options);
  await builder.build();
}
class AstroBuilder {
  constructor(config, options) {
    this.mode = "production";
    this.routeCache = {};
    if (!config.buildOptions.site && config.buildOptions.sitemap !== false) {
      warn(options.logging, "config", `Set "buildOptions.site" to generate correct canonical URLs and sitemap`);
    }
    if (options.mode)
      this.mode = options.mode;
    this.config = config;
    const port = config.devOptions.port;
    this.logging = options.logging;
    this.origin = config.buildOptions.site ? new URL(config.buildOptions.site).origin : `http://localhost:${port}`;
    this.manifest = createRouteManifest({ config }, this.logging);
  }
  async build() {
    const { logging, origin } = this;
    const timer = {};
    timer.init = performance.now();
    timer.viteStart = performance.now();
    const viteConfig = await createVite(vite.mergeConfig({
      mode: this.mode,
      server: {
        hmr: { overlay: false },
        middlewareMode: "ssr"
      }
    }, this.config.vite || {}), { astroConfig: this.config, logging });
    this.viteConfig = viteConfig;
    const viteServer = await vite.createServer(viteConfig);
    this.viteServer = viteServer;
    debug(logging, "build", timerMessage("Vite started", timer.viteStart));
    timer.loadStart = performance.now();
    const { assets, allPages } = await collectPagesData({
      astroConfig: this.config,
      logging: this.logging,
      manifest: this.manifest,
      origin,
      routeCache: this.routeCache,
      viteServer: this.viteServer
    });
    debug(logging, "build", timerMessage("All pages loaded", timer.loadStart));
    const pageNames = [];
    timer.buildStart = performance.now();
    if (this.config.buildOptions.experimentalStaticBuild) {
      await staticBuild({
        allPages,
        astroConfig: this.config,
        logging: this.logging,
        origin: this.origin,
        pageNames,
        routeCache: this.routeCache,
        viteConfig: this.viteConfig
      });
    } else {
      await scanBasedBuild({
        allPages,
        astroConfig: this.config,
        logging: this.logging,
        origin: this.origin,
        pageNames,
        routeCache: this.routeCache,
        viteConfig: this.viteConfig,
        viteServer: this.viteServer
      });
    }
    debug(logging, "build", timerMessage("Vite build finished", timer.buildStart));
    timer.assetsStart = performance.now();
    Object.keys(assets).map((k) => {
      if (!assets[k])
        return;
      const filePath = new URL(`file://${k}`);
      fs.mkdirSync(new URL("./", filePath), { recursive: true });
      fs.writeFileSync(filePath, assets[k], "utf8");
      delete assets[k];
    });
    debug(logging, "build", timerMessage("Additional assets copied", timer.assetsStart));
    timer.sitemapStart = performance.now();
    if (this.config.buildOptions.sitemap && this.config.buildOptions.site) {
      const sitemap = generateSitemap(pageNames.map((pageName) => new URL(`/${pageName}`, this.config.buildOptions.site).href));
      const sitemapPath = new URL("./sitemap.xml", this.config.dist);
      await fs.promises.mkdir(new URL("./", sitemapPath), { recursive: true });
      await fs.promises.writeFile(sitemapPath, sitemap, "utf8");
    }
    debug(logging, "build", timerMessage("Sitemap built", timer.sitemapStart));
    await viteServer.close();
    if (logging.level && levels[logging.level] <= levels["info"]) {
      await this.printStats({ logging, timeStart: timer.init, pageCount: pageNames.length });
    }
  }
  async printStats({ logging, timeStart, pageCount }) {
    debug(logging, "");
    const buildTime = performance.now() - timeStart;
    const total = buildTime < 750 ? `${Math.round(buildTime)}ms` : `${(buildTime / 1e3).toFixed(2)}s`;
    const perPage = `${Math.round(buildTime / pageCount)}ms`;
    info(logging, "build", `${pageCount} pages built in ${colors.bold(total)} ${colors.dim(`(${perPage}/page)`)}`);
    info(logging, "build", `\u{1F680} ${colors.cyan(colors.bold("Done"))}`);
  }
}
export {
  build as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvYnVpbGQvaW5kZXgudHMiXSwKICAibW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