import { promises } from 'node:fs';
import process from 'node:process';
import { d as defineCommand, e as extendsArgs, a as dotEnvArgs, b as legacyRootDirArgs, l as logLevelArgs, c as cwdArgs } from '../shared/nuxi.C0YEEVs2.mjs';
import { d as defu } from '../shared/nuxi.D2_bzAv0.mjs';
import { c as createApp, l as lazyEventHandler, e as eventHandler, t as toNodeListener } from '../shared/nuxi.CTyTlDmo.mjs';
import { l as listen } from '../shared/nuxi.yPqsj7vw.mjs';
import { o as overrideEnv } from '../shared/nuxi.C_u-rG9b.mjs';
import { c as clearDir } from '../shared/nuxi.CrvQqJcE.mjs';
import { l as loadKit } from '../shared/nuxi.BiWTNJI4.mjs';
import { l as logger } from '../shared/nuxi.DQjfoGl0.mjs';
import { r as resolve, j as join } from '../shared/nuxi.Do0aYBCO.mjs';
import 'node:crypto';
import 'node:path';
import 'node:tty';
import 'node:url';
import '../shared/nuxi.QWnQy_ku.mjs';
import 'node:http';
import 'node:https';
import 'node:util';
import 'node:net';
import 'node:os';
import 'node:fs/promises';
import '../shared/nuxi.BAGoDD49.mjs';
import 'http';
import 'https';
import 'node:child_process';
import 'crypto';
import '../shared/nuxi.BLb4POFS.mjs';
import 'node:assert';
import 'node:v8';

const analyze = defineCommand({
  meta: {
    name: "analyze",
    description: "Build nuxt and analyze production bundle (experimental)"
  },
  args: {
    ...cwdArgs,
    ...logLevelArgs,
    ...legacyRootDirArgs,
    ...dotEnvArgs,
    ...extendsArgs,
    name: {
      type: "string",
      description: "Name of the analysis",
      default: "default",
      valueHint: "name"
    },
    serve: {
      type: "boolean",
      description: "Serve the analysis results",
      negativeDescription: "Skip serving the analysis results",
      default: true
    }
  },
  async run(ctx) {
    overrideEnv("production");
    const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
    const name = ctx.args.name || "default";
    const slug = name.trim().replace(/[^\w-]/g, "_");
    const startTime = Date.now();
    const { loadNuxt, buildNuxt } = await loadKit(cwd);
    const nuxt = await loadNuxt({
      cwd,
      dotenv: {
        cwd,
        fileName: ctx.args.dotenv
      },
      overrides: defu(ctx.data?.overrides, {
        ...ctx.args.extends && { extends: ctx.args.extends },
        build: {
          analyze: {
            enabled: true
          }
        },
        vite: {
          build: {
            rollupOptions: {
              output: {
                chunkFileNames: "_nuxt/[name].js",
                entryFileNames: "_nuxt/[name].js"
              }
            }
          }
        },
        logLevel: ctx.args.logLevel
      })
    });
    const analyzeDir = nuxt.options.analyzeDir;
    const buildDir = nuxt.options.buildDir;
    const outDir = nuxt.options.nitro.output?.dir || join(nuxt.options.rootDir, ".output");
    nuxt.options.build.analyze = defu(nuxt.options.build.analyze, {
      filename: join(analyzeDir, "client.html")
    });
    await clearDir(analyzeDir);
    await buildNuxt(nuxt);
    const endTime = Date.now();
    const meta = {
      name,
      slug,
      startTime,
      endTime,
      analyzeDir,
      buildDir,
      outDir
    };
    await nuxt.callHook("build:analyze:done", meta);
    await promises.writeFile(
      join(analyzeDir, "meta.json"),
      JSON.stringify(meta, null, 2),
      "utf-8"
    );
    logger.info(`Analyze results are available at: \`${analyzeDir}\``);
    logger.warn("Do not deploy analyze results! Use `nuxi build` before deploying.");
    if (ctx.args.serve !== false && !process.env.CI) {
      const app = createApp();
      const serveFile = (filePath) => lazyEventHandler(async () => {
        const contents = await promises.readFile(filePath, "utf-8");
        return eventHandler((event) => {
          event.node.res.end(contents);
        });
      });
      logger.info("Starting stats server...");
      app.use("/client", serveFile(join(analyzeDir, "client.html")));
      app.use("/nitro", serveFile(join(analyzeDir, "nitro.html")));
      app.use(
        eventHandler(
          () => `<!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="utf-8">
        <title>Nuxt Bundle Stats (experimental)</title>
        </head>
          <h1>Nuxt Bundle Stats (experimental)</h1>
          <ul>
            <li>
              <a href="/nitro">Nitro server bundle stats</a>
            </li>
            <li>
              <a href="/client">Client bundle stats</a>
            </li>
          </ul>
        </html>
      `
        )
      );
      await listen(toNodeListener(app));
    }
  }
});

export { analyze as default };
