heximon 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { _ as StdoutRedirect, d as RegistryAccessStatus, f as CommandOutput, g as CliEntry, i as createCommand, m as PromptRefusedError, n as ProjectRoot, p as CommandFailure, r as CreateDefaults, t as skillsCommand, u as RegistryAccess, v as CliDiagnosticCode, x as PromptCancelledError, y as CliDiagnostics } from "./skills-command-Czsv_c74.mjs";
2
+ import { _ as StdoutRedirect, d as RegistryAccessStatus, f as CommandOutput, g as CliEntry, i as createCommand, m as PromptRefusedError, n as ProjectRoot, p as CommandFailure, r as CreateDefaults, t as skillsCommand, u as RegistryAccess, v as CliDiagnosticCode, x as PromptCancelledError, y as CliDiagnostics } from "./skills-command-BiuBtTbZ.mjs";
3
3
  import { createRequire, register } from "node:module";
4
4
  import { cancel, confirm, intro, isCancel, log, outro, select, spinner } from "@clack/prompts";
5
5
  import process from "node:process";
6
6
  import { defineCommand } from "citty";
7
7
  import { existsSync, globSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
8
- import { AstNodeType, CompileEnvironment, CompileMode, DeployPlatform, DiagnosticCode, DiagnosticRenderMode, DiagnosticRenderer, DiagnosticSeverity, ImportKind, ReexportIndex, RuntimeConfigFile, RuntimeSingletons, StartReasonKind, StartupBaselineFile, StartupChangeKind, StartupSizeBudget, StartupSizeChangeKind, StartupSizeMeasure, TerminalStyle, UpgradeBaselineFile } from "@heximon/compiler";
8
+ import { AstNodeType, CompileEnvironment, CompileMode, DeployPlatform, DiagnosticCode, DiagnosticRenderMode, DiagnosticRenderer, DiagnosticSeverity, ImportKind, ReexportIndex, RuntimeConfigFile, RuntimeSingletons, StartReasonKind, StartReportRole, StartupBaselineFile, StartupChangeKind, StartupSizeBudget, StartupSizeChangeKind, StartupSizeMeasure, TerminalStyle, UpgradeBaselineFile } from "@heximon/compiler";
9
9
  import { spawn } from "node:child_process";
10
10
  import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
11
11
  import tab from "@bomb.sh/tab/citty";
@@ -46,7 +46,12 @@ const CheckDiagnosticCode = {
46
46
  * `--startup` in a Nuxt app whose target record (`.heximon/nuxt-target.json`) is missing, has a format
47
47
  * version that the command does not read, cannot be read, or is older than a Nuxt config file of the app.
48
48
  */
49
- NuxtTargetUnavailable: "check.nuxt-target-unavailable"
49
+ NuxtTargetUnavailable: "check.nuxt-target-unavailable",
50
+ /**
51
+ * An info: a Nitro or Nuxt host compiled for the Node default, because the command could not apply its Nitro
52
+ * preset and the sidecar declares no `platform`.
53
+ */
54
+ HostTargetDefault: "check.host-target-default"
50
55
  };
51
56
  /** Where the deploy target of a `heximon check --startup` compile comes from. */
52
57
  const StartupTargetSource = {
@@ -59,6 +64,15 @@ const StartupTargetSource = {
59
64
  /** The Nitro preset that the last production Nuxt run recorded in `.heximon/nuxt-target.json`. */
60
65
  NuxtRun: "nuxt-run"
61
66
  };
67
+ /** Why `heximon check --startup` has no size for the chunk of a hostless app. */
68
+ const CheckHostlessSizeUnavailable = {
69
+ /** The build record does not name the generated files of its chunks. */
70
+ NoChunkRecord: "no-chunk-record",
71
+ /** No chunk of the build holds the boot file of the app. The build is older than the compile. */
72
+ NoChunk: "no-chunk",
73
+ /** The size walk of the server entry does not reach the chunk. */
74
+ NotReached: "not-reached"
75
+ };
62
76
  //#endregion
63
77
  //#region src/compile-diagnostics.ts
64
78
  /**
@@ -190,1897 +204,2132 @@ var ConfigSidecar = class ConfigSidecar {
190
204
  }
191
205
  };
192
206
  //#endregion
193
- //#region src/nuxt-target-file.ts
207
+ //#region src/nitro-static-config.ts
194
208
  /**
195
- * Reads `.heximon/nuxt-target.json`, which `@heximon/nuxt` writes on each production Nuxt run (a build, or
196
- * `nuxt prepare`): the Nitro preset and the source directories of that run. The command never runs the Nuxt
197
- * config, so the record is the only source of the deploy target of a Nuxt app. It shows the last run: a record
198
- * older than one of the Nuxt config files that the run loaded is refused.
209
+ * Reads the Nitro options that choose the graph of a build (`preset`, `serverDir`, `scanDirs`) from the source of
210
+ * the config files, without running them. A config file is project code: it can read the environment, call a
211
+ * service, or write a file. So the files are parsed with oxc, and the reader ACCEPTS only a shape that it can
212
+ * prove. Everything else is "computed", and the command then refuses or asks for an explicit input.
213
+ *
214
+ * Accepted in `nitro.config.*`: `export default {…}`, or `export default defineNitroConfig({…})` with
215
+ * `defineNitroConfig` imported from `nitro` or `nitro/config`, or either one through ONE top-level `const` that is
216
+ * never assigned again. The object has no spread. A `$production` or `$env.production` overlay applies; the other
217
+ * environments do not, because the command always compiles for production.
218
+ *
219
+ * Accepted in `vite.config.*`: ONE call of the Nitro plugin of `nitro/vite` (a named or a namespace import), as a
220
+ * direct element of the `plugins` array literal of the exported config (`export default {…}`, or `defineConfig`
221
+ * from `vite` over one, or either through one `const`). No ternary, no `&&`, no spread, no helper, no function.
222
+ *
223
+ * The precedence is Nitro's own: the options of the Vite config, then `NITRO_PRESET` / `SERVER_PRESET`, then the
224
+ * Nitro config file.
199
225
  */
200
- var NuxtTargetFile = class NuxtTargetFile {
201
- /** The format version that this reader knows. `@heximon/nuxt` writes the same number. */
202
- static formatVersion = 1;
203
- /** The file name of the record, in the `.heximon` output directory of the app. */
204
- static fileName = "nuxt-target.json";
205
- /** The path of the record, relative to the app root. */
206
- static relativePath = `.heximon/${NuxtTargetFile.fileName}`;
207
- /** The types directory of Nuxt when the record names none: the default `buildDir`. */
208
- static defaultTypesDirectory = ".nuxt";
209
- /** The tsconfig files that Nuxt generates in its types directory, weakest first: the server one wins. */
210
- static generatedTsconfigNames = ["tsconfig.json", "tsconfig.server.json"];
226
+ var NitroStaticConfig = class NitroStaticConfig {
227
+ static nitroConfigNames = [
228
+ "nitro.config.ts",
229
+ "nitro.config.mts",
230
+ "nitro.config.js",
231
+ "nitro.config.mjs"
232
+ ];
233
+ static viteConfigNames = [
234
+ "vite.config.ts",
235
+ "vite.config.mts",
236
+ "vite.config.js",
237
+ "vite.config.mjs"
238
+ ];
239
+ /** Nuxt creates its own Nitro, which a static read of these files cannot describe. */
240
+ static nuxtConfigNames = [
241
+ "nuxt.config.ts",
242
+ "nuxt.config.mts",
243
+ "nuxt.config.js",
244
+ "nuxt.config.mjs"
245
+ ];
246
+ /** The package names a Nuxt app depends on: the release, or the nightly. */
247
+ static nuxtPackages = ["nuxt", "nuxt-nightly"];
248
+ /** The extensions c12 tries for a config file, scripts and data formats. */
249
+ static configExtensions = [
250
+ ".js",
251
+ ".ts",
252
+ ".mjs",
253
+ ".cjs",
254
+ ".mts",
255
+ ".cts",
256
+ ".json",
257
+ ".jsonc",
258
+ ".json5",
259
+ ".yaml",
260
+ ".yml",
261
+ ".toml"
262
+ ];
263
+ /** The exact name of the rc file c12 reads for Nitro. */
264
+ static resourceFileName = ".nitrorc";
265
+ /** The expression nodes that only wrap another expression. */
266
+ static wrapperTypes = [
267
+ "TSAsExpression",
268
+ "TSSatisfiesExpression",
269
+ "TSNonNullExpression",
270
+ "TSTypeAssertion",
271
+ "ParenthesizedExpression"
272
+ ];
273
+ /** The module that exports the Nitro Vite plugin. */
274
+ static nitroVitePackage = "nitro/vite";
275
+ /** The key of the Nitro config that holds the options of the Heximon compile. */
276
+ static heximonSection = "heximon";
277
+ /** The helper that returns its Nitro config unchanged, and where it is imported from. */
278
+ static nitroConfigHelper = {
279
+ name: "defineNitroConfig",
280
+ packages: ["nitro", "nitro/config"]
281
+ };
282
+ /** The helper that returns its Vite config unchanged, and where it is imported from. */
283
+ static viteConfigHelper = {
284
+ name: "defineConfig",
285
+ packages: ["vite", "vite-plus"]
286
+ };
211
287
  /**
212
- * Read the record of a Nuxt app.
213
- *
214
- * @param rootDir - The app root.
215
- * @returns The target, or why the record cannot be used.
288
+ * @param rootDir - The project root.
289
+ * @param environment - The environment to read `NITRO_PRESET` from; the process environment by default.
216
290
  */
217
- static read(rootDir) {
218
- const file = join(rootDir, NuxtTargetFile.relativePath);
219
- const unavailable = (message) => ({
220
- kind: "unavailable",
221
- file,
222
- message
223
- });
224
- if (!existsSync(file)) return unavailable(`This Nuxt app has no record of its deploy target (${NuxtTargetFile.relativePath}).`);
225
- let record;
226
- try {
227
- record = JSON.parse(readFileSync(file, "utf8"));
228
- } catch {
229
- return unavailable(`The record of the deploy target (${file}) is not valid JSON.`);
230
- }
231
- const content = typeof record === "object" && record !== null ? record : {};
232
- if (content.version !== NuxtTargetFile.formatVersion) return unavailable(`The record of the deploy target (${file}) has the format version ${JSON.stringify(content.version)}, and this command reads version ${NuxtTargetFile.formatVersion}.`);
233
- const isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
234
- if (typeof content.preset !== "string" || content.preset.length === 0 || !isStringList(content.sourceDirectories) || !isStringList(content.configFiles) || content.typesDir !== void 0 && typeof content.typesDir !== "string") return unavailable(`The record of the deploy target (${file}) does not have the expected fields.`);
235
- const typesDirectory = typeof content.typesDir === "string" ? content.typesDir : NuxtTargetFile.defaultTypesDirectory;
236
- const recordedAt = statSync(file).mtimeMs;
237
- const changed = content.configFiles.map((path) => resolve(rootDir, path)).find((path) => !existsSync(path) || statSync(path).mtimeMs > recordedAt);
238
- if (changed !== void 0) return unavailable(`The record of the deploy target (${file}) is older than the Nuxt config file ${changed}, or that file is gone, so the record can hold an old target.`);
291
+ static read(rootDir, environment = process.env) {
292
+ const find = (names) => names.map((name) => join(rootDir, name)).find((path) => existsSync(path));
293
+ const notAHost = {
294
+ isNitroHost: false,
295
+ preset: { kind: "none" },
296
+ serverDir: { kind: "none" },
297
+ scanDirs: { kind: "none" },
298
+ sourceDirectories: { kind: "none" }
299
+ };
300
+ if (NitroStaticConfig.isNuxtProject(rootDir)) return notAHost;
301
+ const configFiles = NitroStaticConfig.configFilesOf(rootDir);
302
+ const nitroFile = configFiles.length === 1 && NitroStaticConfig.nitroConfigNames.some((name) => join(rootDir, name) === configFiles[0]) ? configFiles[0] : void 0;
303
+ const viteFile = find(NitroStaticConfig.viteConfigNames);
304
+ const vite = viteFile === void 0 ? void 0 : NitroStaticConfig.readVite(viteFile);
305
+ const hasNitroSource = configFiles.length > 0 || vite?.usesNitroPlugin === true;
306
+ if (!hasNitroSource && !NitroStaticConfig.dependsOnNitro(rootDir)) return notAHost;
307
+ const viteSources = vite?.sources ?? [];
308
+ const fileSources = nitroFile === void 0 ? [] : NitroStaticConfig.readNitroConfig(nitroFile);
309
+ const hiddenSources = NitroStaticConfig.hiddenSources(rootDir, hasNitroSource, nitroFile === void 0 ? configFiles : []);
310
+ const all = [
311
+ ...viteSources,
312
+ ...fileSources,
313
+ ...hiddenSources
314
+ ];
315
+ const fromVite = NitroStaticConfig.scalar("preset", viteSources, true);
316
+ const fromEnvironment = environment["NITRO_PRESET"] || environment["SERVER_PRESET"];
317
+ const found = fromVite.kind !== "none" ? fromVite : fromEnvironment ? {
318
+ kind: "literal",
319
+ value: fromEnvironment
320
+ } : NitroStaticConfig.scalar("preset", [...fileSources, ...hiddenSources], true);
321
+ const unreadable = all.find((source) => source.kind === "unproven");
239
322
  return {
240
- kind: "found",
241
- target: {
242
- file,
243
- preset: content.preset,
244
- sourceDirectories: content.sourceDirectories.map((path) => resolve(rootDir, path)),
245
- generatedTsconfigFiles: NuxtTargetFile.generatedTsconfigNames.map((name) => join(typesDirectory, name))
246
- }
323
+ isNitroHost: true,
324
+ preset: unreadable !== void 0 && found.kind !== "computed" ? {
325
+ kind: "computed",
326
+ file: unreadable.file,
327
+ reason: unreadable.reason
328
+ } : NitroStaticConfig.withHidden(found, all, ["static", "extends"], ["defaultPreset"]),
329
+ serverDir: NitroStaticConfig.withHidden(NitroStaticConfig.scalar("serverDir", all), all, [], ["extends"]),
330
+ scanDirs: NitroStaticConfig.withHiddenList(NitroStaticConfig.list("scanDirs", all), all),
331
+ sourceDirectories: NitroStaticConfig.withHiddenList(NitroStaticConfig.list("sourceDirectories", NitroStaticConfig.sectionSources(NitroStaticConfig.heximonSection, all)), all)
247
332
  };
248
333
  }
249
- };
250
- //#endregion
251
- //#region src/project-compile-session.ts
252
- /**
253
- * The from-disk compile prologue every inspection command shares (`check`, `graph`, `routes`, `workflows`):
254
- * resolve the source directories, load the `heximon.config.ts` sidecar for the requested `$env`, derive the
255
- * platform compile strategy, and merge the plugin set the compile runs with.
256
- *
257
- * The `.env` cascade is deliberately NOT loaded here. Only `heximon routes` loads it (so a booted app and its
258
- * config sidecar read the environment `vp dev` would give them); the compile-only verbs must not pick up a
259
- * developer's `.env` just by inspecting a project. A caller that wants it loads it before calling
260
- * {@link open}, so the sidecar read still sees it.
261
- */
262
- var ProjectCompileSession = class ProjectCompileSession {
263
- /** The gitignored directory the compile anchors its generated paths at. */
264
- static outputDirectoryName = ".heximon";
265
- /** Why a check reports a topology failure: the build of the same project fails on it too. */
266
- static topologyFailureHint = "The sidecar declares `crossService`, so the build reads the cross-service subscription topology of the workspace and fails on the same error.";
267
- /** The absolute project root the compile runs against. */
268
- rootDir;
269
- /** The warm compiler — reused by a caller that also prunes or writes type verdicts. */
270
- compiler;
271
- /** The resolved sidecar, or `undefined` when the project ships none. */
272
- config;
273
- /** The absolute source directories to scan, or `undefined` for the compiler's own `<rootDir>/src`. */
274
- sourceDirectories;
275
- /** The absolute `.heximon/` directory the compile anchors its generated paths at. */
276
- outputDirectory;
277
- /** The compiler plugins the sidecar declares, merged with the platform strategy's own. */
278
- plugins;
279
- strategy;
280
- /** The `$env` name the sidecar was read for, which the member sidecars of the workspace scan share. */
281
- environment;
282
- /** The runtime config file the app compile checks and bakes in, or `undefined` when there is none. */
283
- runtimeConfig;
284
- /** The module aliases of a host build, which {@link compile} resolves, or `undefined` for none. */
285
- aliases;
286
- /** The output-relative files that another step writes into {@link outputDirectory}, which {@link write} keeps. */
287
- retainedOutput;
288
- constructor(options) {
289
- this.rootDir = options.rootDir;
290
- this.compiler = options.compiler;
291
- this.config = options.config;
292
- this.runtimeConfig = options.runtimeConfig;
293
- this.sourceDirectories = options.sourceDirectories;
294
- this.plugins = options.plugins;
295
- this.strategy = options.strategy;
296
- this.environment = options.environment;
297
- this.aliases = options.aliases;
298
- this.outputDirectory = join(options.rootDir, ProjectCompileSession.outputDirectoryName);
299
- this.retainedOutput = [NuxtTargetFile.fileName, ...options.retainedOutput ?? []];
334
+ /**
335
+ * The literal source directories of a Nitro host, or the first of `serverDir`, `scanDirs` and
336
+ * `heximon.sourceDirectories` that is computed. The build scans the union of the three, so the
337
+ * `heximon.sourceDirectories` join `scanDirs`.
338
+ *
339
+ * @param result - What {@link read} returned.
340
+ */
341
+ static sourceOptionsOf(result) {
342
+ for (const [option, value] of [
343
+ ["serverDir", result.serverDir],
344
+ ["scanDirs", result.scanDirs],
345
+ ["heximon.sourceDirectories", result.sourceDirectories]
346
+ ]) if (value.kind === "computed") return {
347
+ kind: "computed",
348
+ option,
349
+ file: value.file,
350
+ reason: value.reason
351
+ };
352
+ const scanDirs = [...result.scanDirs.kind === "literal" ? result.scanDirs.value : [], ...result.sourceDirectories.kind === "literal" ? result.sourceDirectories.value : []];
353
+ return {
354
+ kind: "literal",
355
+ ...result.serverDir.kind === "literal" ? { serverDir: result.serverDir.value } : {},
356
+ ...result.scanDirs.kind === "literal" || result.sourceDirectories.kind === "literal" ? { scanDirs } : {}
357
+ };
300
358
  }
301
359
  /**
302
- * Resolve one project's compile inputs.
360
+ * Whether the project is a Nuxt app: it has a `nuxt.config.*` file, or package.json lists `nuxt` (or
361
+ * `nuxt-nightly`) as a dependency. Nuxt creates its own Nitro, so {@link read} does not report such a project
362
+ * as a Nitro host, although it deploys through Nitro.
303
363
  *
304
- * @param options - The project root, the `$env` name, and the resolved source directories.
305
- * @returns The session the caller compiles through.
306
- * @throws CommandFailure with `cli.config-unreadable` when the sidecar throws.
364
+ * @param rootDir - The project root.
307
365
  */
308
- static async open(options) {
309
- const config = await ConfigSidecar.load(options.rootDir, options.environment);
310
- const strategy = NodeCompileSeam.resolveStrategy(config?.platform);
311
- return new ProjectCompileSession({
312
- rootDir: options.rootDir,
313
- compiler: new ProjectCompiler(),
314
- config,
315
- runtimeConfig: await RuntimeConfigLoader.load(options.rootDir, config, options.environment),
316
- sourceDirectories: options.sourceDirectories,
317
- plugins: NodeCompileSeam.mergePlugins(config?.plugins ?? [], strategy),
318
- strategy,
319
- environment: options.environment
320
- });
366
+ static isNuxtProject(rootDir) {
367
+ const manifest = NitroStaticConfig.manifestOf(rootDir);
368
+ const dependencies = manifest === void 0 || manifest === "invalid" ? {} : {
369
+ ...manifest.dependencies,
370
+ ...manifest.devDependencies
371
+ };
372
+ return NitroStaticConfig.nuxtConfigNames.some((name) => existsSync(join(rootDir, name))) || NitroStaticConfig.nuxtPackages.some((name) => name in dependencies);
321
373
  }
322
374
  /**
323
- * A session that compiles with the production inputs of a Nitro or Nuxt host: the strategy of its preset, the
324
- * Nitro host plugin, and the production sidecar. {@link open} reads only the sidecar, so it compiles a Nitro app
325
- * for Node whatever the preset is.
326
- *
327
- * @param options - The project root, the host inputs, the module aliases, and the source directories to scan
328
- * instead of the host's, when the caller has some.
329
- * @returns The session the caller compiles through.
375
+ * Sources of options that the project has but the reader cannot read: a `.nitrorc` file (in the project or the
376
+ * home directory), the `nitro` key of `package.json`, and a dependency on `nitro` when no config file or
377
+ * provable plugin call exists.
330
378
  */
331
- static forNitroHost(options) {
332
- const inputs = options.inputs;
333
- return new ProjectCompileSession({
334
- rootDir: options.rootDir,
335
- compiler: new ProjectCompiler(),
336
- config: inputs.config,
337
- runtimeConfig: inputs.runtimeConfig,
338
- sourceDirectories: options.sourceDirectories ?? inputs.sourceDirectories,
339
- plugins: inputs.plugins,
340
- strategy: inputs.strategy,
341
- environment: "production",
342
- aliases: options.aliases,
343
- ...inputs.retainedOutput === void 0 ? {} : { retainedOutput: inputs.retainedOutput }
379
+ static hiddenSources(rootDir, hasNitroSource, unreadFiles) {
380
+ const unproven = (reason) => ({
381
+ kind: "unproven",
382
+ file: join(rootDir, "package.json"),
383
+ reason
344
384
  });
385
+ const sources = [];
386
+ const resourceFile = [rootDir, homedir()].map((directory) => join(directory, NitroStaticConfig.resourceFileName)).find((path) => existsSync(path));
387
+ if (resourceFile !== void 0) sources.push(unproven(`the file ${resourceFile} sets Nitro options`));
388
+ if (unreadFiles.length > 0) sources.push(unproven(`the file ${unreadFiles[0]} sets Nitro options in a form the command does not read`));
389
+ const manifest = NitroStaticConfig.manifestOf(rootDir);
390
+ if (manifest === "invalid") sources.push(unproven("package.json is not valid JSON"));
391
+ else if (manifest !== void 0) {
392
+ if (manifest.nitro !== void 0) sources.push(unproven("the `nitro` key of package.json sets Nitro options"));
393
+ if (!hasNitroSource && NitroStaticConfig.dependsOnNitro(rootDir)) sources.push(unproven("the project depends on nitro, but no Nitro config file or Nitro Vite plugin call was found"));
394
+ }
395
+ return sources;
345
396
  }
346
397
  /**
347
- * Run the app-mode compile.
348
- *
349
- * @param typeVerdicts - Whether to emit the editor-verdict typegen file (only `heximon check` writes it).
350
- * @param options - The baseline verification pass, and the cross-service topology the fan-out
351
- * diagnostics read.
352
- * @returns The compile output, diagnostics included.
398
+ * Every file or directory that the config loader of Nitro (c12) would take as its main config: the name
399
+ * `nitro.config` in the project, in `.config/`, and `.config/nitro`, bare, with each supported extension, and as
400
+ * a directory with an `index` file. The project's own script forms are among them.
353
401
  */
354
- compile(typeVerdicts = false, options = {}) {
355
- return this.compiler.compile({
356
- rootDir: this.rootDir,
357
- outputDirectory: this.outputDirectory,
358
- plugins: this.plugins,
359
- strategy: this.strategy,
360
- ...this.sourceDirectories === void 0 ? {} : { sourceDirectories: this.sourceDirectories },
361
- ...this.aliases === void 0 ? {} : {
362
- aliases: this.aliases.prefixes,
363
- exactAliases: this.aliases.exact
364
- },
365
- ...this.config === void 0 ? {} : { config: this.config },
366
- ...this.config?.wiringMode === void 0 ? {} : { wiringMode: this.config.wiringMode },
367
- ...this.runtimeConfig === void 0 ? {} : { runtimeConfig: this.runtimeConfig },
368
- ...this.config?.root === void 0 ? {} : { apps: { main: this.config.root } },
369
- ...typeVerdicts ? { typeVerdicts: true } : {},
370
- ...options.verifyBaseline === true ? { verifyBaseline: true } : {},
371
- ...options.workspaceSubscribers === void 0 ? {} : { workspaceSubscribers: options.workspaceSubscribers }
372
- });
402
+ static configFilesOf(rootDir) {
403
+ return [
404
+ join(rootDir, "nitro.config"),
405
+ join(rootDir, ".config", "nitro.config"),
406
+ join(rootDir, ".config", "nitro")
407
+ ].flatMap((base) => ["", "/index"].flatMap((suffix) => ["", ...NitroStaticConfig.configExtensions].map((extension) => `${base}${suffix}${extension}`))).filter((path) => existsSync(path));
373
408
  }
374
- /**
375
- * Read the cross-service subscription topology for {@link compile}: only when the sidecar declares
376
- * `crossService`, with the plugins and the `$env` name of this session, over the production graph that
377
- * {@link compile} builds.
378
- *
379
- * @returns The topology, or one error diagnostic in place of the error the read threw.
380
- */
381
- async readWorkspaceTopology() {
409
+ /** The parsed package.json of the project, `undefined` when it has none, `"invalid"` when it is not JSON. */
410
+ static manifestOf(rootDir) {
411
+ const file = join(rootDir, "package.json");
412
+ if (!existsSync(file)) return;
382
413
  try {
383
- return {
384
- topology: await WorkspaceTopologyReader.resolveFromConfig(this.rootDir, this.plugins, this.config, this.environment, CompileEnvironment.Production),
385
- diagnostics: []
386
- };
387
- } catch (error) {
388
- return {
389
- topology: void 0,
390
- diagnostics: [this.topologyFailure(error)]
391
- };
414
+ return JSON.parse(readFileSync(file, "utf8"));
415
+ } catch {
416
+ return "invalid";
392
417
  }
393
418
  }
419
+ /** Whether package.json lists `nitro` as a dependency or a dev dependency. */
420
+ static dependsOnNitro(rootDir) {
421
+ const manifest = NitroStaticConfig.manifestOf(rootDir);
422
+ return manifest !== void 0 && manifest !== "invalid" && ("nitro" in (manifest.dependencies ?? {}) || "nitro" in (manifest.devDependencies ?? {}));
423
+ }
394
424
  /**
395
- * Write the generated files into {@link outputDirectory}, and prune the stale ones. The files that another
396
- * step writes there, such as the deploy target record of `@heximon/nuxt`, stay.
397
- *
398
- * @param files - The files of the compile output.
425
+ * Apply the keys that change a value without showing in it. A key in `always` (for the preset: `static`, which
426
+ * turns a preset into its static variant) makes the value unknown. A key in `whenUnset` (`defaultPreset`,
427
+ * `extends`: the layers sit below every other source) matters only when no literal was found.
399
428
  */
400
- write(files) {
401
- this.compiler.write(this.outputDirectory, files, { retain: this.retainedOutput });
402
- }
403
- /** The platform the session compiles for, or `undefined` for the zero-config Node default. */
404
- platformName() {
405
- return this.strategy.platformName;
429
+ static withHidden(value, sources, always, whenUnset) {
430
+ const hidden = (keys) => {
431
+ for (const source of sources) {
432
+ const key = source.kind === "object" ? keys.find((name) => source.entries.has(name)) : void 0;
433
+ if (source.kind === "object" && key !== void 0) return {
434
+ file: source.file,
435
+ key
436
+ };
437
+ }
438
+ };
439
+ const alwaysHidden = hidden(always);
440
+ const unsetHidden = value.kind === "none" ? hidden(whenUnset) : void 0;
441
+ const reason = alwaysHidden ?? unsetHidden;
442
+ return reason === void 0 ? value : {
443
+ kind: "computed",
444
+ file: reason.file,
445
+ reason: `\`${reason.key}\` can change the value`
446
+ };
406
447
  }
407
- /** The runtime class the session compiles for: `node` or `edge`. */
408
- targetClass() {
409
- return this.strategy.targetClass;
448
+ /** A list gets every `extends` layer on top of it, so a layer makes it unknown. */
449
+ static withHiddenList(value, sources) {
450
+ const layered = sources.find((source) => source.kind === "object" && source.entries.has("extends"));
451
+ return layered === void 0 || layered.kind !== "object" ? value : {
452
+ kind: "computed",
453
+ file: layered.file,
454
+ reason: "`extends` can add values"
455
+ };
410
456
  }
411
457
  /**
412
- * Run the compile `vp build` runs, into a chosen directory: the production graph with the sidecar's wiring
413
- * mode, diagnostic dials and cross-service topology. {@link compile} leaves out the first two, and reads the
414
- * topology only when its caller passes it.
415
- *
416
- * @param outputDirectory - The directory the generated files will be written to. It must sit directly
417
- * under the project root, because the generated imports of the app source are relative to it.
418
- * @param aliases - The module aliases of the project (prefix → absolute path), when it has some.
419
- * @returns The compile output. Nothing is written.
458
+ * The option sources of a Nitro config file, highest priority first: the production overlays, then the
459
+ * object itself. An `extends` or `defaultPreset` key brings values that the source does not show, so it adds
460
+ * an unproven source below the object.
420
461
  */
421
- async compileProduction(outputDirectory, aliases = {
422
- exact: {},
423
- prefixes: {}
424
- }) {
425
- const workspaceSubscribers = await WorkspaceTopologyReader.resolveFromConfig(this.rootDir, this.plugins, this.config, this.environment);
426
- return this.compiler.compile({
427
- rootDir: this.rootDir,
428
- outputDirectory,
429
- plugins: this.plugins,
430
- strategy: this.strategy,
431
- environment: CompileEnvironment.Production,
432
- aliases: aliases.prefixes,
433
- exactAliases: aliases.exact,
434
- ...this.sourceDirectories === void 0 ? {} : { sourceDirectories: this.sourceDirectories },
435
- ...this.config === void 0 ? {} : { config: this.config },
436
- ...this.config?.wiringMode === void 0 ? {} : { wiringMode: this.config.wiringMode },
437
- ...this.config?.strictDiagnostics === void 0 ? {} : { strictDiagnostics: this.config.strictDiagnostics },
438
- ...this.config?.suppressDiagnostics === void 0 ? {} : { suppressDiagnostics: this.config.suppressDiagnostics },
439
- ...this.runtimeConfig === void 0 ? {} : { runtimeConfig: this.runtimeConfig },
440
- ...this.config?.root === void 0 ? {} : { apps: { main: this.config.root } },
441
- ...workspaceSubscribers === void 0 ? {} : { workspaceSubscribers }
462
+ static readNitroConfig(file) {
463
+ const { program, imports } = NitroStaticConfig.parse(file);
464
+ const resolved = NitroStaticConfig.exportedObject(program, imports, NitroStaticConfig.nitroConfigHelper);
465
+ if (resolved.kind === "unproven") return [{
466
+ kind: "unproven",
467
+ file,
468
+ reason: resolved.reason
469
+ }];
470
+ const base = NitroStaticConfig.prove(resolved.node, file);
471
+ if (base.kind === "unproven") return [base];
472
+ const overlay = /* @__PURE__ */ new Map();
473
+ const sources = [];
474
+ const overlays = [base.entries.get("$production")];
475
+ const environments = base.entries.get("$env");
476
+ if (environments !== void 0) {
477
+ const proven = NitroStaticConfig.prove(environments, file);
478
+ if (proven.kind === "unproven") sources.push(proven);
479
+ else overlays.push(proven.entries.get("production"));
480
+ }
481
+ for (const node of overlays) {
482
+ if (node === void 0) continue;
483
+ const proven = NitroStaticConfig.prove(node, file);
484
+ if (proven.kind === "unproven") sources.push(proven);
485
+ else for (const [key, value] of proven.entries) overlay.set(key, value);
486
+ }
487
+ if (overlay.size > 0) sources.push({
488
+ kind: "object",
489
+ file,
490
+ entries: overlay
442
491
  });
492
+ sources.push(base);
493
+ return sources;
443
494
  }
444
495
  /**
445
- * Run the library-mode compile — a published module package goes through the same {@link LibraryEmitter}
446
- * its own `vp pack` build uses, rather than being compiled as an app. Not a byte-for-byte replay of that
447
- * build: the pack host supplies its own plugin set, wiring mode and `pack.entry`-derived publication set,
448
- * while this reads plugins from the config sidecar and falls back to the committed `exports` map.
449
- *
450
- * Two things make the app-mode compile wrong here, not merely noisy. It enforces every `requires` hop-by-hop
451
- * against a host binding, while a library leaves that seam open on purpose (the published factory reads a
452
- * required token as a constructor input); and it looks for one root module, while a multi-root package
453
- * publishes several. Both surface as errors a `vp pack` of the same source never raises.
454
- *
455
- * @param options - `pruneVerdicts` also removes a verdict mirror an EARLIER app-mode run wrote. Library
456
- * mode emits none to replace it, so nothing would ever overwrite those app-mode-only errors — only
457
- * `heximon check`, which owns the mirror, asks for it. Every other verb stays write-free.
458
- * @returns The compile's diagnostics, files and graph projections; a throwing emit becomes one diagnostic.
496
+ * What the Vite config says: whether it imports the Nitro plugin, and the option sources it gives. Once the
497
+ * plugin is imported, anything the reader cannot prove makes the sources unproven; the project is still a
498
+ * Nitro host.
459
499
  */
460
- compileLibrary(options = {}) {
461
- const sourceDirectory = this.sourceDirectories?.[0] ?? (this.config?.sourceDirectory === void 0 ? void 0 : resolve(this.rootDir, this.config.sourceDirectory));
462
- const prunedVerdicts = options.pruneVerdicts === true ? this.compiler.pruneTypeVerdicts({
463
- rootDir: this.rootDir,
464
- ...sourceDirectory === void 0 ? {} : { sourceDirectories: [sourceDirectory] }
465
- }) : void 0;
466
- try {
467
- const emitted = new LibraryEmitter(this.compiler).compile({
468
- rootDir: this.rootDir,
469
- plugins: this.plugins,
470
- ...sourceDirectory === void 0 ? {} : { sourceDirectory },
471
- ...this.config === void 0 ? {} : { config: this.config }
472
- });
473
- return {
474
- diagnostics: emitted.diagnostics,
475
- files: emitted.files,
476
- moduleGraph: emitted.moduleGraph,
477
- boundaryNodes: emitted.boundaryNodes,
478
- ...prunedVerdicts === void 0 ? {} : { prunedVerdicts }
479
- };
480
- } catch (error) {
481
- return {
482
- diagnostics: [{
483
- severity: DiagnosticSeverity.Error,
484
- message: `The library compile of this package failed: ${error instanceof Error ? error.message : String(error)}`,
485
- location: this.rootDir
486
- }],
487
- files: [],
488
- moduleGraph: void 0,
489
- boundaryNodes: [],
490
- ...prunedVerdicts === void 0 ? {} : { prunedVerdicts }
491
- };
500
+ static readVite(file) {
501
+ const { program, imports } = NitroStaticConfig.parse(file);
502
+ const named = /* @__PURE__ */ new Set();
503
+ const namespaces = /* @__PURE__ */ new Set();
504
+ for (const entry of imports) {
505
+ if (entry.request !== NitroStaticConfig.nitroVitePackage || entry.isTypeOnly) continue;
506
+ if (entry.importKind === ImportKind.Namespace) namespaces.add(entry.localName);
507
+ else if (entry.importKind === ImportKind.Named && entry.importedName === "nitro") named.add(entry.localName);
492
508
  }
493
- }
494
- /**
495
- * One error diagnostic for each library the last compile consumed whose source changed since its last
496
- * pack. The compile read old wiring for it, so the verdicts of that compile cannot be trusted. Each
497
- * message is the `heximon doctor` line for the library.
498
- *
499
- * @returns The diagnostics, or an empty list when every consumed library is current.
500
- */
501
- async staleLibraryDiagnostics() {
502
- return (await new LibraryFreshness().findStale(this.compiler.consumedBoundaryPackages())).map((library) => ({
503
- severity: DiagnosticSeverity.Error,
504
- message: LibraryFreshness.staleLine(library.specifier, library.report),
505
- location: library.report.packageDirectory
506
- }));
507
- }
508
- /** The `rootDir` + `sourceDirectories` pair the type-verdict write path keys on, plus the runtime config file. */
509
- typeVerdictTarget() {
509
+ if (named.size === 0 && namespaces.size === 0) return {
510
+ usesNitroPlugin: false,
511
+ sources: []
512
+ };
513
+ const unproven = (reason) => ({
514
+ usesNitroPlugin: true,
515
+ sources: [{
516
+ kind: "unproven",
517
+ file,
518
+ reason
519
+ }]
520
+ });
521
+ const importStarts = new Set(program.descendants("ImportDeclaration").flatMap((declaration) => declaration.descendants(AstNodeType.Identifier)).map((identifier) => identifier.start));
522
+ const calls = program.descendants(AstNodeType.CallExpression).flatMap((call) => {
523
+ const callee = call.child("callee");
524
+ if (callee.is(AstNodeType.Identifier) && named.has(callee.name ?? "")) return [{
525
+ call,
526
+ referenceStart: callee.start
527
+ }];
528
+ if (callee.is(AstNodeType.MemberExpression) && !callee.flagAt("computed") && callee.child("property").name === "nitro" && callee.child("object").is(AstNodeType.Identifier) && namespaces.has(callee.child("object").name ?? "")) return [{
529
+ call,
530
+ referenceStart: callee.child("object").start
531
+ }];
532
+ return [];
533
+ });
534
+ const callStarts = new Set(calls.map((entry) => entry.referenceStart));
535
+ const nameStarts = NitroStaticConfig.nameStarts(program);
536
+ if (program.descendants(AstNodeType.Identifier).filter((identifier) => (named.has(identifier.name ?? "") || namespaces.has(identifier.name ?? "")) && !importStarts.has(identifier.start) && !nameStarts.has(identifier.start) && !callStarts.has(identifier.start)).length > 0) return unproven("the Nitro Vite plugin is used other than by a direct call");
537
+ if (calls.length !== 1) return unproven(`the Nitro Vite plugin is called ${calls.length} times, not once`);
538
+ const resolved = NitroStaticConfig.exportedObject(program, imports, NitroStaticConfig.viteConfigHelper);
539
+ if (resolved.kind === "unproven") return unproven(resolved.reason);
540
+ const config = NitroStaticConfig.prove(resolved.node, file);
541
+ if (config.kind === "unproven") return {
542
+ usesNitroPlugin: true,
543
+ sources: [config]
544
+ };
545
+ const plugins = NitroStaticConfig.unwrap(config.entries.get("plugins"));
546
+ const call = calls[0].call;
547
+ if (!(plugins?.is(AstNodeType.ArrayExpression) === true && plugins.children("elements").some((element) => NitroStaticConfig.unwrap(element)?.start === call.start))) return unproven("the Nitro Vite plugin is not a direct element of the `plugins` array");
548
+ const sources = [];
549
+ const argument = NitroStaticConfig.unwrap(call.children("arguments")[0]);
550
+ if (argument !== void 0) {
551
+ const options = NitroStaticConfig.prove(argument, file);
552
+ sources.push(options);
553
+ const nested = options.kind === "object" ? options.entries.get("config") : void 0;
554
+ if (nested !== void 0) sources.push(NitroStaticConfig.prove(nested, file));
555
+ }
556
+ const nitroKey = config.entries.get("nitro");
557
+ if (nitroKey !== void 0) sources.push(NitroStaticConfig.prove(nitroKey, file));
510
558
  return {
511
- rootDir: this.rootDir,
512
- ...this.runtimeConfig === void 0 ? {} : { runtimeConfigFile: this.runtimeConfig.file },
513
- ...this.sourceDirectories === void 0 ? {} : { sourceDirectories: this.sourceDirectories }
559
+ usesNitroPlugin: true,
560
+ sources
514
561
  };
515
562
  }
516
563
  /**
517
- * The diagnostic for a topology read that threw. The reader puts the code of a known failure on the error
518
- * and at the start of its message; the diagnostic carries the code once, in its own field.
564
+ * The object that `export default` gives: a literal, a call of the verified identity helper over one, or a
565
+ * single top-level `const` that holds either and is never assigned again.
519
566
  */
520
- topologyFailure(error) {
521
- const message = error instanceof Error ? error.message : String(error);
522
- const code = error?.code;
523
- const knownCode = Object.values(DiagnosticCode).find((candidate) => candidate === code);
524
- return {
525
- severity: DiagnosticSeverity.Error,
526
- message: knownCode !== void 0 && message.startsWith(`[${knownCode}] `) ? message.slice(knownCode.length + 3) : message,
527
- location: this.rootDir,
528
- hint: ProjectCompileSession.topologyFailureHint,
529
- ...knownCode === void 0 ? {} : { code: knownCode }
567
+ static exportedObject(program, imports, helper) {
568
+ const helperNames = new Set(imports.filter((entry) => entry.importKind === ImportKind.Named && entry.importedName === helper.name && helper.packages.includes(entry.request) && !entry.isTypeOnly).map((entry) => entry.localName));
569
+ const declaration = program.children("body").find((statement) => statement.is(AstNodeType.ExportDefaultDeclaration))?.child("declaration");
570
+ const objectOf = (node, viaConstant) => {
571
+ const expression = NitroStaticConfig.unwrap(node);
572
+ if (expression === void 0) return {
573
+ kind: "unproven",
574
+ reason: "the config has no default export"
575
+ };
576
+ if (expression.is(AstNodeType.ObjectExpression)) return {
577
+ kind: "found",
578
+ node: expression
579
+ };
580
+ if (expression.is(AstNodeType.CallExpression)) {
581
+ const callee = expression.child("callee");
582
+ return callee.is(AstNodeType.Identifier) && helperNames.has(callee.name ?? "") && expression.children("arguments").length === 1 ? objectOf(expression.children("arguments")[0], viaConstant) : {
583
+ kind: "unproven",
584
+ reason: `the config is a call of something other than ${helper.name} from ${helper.packages.join(" or ")}`
585
+ };
586
+ }
587
+ if (expression.is(AstNodeType.Identifier) && !viaConstant) {
588
+ const initializer = NitroStaticConfig.constantOf(program, expression.name ?? "", expression.start);
589
+ return initializer === void 0 ? {
590
+ kind: "unproven",
591
+ reason: `\`${expression.name}\` is not a top-level const that nothing else uses`
592
+ } : objectOf(initializer, true);
593
+ }
594
+ return {
595
+ kind: "unproven",
596
+ reason: "the default export is not an object the reader can prove"
597
+ };
530
598
  };
599
+ return objectOf(declaration, false);
531
600
  }
532
- };
533
- //#endregion
534
- //#region src/source-directories.ts
535
- /**
536
- * Resolves which directories the host-agnostic compile commands (`check`, `graph`, `routes`) scan for Heximon
537
- * source. The compiler's own default is `<rootDir>/src`; a Nitro/Nuxt host instead keeps its modules under
538
- * `server/` and passes that directory to the compiler from its own build. The standalone CLI is just another
539
- * host, so it detects that layout and passes `server/` too — otherwise its compile finds no modules.
540
- */
541
- var SourceDirectories = class SourceDirectories {
542
- /** Host-framework config basenames whose presence marks a project that roots its modules under `server/`. */
543
- static serverHostConfigNames = [
544
- "nuxt.config.ts",
545
- "nuxt.config.mts",
546
- "nuxt.config.js",
547
- "nuxt.config.mjs",
548
- "nitro.config.ts",
549
- "nitro.config.mts",
550
- "nitro.config.js",
551
- "nitro.config.mjs"
552
- ];
553
601
  /**
554
- * The absolute source directories to scan, or `undefined` to accept the compiler's own `<rootDir>/src`
555
- * default. An explicit `--src` (comma-separated) always wins; otherwise, when the project has no `src/` but
556
- * is a Nitro/Nuxt host carrying a `server/` directory, that directory is scanned.
557
- *
558
- * @param rootDir - The absolute project root.
559
- * @param sourceOption - The raw `--src` argument, when the caller passed one.
560
- * @returns Absolute directories, or `undefined` for the compiler default.
602
+ * The initializer of `const <name> = …` at the top level, when the name has no use except the one at
603
+ * `exportStart` (the default export, or the single wrapper call around it). A member assignment
604
+ * (`config.preset = …`), a call that gets the name (`Object.assign(config, …)`), or a spread of it is another
605
+ * use, and it makes the value unknown.
561
606
  */
562
- static resolve(rootDir, sourceOption) {
563
- if (sourceOption !== void 0 && sourceOption.trim() !== "") {
564
- const directories = sourceOption.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0).map((entry) => resolve(rootDir, entry));
565
- if (directories.length > 0) return directories;
607
+ static constantOf(program, name, exportStart) {
608
+ const initializers = [];
609
+ for (const statement of program.children("body")) {
610
+ const declaration = statement.is(AstNodeType.ExportNamedDeclaration) ? statement.child("declaration") : statement;
611
+ if (declaration.stringAt("kind") !== "const") continue;
612
+ for (const declarator of declaration.children("declarations")) if (declarator.child("id").name === name) initializers.push({
613
+ init: declarator.child("init"),
614
+ idStart: declarator.child("id").start
615
+ });
566
616
  }
567
- if (SourceDirectories.isDirectory(join(rootDir, "src"))) return;
568
- if (SourceDirectories.isServerHost(rootDir) && SourceDirectories.isDirectory(join(rootDir, "server"))) return [join(rootDir, "server")];
617
+ if (initializers.length !== 1) return;
618
+ const names = NitroStaticConfig.nameStarts(program);
619
+ return program.descendants(AstNodeType.Identifier).filter((identifier) => identifier.name === name && identifier.start !== initializers[0].idStart && identifier.start !== exportStart && !names.has(identifier.start)).length === 0 ? initializers[0].init : void 0;
569
620
  }
570
- /** Whether the root carries a Nitro/Nuxt host config, which roots Heximon modules under `server/`. */
571
- static isServerHost(rootDir) {
572
- return SourceDirectories.serverHostConfigNames.some((name) => existsSync(join(rootDir, name)));
621
+ /** The starts of identifiers that are names, not references: a property key and a member name. */
622
+ static nameStarts(program) {
623
+ return /* @__PURE__ */ new Set([...program.descendants(AstNodeType.Property).filter((property) => !property.flagAt("computed") && !property.flagAt("shorthand")).map((property) => property.child("key").start), ...program.descendants(AstNodeType.MemberExpression).filter((member) => !member.flagAt("computed")).map((member) => member.child("property").start)]);
573
624
  }
574
- /** Whether `path` exists and is a directory. */
575
- static isDirectory(path) {
576
- try {
577
- return statSync(path).isDirectory();
578
- } catch {
579
- return false;
625
+ /** The options of one object, or the reason that the reader cannot prove it. */
626
+ static prove(node, file) {
627
+ const object = NitroStaticConfig.unwrap(node);
628
+ if (object === void 0 || !object.is(AstNodeType.ObjectExpression)) return {
629
+ kind: "unproven",
630
+ file,
631
+ reason: "an options value is not an object literal"
632
+ };
633
+ const entries = /* @__PURE__ */ new Map();
634
+ for (const property of object.children("properties")) {
635
+ if (!property.is(AstNodeType.Property)) return {
636
+ kind: "unproven",
637
+ file,
638
+ reason: "an options object has a spread"
639
+ };
640
+ const key = property.child("key");
641
+ const name = key.name ?? key.stringAt("value");
642
+ if (property.flagAt("computed") || property.flagAt("method") || property.stringAt("kind") !== "init" || name === void 0) return {
643
+ kind: "unproven",
644
+ file,
645
+ reason: "an options object has a computed key, a getter or a method"
646
+ };
647
+ entries.set(name, property.child("value"));
580
648
  }
649
+ return {
650
+ kind: "object",
651
+ file,
652
+ entries
653
+ };
581
654
  }
582
- };
583
- //#endregion
584
- //#region src/startup-baseline.ts
585
- /**
586
- * The command side of the committed startup baseline: it reads and writes `heximon.startup.json`, and turns a
587
- * comparison into the errors and notes of `heximon check --startup`.
588
- */
589
- var StartupBaseline = class StartupBaseline {
590
- /** The command that writes the file. */
591
- static updateCommand = "heximon check --startup --update";
592
- /**
593
- * Compares the start reports of a compile with the committed file.
594
- *
595
- * @param rootDir - The app root that holds the committed file.
596
- * @param reports - The start reports of the compile.
597
- */
598
- static check(rootDir, reports) {
599
- const target = join(rootDir, StartupBaselineFile.fileName);
600
- const committed = StartupBaseline.readCommitted(target);
601
- const cliCodes = /* @__PURE__ */ new Map();
602
- if (committed === void 0 || committed.apps === void 0) {
603
- const missing = committed === void 0;
604
- const diagnostic = {
605
- severity: DiagnosticSeverity.Error,
606
- message: missing ? `there is no committed ${StartupBaselineFile.fileName}, so the startup check has nothing to compare with.` : `${StartupBaselineFile.fileName} is not a version ${StartupBaselineFile.version} startup baseline, so the startup check cannot read it.`,
607
- hint: `Run \`${StartupBaseline.updateCommand}\` and commit the file.`
655
+ /** A string option: the first source that sets it decides. */
656
+ static scalar(key, sources, emptyIsAbsent = false) {
657
+ for (const source of sources) {
658
+ if (source.kind === "unproven") return {
659
+ kind: "computed",
660
+ file: source.file,
661
+ reason: source.reason
608
662
  };
609
- cliCodes.set(diagnostic, missing ? CheckDiagnosticCode.StartupBaselineMissing : CheckDiagnosticCode.StartupBaselineUnreadable);
610
- return {
611
- result: {
612
- action: "compare",
613
- path: target,
614
- committed: false,
615
- reason: missing ? "missing" : "unreadable"
616
- },
617
- diagnostics: [diagnostic],
618
- cliCodes,
619
- notes: []
663
+ const node = source.entries.get(key);
664
+ if (node === void 0) continue;
665
+ const value = NitroStaticConfig.stringOf(node);
666
+ if (emptyIsAbsent && value === "") continue;
667
+ return value === void 0 ? {
668
+ kind: "computed",
669
+ file: source.file,
670
+ reason: `\`${key}\` is not a string literal`
671
+ } : {
672
+ kind: "literal",
673
+ value
620
674
  };
621
675
  }
622
- const comparison = StartupBaselineFile.compare(committed.apps, reports);
623
- const diagnostics = comparison.growth.map((change) => {
624
- const diagnostic = {
625
- severity: DiagnosticSeverity.Error,
626
- message: StartupBaseline.growthMessage(change),
627
- hint: `Make the package wait for its first use (see the reasons), or accept the growth: run \`${StartupBaseline.updateCommand}\` and commit the file.`
628
- };
629
- cliCodes.set(diagnostic, CheckDiagnosticCode.StartupGrowth);
630
- return diagnostic;
676
+ return { kind: "none" };
677
+ }
678
+ /**
679
+ * The options of one nested section (such as `heximon`) of each source, in the same order. A section that is
680
+ * not an object literal the reader can prove is unproven; a source without the section adds nothing.
681
+ */
682
+ static sectionSources(key, sources) {
683
+ return sources.flatMap((source) => {
684
+ if (source.kind === "unproven") return [source];
685
+ const section = source.entries.get(key);
686
+ return section === void 0 ? [] : [NitroStaticConfig.prove(section, source.file)];
631
687
  });
688
+ }
689
+ /** A list option: every source adds to it, so one unproven source makes it unknown. */
690
+ static list(key, sources) {
691
+ const values = [];
692
+ let found = false;
693
+ for (const source of sources) {
694
+ if (source.kind === "unproven") return {
695
+ kind: "computed",
696
+ file: source.file,
697
+ reason: source.reason
698
+ };
699
+ const node = NitroStaticConfig.unwrap(source.entries.get(key));
700
+ if (node === void 0) continue;
701
+ const strings = (node.is(AstNodeType.ArrayExpression) ? node.children("elements") : []).map((element) => NitroStaticConfig.stringOf(element));
702
+ if (!node.is(AstNodeType.ArrayExpression) || strings.some((value) => value === void 0)) return {
703
+ kind: "computed",
704
+ file: source.file,
705
+ reason: `\`${key}\` is not an array of string literals`
706
+ };
707
+ found = true;
708
+ values.push(...strings);
709
+ }
710
+ return found ? {
711
+ kind: "literal",
712
+ value: values
713
+ } : { kind: "none" };
714
+ }
715
+ /** The text of a string literal or of a template literal with no placeholder; else `undefined`. */
716
+ static stringOf(node) {
717
+ const value = NitroStaticConfig.unwrap(node);
718
+ if (value === void 0) return;
719
+ if (typeof value.literalValue === "string") return value.literalValue;
720
+ if (value.is(AstNodeType.TemplateLiteral) && !value.hasChildren("expressions")) return value.children("quasis")[0]?.child("value").stringAt("cooked");
721
+ }
722
+ /** The node without its wrappers (`as`, `satisfies`, `!`, parentheses); `undefined` when absent. */
723
+ static unwrap(node) {
724
+ let current = node;
725
+ while (current !== void 0 && current.exists() && NitroStaticConfig.wrapperTypes.includes(current.type ?? "")) current = current.child("expression");
726
+ return current === void 0 || !current.exists() ? void 0 : current;
727
+ }
728
+ static parse(file) {
729
+ const parsed = new SourceParser().parse(file, readFileSync(file, "utf8"));
632
730
  return {
633
- result: {
634
- action: "compare",
635
- path: target,
636
- committed: true,
637
- growth: comparison.growth,
638
- notes: comparison.notes
639
- },
640
- diagnostics,
641
- cliCodes,
642
- notes: StartupBaseline.noteLines(comparison.notes)
731
+ program: parsed.program,
732
+ imports: parsed.imports
643
733
  };
644
734
  }
735
+ };
736
+ //#endregion
737
+ //#region src/nuxt-target-file.ts
738
+ /**
739
+ * Reads `.heximon/nuxt-target.json`, which `@heximon/nuxt` writes on each production Nuxt run (a build, or
740
+ * `nuxt prepare`): the Nitro preset and the source directories of that run. The command never runs the Nuxt
741
+ * config, so the record is the only source of the deploy target of a Nuxt app. It shows the last run: a record
742
+ * older than one of the Nuxt config files that the run loaded is refused.
743
+ */
744
+ var NuxtTargetFile = class NuxtTargetFile {
745
+ /** The format version that this reader knows. `@heximon/nuxt` writes the same number. */
746
+ static formatVersion = 1;
747
+ /** The file name of the record, in the `.heximon` output directory of the app. */
748
+ static fileName = "nuxt-target.json";
749
+ /** The path of the record, relative to the app root. */
750
+ static relativePath = `.heximon/${NuxtTargetFile.fileName}`;
751
+ /** The types directory of Nuxt when the record names none: the default `buildDir`. */
752
+ static defaultTypesDirectory = ".nuxt";
753
+ /** The tsconfig files that Nuxt generates in its types directory, weakest first: the server one wins. */
754
+ static generatedTsconfigNames = ["tsconfig.json", "tsconfig.server.json"];
645
755
  /**
646
- * The committed file, parsed, when it is a startup baseline that this version reads.
756
+ * Read the record of a Nuxt app.
647
757
  *
648
- * @param rootDir - The app root that holds the committed file.
758
+ * @param rootDir - The app root.
759
+ * @returns The target, or why the record cannot be used.
649
760
  */
650
- static committedDocument(rootDir) {
651
- const committed = StartupBaseline.readCommitted(join(rootDir, StartupBaselineFile.fileName));
652
- return committed?.apps === void 0 ? void 0 : committed.document;
761
+ static read(rootDir) {
762
+ const file = join(rootDir, NuxtTargetFile.relativePath);
763
+ const unavailable = (message) => ({
764
+ kind: "unavailable",
765
+ file,
766
+ message
767
+ });
768
+ if (!existsSync(file)) return unavailable(`This Nuxt app has no record of its deploy target (${NuxtTargetFile.relativePath}).`);
769
+ let record;
770
+ try {
771
+ record = JSON.parse(readFileSync(file, "utf8"));
772
+ } catch {
773
+ return unavailable(`The record of the deploy target (${file}) is not valid JSON.`);
774
+ }
775
+ const content = typeof record === "object" && record !== null ? record : {};
776
+ if (content.version !== NuxtTargetFile.formatVersion) return unavailable(`The record of the deploy target (${file}) has the format version ${JSON.stringify(content.version)}, and this command reads version ${NuxtTargetFile.formatVersion}.`);
777
+ const isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
778
+ if (typeof content.preset !== "string" || content.preset.length === 0 || !isStringList(content.sourceDirectories) || !isStringList(content.configFiles) || content.typesDir !== void 0 && typeof content.typesDir !== "string") return unavailable(`The record of the deploy target (${file}) does not have the expected fields.`);
779
+ const typesDirectory = typeof content.typesDir === "string" ? content.typesDir : NuxtTargetFile.defaultTypesDirectory;
780
+ const recordedAt = statSync(file).mtimeMs;
781
+ const changed = content.configFiles.map((path) => resolve(rootDir, path)).find((path) => !existsSync(path) || statSync(path).mtimeMs > recordedAt);
782
+ if (changed !== void 0) return unavailable(`The record of the deploy target (${file}) is older than the Nuxt config file ${changed}, or that file is gone, so the record can hold an old target.`);
783
+ return {
784
+ kind: "found",
785
+ target: {
786
+ file,
787
+ preset: content.preset,
788
+ sourceDirectories: content.sourceDirectories.map((path) => resolve(rootDir, path)),
789
+ generatedTsconfigFiles: NuxtTargetFile.generatedTsconfigNames.map((name) => join(typesDirectory, name))
790
+ }
791
+ };
653
792
  }
654
- /**
655
- * Writes the file for the start reports of a compile when it differs from the committed one. The other
656
- * top-level sections of the committed file stay as they are.
793
+ };
794
+ //#endregion
795
+ //#region src/host-target-strategy.ts
796
+ /**
797
+ * Resolves the deploy strategy of a compile. A Nitro or Nuxt host takes it from its Nitro preset, as its build
798
+ * does: `@heximon/nitro` maps the preset to the strategy of the vendor. The preset of a Nitro host comes from the
799
+ * text of its config files ({@link NitroStaticConfig}), and the preset of a Nuxt app from the record of its last
800
+ * production run ({@link NuxtTargetFile}). When the command cannot apply the preset, the sidecar `platform`
801
+ * decides; without one, the compile uses the Node default and gets a note. Any other project uses the sidecar.
802
+ */
803
+ var HostTargetStrategy = class HostTargetStrategy {
804
+ /** The package that maps a Nitro preset to its strategy. */
805
+ static nitroPackage = "@heximon/nitro";
806
+ /** The entry of {@link nitroPackage} with the strategy function. */
807
+ static nitroModule = `${HostTargetStrategy.nitroPackage}/module`;
808
+ /** The package of a Nuxt app that depends on {@link nitroPackage}, which pnpm does not hoist to the app. */
809
+ static nuxtPackage = "@heximon/nuxt";
810
+ /** The preset of the Node default. A request without a preset would take the provider of the environment. */
811
+ static nodePreset = "node-server";
812
+ /** The fix that every note names last. */
813
+ static platformFix = "declare `platform` in heximon.config.ts (for example `platform: new CloudflareWorkersStrategy()`)";
814
+ /**
815
+ * Resolve the strategy of a project.
657
816
  *
658
- * @param rootDir - The app root that holds the committed file.
659
- * @param reports - The start reports of the compile.
660
- * @param size - The size of the built server code. Without it, the committed size section stays.
661
- * @returns The path, and whether the content changed.
662
- */
663
- static update(rootDir, reports, size) {
664
- const target = join(rootDir, StartupBaselineFile.fileName);
665
- const committed = StartupBaseline.readCommitted(target);
666
- const content = StartupBaselineFile.compose(reports, committed?.document, size === void 0 ? {} : { [StartupSizeBudget.sectionKey]: size });
667
- const changed = committed?.content !== content;
668
- if (changed) writeFileSync(target, content);
817
+ * @param rootDir - The absolute project root.
818
+ * @param config - The loaded sidecar, or `undefined` when the project has none.
819
+ * @returns The strategy, and the note when a host compiles for the Node default.
820
+ * @throws CommandFailure with {@link CliDiagnosticCode.HostStrategyUnavailable} when the preset names a vendor
821
+ * whose platform package does not load. The build of the host fails on the same error.
822
+ */
823
+ static async resolve(rootDir, config) {
824
+ const hostPreset = HostTargetStrategy.presetOf(rootDir);
825
+ if (hostPreset === void 0) return { strategy: NodeCompileSeam.resolveStrategy(config?.platform) };
826
+ const resolver = await HostTargetStrategy.resolverOf(rootDir);
827
+ let unapplied;
828
+ if (hostPreset.kind === "known" && resolver.kind === "loaded") {
829
+ const strategy = await HostTargetStrategy.strategyOf(resolver, rootDir, hostPreset.preset);
830
+ if (strategy !== void 0) return { strategy };
831
+ unapplied = {
832
+ kind: "unapplied",
833
+ reason: `The Nitro preset '${hostPreset.preset ?? ""}' is not a built-in preset of Nitro, and the command does not load a custom preset.`,
834
+ fix: "Set the Nitro preset to the name of a built-in preset"
835
+ };
836
+ } else unapplied = hostPreset.kind === "unapplied" ? hostPreset : resolver;
837
+ if (config?.platform !== void 0) return { strategy: config.platform };
669
838
  return {
670
- target,
671
- changed
839
+ strategy: (resolver.kind === "loaded" ? await HostTargetStrategy.strategyOf(resolver, rootDir, HostTargetStrategy.nodePreset) : void 0) ?? NodeCompileSeam.resolveStrategy(void 0),
840
+ note: {
841
+ severity: DiagnosticSeverity.Info,
842
+ message: `The compile used the Node default, not the deploy target of the build: ${unapplied.reason} A diagnostic that depends on the target can be wrong for the build.`,
843
+ hint: `${unapplied.fix}, or ${HostTargetStrategy.platformFix}.`,
844
+ location: rootDir
845
+ }
672
846
  };
673
847
  }
674
- /** The error text of one growth. */
675
- static growthMessage(change) {
676
- const file = StartupBaselineFile.fileName;
677
- switch (change.kind) {
678
- case StartupChangeKind.NewApp: return `app '${change.app}' has no record in ${file}, so every package of its start is new.`;
679
- case StartupChangeKind.EntryGrowth: return `app '${change.app}': the first use of '${change.place}' now loads '${change.package}', and ${file} does not list it for this entry.`;
680
- default: return `app '${change.app}': '${change.package}' now loads at the start, and ${file} does not list it there. Reasons: ${(change.reasons ?? []).join("; ")}.`;
848
+ /** The preset of a Nitro or Nuxt host, or `undefined` for a project that is neither. */
849
+ static presetOf(rootDir) {
850
+ if (NitroStaticConfig.isNuxtProject(rootDir)) {
851
+ const reading = NuxtTargetFile.read(rootDir);
852
+ return reading.kind === "found" ? {
853
+ kind: "known",
854
+ preset: reading.target.preset
855
+ } : {
856
+ kind: "unapplied",
857
+ reason: `${reading.message} The command does not run the Nuxt config.`,
858
+ fix: "Run `nuxi prepare` (or build the app) to write the record"
859
+ };
681
860
  }
861
+ const nitro = NitroStaticConfig.read(rootDir);
862
+ if (!nitro.isNitroHost) return;
863
+ if (nitro.preset.kind === "computed") return {
864
+ kind: "unapplied",
865
+ reason: `The Nitro preset is computed (${nitro.preset.reason}, in ${nitro.preset.file}), and the command does not run your config files.`,
866
+ fix: "Set `preset` in the Nitro config to a string, or set NITRO_PRESET"
867
+ };
868
+ return {
869
+ kind: "known",
870
+ preset: nitro.preset.kind === "literal" ? nitro.preset.value : void 0
871
+ };
682
872
  }
683
- /** The note lines: one per change that does not fail, and one line that says the file can be smaller. */
684
- static noteLines(notes) {
685
- const lines = notes.map((change) => {
686
- switch (change.kind) {
687
- case StartupChangeKind.StartShrink: return `app '${change.app}': '${change.package}' no longer loads at the start.`;
688
- case StartupChangeKind.EntryShrink: return `app '${change.app}': the first use of '${change.place}' no longer loads '${change.package}'.`;
689
- case StartupChangeKind.NewEntry: return `app '${change.app}': '${change.place}' is a new entry.`;
690
- case StartupChangeKind.RemovedEntry: return `app '${change.app}': '${change.place}' is no longer an entry.`;
691
- case StartupChangeKind.RemovedApp: return `app '${change.app}' is no longer built.`;
692
- case StartupChangeKind.TargetChanged: return `app '${change.app}': the deploy target changed whether it defers packages.`;
693
- default: return `app '${change.app}': '${change.package}' loads at the start for other reasons: ${(change.reasons ?? []).join("; ")}.`;
694
- }
695
- });
696
- if (lines.length === 0) return [];
697
- const shrinks = notes.some((change) => change.kind === StartupChangeKind.StartShrink || change.kind === StartupChangeKind.EntryShrink);
698
- return [...lines, shrinks ? `The app loads less than ${StartupBaselineFile.fileName} records. Run \`${StartupBaseline.updateCommand}\` to make the baseline smaller.` : `Run \`${StartupBaseline.updateCommand}\` to record these changes.`];
699
- }
700
- /** The committed file's text, its parsed form, and its app records, or `undefined` when the file is absent. */
701
- static readCommitted(target) {
702
- let content;
873
+ /**
874
+ * Load the preset resolver of `@heximon/nitro` from the project: its own copy, or the copy that its
875
+ * `@heximon/nuxt` depends on.
876
+ */
877
+ static async resolverOf(rootDir) {
878
+ const projectRequire = createRequire(join(rootDir, "package.json"));
879
+ const resolutions = [() => projectRequire.resolve(HostTargetStrategy.nitroModule), () => createRequire(projectRequire.resolve(HostTargetStrategy.nuxtPackage)).resolve(HostTargetStrategy.nitroModule)];
880
+ let entry;
881
+ for (const resolution of resolutions) try {
882
+ entry = resolution();
883
+ break;
884
+ } catch {}
885
+ if (entry === void 0) return {
886
+ kind: "unapplied",
887
+ reason: `The project has no ${HostTargetStrategy.nitroPackage} to map the Nitro preset to its target.`,
888
+ fix: `Install ${HostTargetStrategy.nitroPackage} in the project`
889
+ };
890
+ let resolve;
703
891
  try {
704
- content = readFileSync(target, "utf8");
705
- } catch {
706
- return;
892
+ resolve = (await import(pathToFileURL(entry).href)).resolveNitroPresetStrategy;
893
+ } catch (error) {
894
+ return {
895
+ kind: "unapplied",
896
+ reason: `${HostTargetStrategy.nitroModule} of the project could not be loaded (${error instanceof Error ? error.message : String(error)}).`,
897
+ fix: `Fix the install of ${HostTargetStrategy.nitroPackage}`
898
+ };
707
899
  }
708
- let document;
900
+ return resolve === void 0 ? {
901
+ kind: "unapplied",
902
+ reason: `The ${HostTargetStrategy.nitroPackage} of the project is older than this command, so it cannot map the Nitro preset to its target.`,
903
+ fix: `Update ${HostTargetStrategy.nitroPackage} to the version of this command`
904
+ } : {
905
+ kind: "loaded",
906
+ resolve
907
+ };
908
+ }
909
+ /**
910
+ * The strategy of a preset, or `undefined` for a custom preset. The vendor platform package loads from the
911
+ * project root, as in the build.
912
+ */
913
+ static async strategyOf(resolver, rootDir, preset) {
709
914
  try {
710
- document = JSON.parse(content);
711
- } catch {
712
- document = void 0;
915
+ return await resolver.resolve({
916
+ rootDirectory: rootDir,
917
+ preset
918
+ });
919
+ } catch (error) {
920
+ throw CommandFailure.of(CliDiagnosticCode.HostStrategyUnavailable, `The strategy of ${preset === void 0 ? "the default Nitro preset" : `the Nitro preset '${preset}'`} could not be loaded, so the command cannot compile for the deploy target of the build: ${error instanceof Error ? error.message : String(error)}`, "Fix the install of the platform package. The build of the app fails on the same error.");
713
921
  }
714
- return {
715
- content,
716
- document,
717
- apps: StartupBaselineFile.parse(document)
718
- };
719
922
  }
720
923
  };
721
924
  //#endregion
722
- //#region src/startup-built-code.ts
925
+ //#region src/project-compile-session.ts
723
926
  /**
724
- * The built server code of one entry, as the size walk read it, with the packages of each file. It finds the
725
- * files that hold the code of a package, and the files that some files load when they run.
927
+ * The from-disk compile prologue every inspection command shares (`check`, `graph`, `routes`, `workflows`):
928
+ * resolve the source directories, load the `heximon.config.ts` sidecar for the requested `$env`, derive the
929
+ * platform compile strategy, and merge the plugin set the compile runs with.
726
930
  *
727
- * The code of a package starts at the chunk of its generated loader, when the start report names the loader and
728
- * the build record names the chunk. So two roots of one npm package each get their own files. Otherwise a file
729
- * holds the code of a package when the build record gives the package bytes in the file, or when the file is in
730
- * the `node_modules` directory of the package in the output, without the files that only the other roots of the
731
- * package reach. From these files, the code of a package is every file that they import, with a static import or
732
- * with `import()`, up to the loader chunk of another package.
931
+ * The `.env` cascade is deliberately NOT loaded here. Only `heximon routes` loads it (so a booted app and its
932
+ * config sidecar read the environment `vp dev` would give them); the compile-only verbs must not pick up a
933
+ * developer's `.env` just by inspecting a project. A caller that wants it loads it before calling
934
+ * {@link open}, so the sidecar read still sees it.
733
935
  */
734
- var StartupBuiltCode = class StartupBuiltCode {
735
- measured;
736
- chunks;
737
- /** The directory of the installed packages in a path of the output. */
738
- static packageDirectory = "node_modules/";
739
- /** The bytes of each file that the walk reached, by path in the output directory. */
740
- bytesByFile;
741
- /** The files that hold the code of each package, by package name. */
742
- filesByPackage;
743
- /** The chunks that hold the loader of each package with a known loader, by package identity. */
744
- loaderChunks;
745
- /** The files that the first load of each package with a known loader reaches, by package identity. */
746
- loaderClosures = /* @__PURE__ */ new Map();
747
- /** The static start closure of the walk. */
748
- staticStart;
936
+ var ProjectCompileSession = class ProjectCompileSession {
937
+ /** The gitignored directory the compile anchors its generated paths at. */
938
+ static outputDirectoryName = ".heximon";
939
+ /** Why a check reports a topology failure: the build of the same project fails on it too. */
940
+ static topologyFailureHint = "The sidecar declares `crossService`, so the build reads the cross-service subscription topology of the workspace and fails on the same error.";
941
+ /** The absolute project root the compile runs against. */
942
+ rootDir;
943
+ /** The warm compiler — reused by a caller that also prunes or writes type verdicts. */
944
+ compiler;
945
+ /** The resolved sidecar, or `undefined` when the project ships none. */
946
+ config;
947
+ /** The absolute source directories to scan, or `undefined` for the compiler's own `<rootDir>/src`. */
948
+ sourceDirectories;
949
+ /** The absolute `.heximon/` directory the compile anchors its generated paths at. */
950
+ outputDirectory;
951
+ /** The compiler plugins the sidecar declares, merged with the platform strategy's own. */
952
+ plugins;
953
+ strategy;
954
+ /** The `$env` name the sidecar was read for, which the member sidecars of the workspace scan share. */
955
+ environment;
956
+ /** The runtime config file the app compile checks and bakes in, or `undefined` when there is none. */
957
+ runtimeConfig;
958
+ /** The module aliases of a host build, which {@link compile} resolves, or `undefined` for none. */
959
+ aliases;
960
+ /** The output-relative files that another step writes into {@link outputDirectory}, which {@link write} keeps. */
961
+ retainedOutput;
962
+ /** Why a Nitro or Nuxt host compiles for the Node default, or `undefined` when it does not. */
963
+ hostTargetNote;
964
+ constructor(options) {
965
+ this.rootDir = options.rootDir;
966
+ this.compiler = options.compiler;
967
+ this.config = options.config;
968
+ this.runtimeConfig = options.runtimeConfig;
969
+ this.sourceDirectories = options.sourceDirectories;
970
+ this.plugins = options.plugins;
971
+ this.strategy = options.strategy;
972
+ this.environment = options.environment;
973
+ this.aliases = options.aliases;
974
+ this.hostTargetNote = options.hostTargetNote;
975
+ this.outputDirectory = join(options.rootDir, ProjectCompileSession.outputDirectoryName);
976
+ this.retainedOutput = [NuxtTargetFile.fileName, ...options.retainedOutput ?? []];
977
+ }
749
978
  /**
750
- * @param measured - The measurement of the entry, with the imports of each file.
751
- * @param chunks - The packages of each chunk of the build, from the build record.
752
- * @param generated - The generated wiring files of each chunk of the build, from the build record.
753
- * @param loaders - The generated loader file of each package, by identity, from the start report.
979
+ * Resolve one project's compile inputs.
980
+ *
981
+ * @param options - The project root, the `$env` name, and the resolved source directories.
982
+ * @returns The session the caller compiles through.
983
+ * @throws CommandFailure with `cli.config-unreadable` when the sidecar throws, or with
984
+ * `cli.host-strategy-unavailable` when the strategy of a host preset does not load.
754
985
  */
755
- constructor(measured, chunks, generated = {}, loaders = {}) {
756
- this.measured = measured;
757
- this.chunks = chunks;
758
- const filesByPackage = /* @__PURE__ */ new Map();
759
- this.bytesByFile = new Map(measured.measurement.files.map((file) => [file.path, file.bytes]));
760
- for (const file of measured.measurement.files) {
761
- const names = new Set(Object.keys(this.packagesOfFile(file.path)));
762
- for (const name of names) filesByPackage.set(name, [...filesByPackage.get(name) ?? [], file.path]);
763
- }
764
- this.filesByPackage = filesByPackage;
765
- this.loaderChunks = this.loaderChunksOf(generated, loaders);
766
- this.staticStart = this.reach(this.staticStartFiles(), /* @__PURE__ */ new Set(), void 0);
986
+ static async open(options) {
987
+ const config = await ConfigSidecar.load(options.rootDir, options.environment);
988
+ const target = options.hostTarget === true ? await HostTargetStrategy.resolve(options.rootDir, config) : {
989
+ strategy: NodeCompileSeam.resolveStrategy(config?.platform),
990
+ note: void 0
991
+ };
992
+ const strategy = target.strategy;
993
+ return new ProjectCompileSession({
994
+ rootDir: options.rootDir,
995
+ compiler: new ProjectCompiler(),
996
+ config,
997
+ runtimeConfig: await RuntimeConfigLoader.load(options.rootDir, config, options.environment),
998
+ sourceDirectories: options.sourceDirectories,
999
+ plugins: NodeCompileSeam.mergePlugins(config?.plugins ?? [], strategy),
1000
+ strategy,
1001
+ environment: options.environment,
1002
+ ...target.note === void 0 ? {} : { hostTargetNote: target.note }
1003
+ });
767
1004
  }
768
1005
  /**
769
- * The package name of a package identity: `@acme/orders/admin#OrdersModule` gives `@acme/orders`.
1006
+ * A session that compiles with the production inputs of a Nitro or Nuxt host: the strategy of its preset, the
1007
+ * Nitro host plugin, and the production sidecar. {@link open} reads only the sidecar, so it compiles a Nitro app
1008
+ * for Node whatever the preset is.
770
1009
  *
771
- * @param identity - The identity, as `<specifier>#<module class>`.
1010
+ * @param options - The project root, the host inputs, the module aliases, and the source directories to scan
1011
+ * instead of the host's, when the caller has some.
1012
+ * @returns The session the caller compiles through.
772
1013
  */
773
- static packageNameOf(identity) {
774
- const specifier = identity.slice(0, identity.lastIndexOf("#") === -1 ? void 0 : identity.lastIndexOf("#"));
775
- return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
776
- }
777
- /** The files that the entry loads when it runs: the static start closure of the walk. */
778
- staticStartFiles() {
779
- return this.measured.measurement.files.filter((file) => file.isStart).map((file) => file.path);
1014
+ static forNitroHost(options) {
1015
+ const inputs = options.inputs;
1016
+ return new ProjectCompileSession({
1017
+ rootDir: options.rootDir,
1018
+ compiler: new ProjectCompiler(),
1019
+ config: inputs.config,
1020
+ runtimeConfig: inputs.runtimeConfig,
1021
+ sourceDirectories: options.sourceDirectories ?? inputs.sourceDirectories,
1022
+ plugins: inputs.plugins,
1023
+ strategy: inputs.strategy,
1024
+ environment: "production",
1025
+ aliases: options.aliases,
1026
+ ...inputs.retainedOutput === void 0 ? {} : { retainedOutput: inputs.retainedOutput }
1027
+ });
780
1028
  }
781
1029
  /**
782
- * The files that the first load of some packages reaches, without the files that are loaded already: from the
783
- * chunk of each loader, or the files of the npm package ({@link byPackageName}), every file that they import
784
- * with a static import or with `import()`. The walk does not go into the loader chunk of another package
785
- * through `import()`, as that chunk loads on the first use of that package.
1030
+ * Run the app-mode compile.
786
1031
  *
787
- * @param identities - The packages, by identity.
788
- * @param loaded - The files that are loaded already. The walk does not pass through them.
1032
+ * @param typeVerdicts - Whether to emit the editor-verdict typegen file (only `heximon check` writes it).
1033
+ * @param options - The baseline verification pass, and the cross-service topology the fan-out
1034
+ * diagnostics read.
1035
+ * @returns The compile output, diagnostics included.
789
1036
  */
790
- codeOf(identities, loaded = /* @__PURE__ */ new Set()) {
791
- return this.reach(this.seedsOf(identities), loaded, this.loaderChunksOutside(new Set(identities)));
1037
+ compile(typeVerdicts = false, options = {}) {
1038
+ return this.compiler.compile({
1039
+ rootDir: this.rootDir,
1040
+ outputDirectory: this.outputDirectory,
1041
+ plugins: this.plugins,
1042
+ strategy: this.strategy,
1043
+ ...this.sourceDirectories === void 0 ? {} : { sourceDirectories: this.sourceDirectories },
1044
+ ...this.aliases === void 0 ? {} : {
1045
+ aliases: this.aliases.prefixes,
1046
+ exactAliases: this.aliases.exact
1047
+ },
1048
+ ...this.config === void 0 ? {} : { config: this.config },
1049
+ ...this.config?.wiringMode === void 0 ? {} : { wiringMode: this.config.wiringMode },
1050
+ ...this.runtimeConfig === void 0 ? {} : { runtimeConfig: this.runtimeConfig },
1051
+ ...this.config?.root === void 0 ? {} : { apps: { main: this.config.root } },
1052
+ ...typeVerdicts ? { typeVerdicts: true } : {},
1053
+ ...options.verifyBaseline === true ? { verifyBaseline: true } : {},
1054
+ ...options.workspaceSubscribers === void 0 ? {} : { workspaceSubscribers: options.workspaceSubscribers }
1055
+ });
792
1056
  }
793
1057
  /**
794
- * The files that the app loads before it is ready: the static start closure, and the code of the start
795
- * packages ({@link codeOf}), also where it passes through the static start.
1058
+ * Read the cross-service subscription topology for {@link compile}: only when the sidecar declares
1059
+ * `crossService`, with the plugins and the `$env` name of this session, over the production graph that
1060
+ * {@link compile} builds.
796
1061
  *
797
- * @param identities - The start packages, by identity.
1062
+ * @returns The topology, or one error diagnostic in place of the error the read threw.
798
1063
  */
799
- startFiles(identities) {
800
- return /* @__PURE__ */ new Set([...this.staticStart, ...this.codeOf(identities)]);
801
- }
802
- /** Whether the code finds the files of some package by its loader chunk. */
803
- hasLoaders() {
804
- return this.loaderChunks.size > 0;
1064
+ async readWorkspaceTopology() {
1065
+ try {
1066
+ return {
1067
+ topology: await WorkspaceTopologyReader.resolveFromConfig(this.rootDir, this.plugins, this.config, this.environment, CompileEnvironment.Production),
1068
+ diagnostics: []
1069
+ };
1070
+ } catch (error) {
1071
+ return {
1072
+ topology: void 0,
1073
+ diagnostics: [this.topologyFailure(error)]
1074
+ };
1075
+ }
805
1076
  }
806
1077
  /**
807
- * The packages whose files {@link codeOf} finds by npm package name, because the build record names no
808
- * chunk of a loader of theirs. Their bytes are less exact.
1078
+ * Write the generated files into {@link outputDirectory}, and prune the stale ones. The files that another
1079
+ * step writes there, such as the deploy target record of `@heximon/nuxt`, stay.
809
1080
  *
810
- * @param identities - The packages, by identity.
1081
+ * @param files - The files of the compile output.
811
1082
  */
812
- byPackageName(identities) {
813
- return identities.filter((identity) => !this.loaderChunks.has(identity));
1083
+ write(files) {
1084
+ this.compiler.write(this.outputDirectory, files, { retain: this.retainedOutput });
1085
+ }
1086
+ /** The platform the session compiles for, or `undefined` for the zero-config Node default. */
1087
+ platformName() {
1088
+ return this.strategy.platformName;
814
1089
  }
815
1090
  /**
816
- * How many files a set has, and their bytes.
1091
+ * Why a Nitro or Nuxt host compiles for the Node default and not for the deploy target of its build.
817
1092
  *
818
- * @param files - The files.
1093
+ * @returns One info diagnostic, or `undefined` when the session compiles for the target of the build.
819
1094
  */
820
- sizeOf(files) {
821
- let bytes = 0;
822
- for (const file of files) bytes += this.bytesByFile.get(file) ?? 0;
823
- return {
824
- files: files.size,
825
- bytes
826
- };
1095
+ targetNote() {
1096
+ return this.hostTargetNote;
1097
+ }
1098
+ /** The runtime class the session compiles for: `node` or `edge`. */
1099
+ targetClass() {
1100
+ return this.strategy.targetClass;
827
1101
  }
828
1102
  /**
829
- * About how many bytes of some files belong to each package. A chunk gives each of its packages a part of its
830
- * bytes, in the ratio of their rendered code. A file of a package's `node_modules` directory belongs to the
831
- * package. Other bytes, such as a runtime helper of the bundler, belong to no package.
1103
+ * Run the compile `vp build` runs, into a chosen directory: the production graph with the sidecar's wiring
1104
+ * mode, diagnostic dials and cross-service topology. {@link compile} leaves out the first two, and reads the
1105
+ * topology only when its caller passes it.
832
1106
  *
833
- * @param files - The files.
834
- * @returns The bytes of each package, by package name.
1107
+ * @param outputDirectory - The directory the generated files will be written to. It must sit directly
1108
+ * under the project root, because the generated imports of the app source are relative to it.
1109
+ * @param aliases - The module aliases of the project (prefix → absolute path), when it has some.
1110
+ * @returns The compile output. Nothing is written.
835
1111
  */
836
- packageBytes(files) {
837
- const bytesByPackage = /* @__PURE__ */ new Map();
838
- for (const file of files) for (const [name, bytes] of Object.entries(this.packagesOfFile(file))) bytesByPackage.set(name, (bytesByPackage.get(name) ?? 0) + bytes);
839
- return bytesByPackage;
1112
+ async compileProduction(outputDirectory, aliases = {
1113
+ exact: {},
1114
+ prefixes: {}
1115
+ }) {
1116
+ const workspaceSubscribers = await WorkspaceTopologyReader.resolveFromConfig(this.rootDir, this.plugins, this.config, this.environment);
1117
+ return this.compiler.compile({
1118
+ rootDir: this.rootDir,
1119
+ outputDirectory,
1120
+ plugins: this.plugins,
1121
+ strategy: this.strategy,
1122
+ environment: CompileEnvironment.Production,
1123
+ aliases: aliases.prefixes,
1124
+ exactAliases: aliases.exact,
1125
+ ...this.sourceDirectories === void 0 ? {} : { sourceDirectories: this.sourceDirectories },
1126
+ ...this.config === void 0 ? {} : { config: this.config },
1127
+ ...this.config?.wiringMode === void 0 ? {} : { wiringMode: this.config.wiringMode },
1128
+ ...this.config?.strictDiagnostics === void 0 ? {} : { strictDiagnostics: this.config.strictDiagnostics },
1129
+ ...this.config?.suppressDiagnostics === void 0 ? {} : { suppressDiagnostics: this.config.suppressDiagnostics },
1130
+ ...this.runtimeConfig === void 0 ? {} : { runtimeConfig: this.runtimeConfig },
1131
+ ...this.config?.root === void 0 ? {} : { apps: { main: this.config.root } },
1132
+ ...workspaceSubscribers === void 0 ? {} : { workspaceSubscribers }
1133
+ });
840
1134
  }
841
1135
  /**
842
- * Some files and every file that they import, without the files that are loaded already. With `boundary`, the
843
- * walk follows `import()` too, but not into a file of `boundary`.
1136
+ * Run the library-mode compile — a published module package goes through the same {@link LibraryEmitter}
1137
+ * its own `vp pack` build uses, rather than being compiled as an app. Not a byte-for-byte replay of that
1138
+ * build: the pack host supplies its own plugin set, wiring mode and `pack.entry`-derived publication set,
1139
+ * while this reads plugins from the config sidecar and falls back to the committed `exports` map.
1140
+ *
1141
+ * Two things make the app-mode compile wrong here, not merely noisy. It enforces every `requires` hop-by-hop
1142
+ * against a host binding, while a library leaves that seam open on purpose (the published factory reads a
1143
+ * required token as a constructor input); and it looks for one root module, while a multi-root package
1144
+ * publishes several. Both surface as errors a `vp pack` of the same source never raises.
1145
+ *
1146
+ * @param options - `pruneVerdicts` also removes a verdict mirror an EARLIER app-mode run wrote. Library
1147
+ * mode emits none to replace it, so nothing would ever overwrite those app-mode-only errors — only
1148
+ * `heximon check`, which owns the mirror, asks for it. Every other verb stays write-free.
1149
+ * @returns The compile's diagnostics, files and graph projections; a throwing emit becomes one diagnostic.
844
1150
  */
845
- reach(seeds, loaded, boundary) {
846
- const reached = /* @__PURE__ */ new Set();
847
- const pending = seeds.filter((file) => !loaded.has(file));
848
- for (let file = pending.pop(); file !== void 0; file = pending.pop()) {
849
- if (reached.has(file)) continue;
850
- reached.add(file);
851
- const targets = [...StartupBuiltCode.importsOf(this.measured.staticImports, file), ...boundary === void 0 ? [] : StartupBuiltCode.importsOf(this.measured.dynamicImports, file).filter((target) => !boundary.has(target))];
852
- for (const target of targets) if (!loaded.has(target) && !reached.has(target)) pending.push(target);
1151
+ compileLibrary(options = {}) {
1152
+ const sourceDirectory = this.sourceDirectories?.[0] ?? (this.config?.sourceDirectory === void 0 ? void 0 : resolve(this.rootDir, this.config.sourceDirectory));
1153
+ const prunedVerdicts = options.pruneVerdicts === true ? this.compiler.pruneTypeVerdicts({
1154
+ rootDir: this.rootDir,
1155
+ ...sourceDirectory === void 0 ? {} : { sourceDirectories: [sourceDirectory] }
1156
+ }) : void 0;
1157
+ try {
1158
+ const emitted = new LibraryEmitter(this.compiler).compile({
1159
+ rootDir: this.rootDir,
1160
+ plugins: this.plugins,
1161
+ ...sourceDirectory === void 0 ? {} : { sourceDirectory },
1162
+ ...this.config === void 0 ? {} : { config: this.config }
1163
+ });
1164
+ return {
1165
+ diagnostics: emitted.diagnostics,
1166
+ files: emitted.files,
1167
+ moduleGraph: emitted.moduleGraph,
1168
+ boundaryNodes: emitted.boundaryNodes,
1169
+ ...prunedVerdicts === void 0 ? {} : { prunedVerdicts }
1170
+ };
1171
+ } catch (error) {
1172
+ return {
1173
+ diagnostics: [{
1174
+ severity: DiagnosticSeverity.Error,
1175
+ message: `The library compile of this package failed: ${error instanceof Error ? error.message : String(error)}`,
1176
+ location: this.rootDir
1177
+ }],
1178
+ files: [],
1179
+ moduleGraph: void 0,
1180
+ boundaryNodes: [],
1181
+ ...prunedVerdicts === void 0 ? {} : { prunedVerdicts }
1182
+ };
853
1183
  }
854
- return reached;
855
- }
856
- /** The chunk of the loader of each package, or the files of its npm package. */
857
- seedsOf(identities) {
858
- return [...new Set(identities.flatMap((identity) => this.loaderChunks.get(identity) ?? this.packageNameFilesOf(identity)))];
859
- }
860
- /** The loader chunks of the packages that are not in `identities`. */
861
- loaderChunksOutside(identities) {
862
- return new Set([...this.loaderChunks].filter(([identity]) => !identities.has(identity)).flatMap(([, chunks]) => chunks));
863
1184
  }
864
1185
  /**
865
- * The files of the npm package of a root, without the files that only the other roots of the package reach
866
- * beyond the static start: those load on the first use of the other roots. A file that the root reaches from
867
- * its own files stays, as the walk cannot show that only the other roots load it.
1186
+ * One error diagnostic for each library the last compile consumed whose source changed since its last
1187
+ * pack. The compile read old wiring for it, so the verdicts of that compile cannot be trusted. Each
1188
+ * message is the `heximon doctor` line for the library.
1189
+ *
1190
+ * @returns The diagnostics, or an empty list when every consumed library is current.
868
1191
  */
869
- packageNameFilesOf(identity) {
870
- const name = StartupBuiltCode.packageNameOf(identity);
871
- const files = this.filesByPackage.get(name) ?? [];
872
- const others = [...this.loaderChunks].filter(([other]) => other !== identity && StartupBuiltCode.packageNameOf(other) === name);
873
- if (others.length === 0) return files;
874
- const otherFiles = new Set(others.flatMap(([other, chunks]) => {
875
- const closure = this.loaderClosures.get(other) ?? this.reach(chunks, this.staticStart, this.loaderChunksOutside(/* @__PURE__ */ new Set([other])));
876
- this.loaderClosures.set(other, closure);
877
- return [...closure];
1192
+ async staleLibraryDiagnostics() {
1193
+ return (await new LibraryFreshness().findStale(this.compiler.consumedBoundaryPackages())).map((library) => ({
1194
+ severity: DiagnosticSeverity.Error,
1195
+ message: LibraryFreshness.staleLine(library.specifier, library.report),
1196
+ location: library.report.packageDirectory
878
1197
  }));
879
- const ownFiles = this.reach(files.filter((file) => !otherFiles.has(file)), /* @__PURE__ */ new Set(), this.loaderChunksOutside(/* @__PURE__ */ new Set([identity])));
880
- return files.filter((file) => !otherFiles.has(file) || ownFiles.has(file));
881
1198
  }
882
- /** The targets of one file in an import table of the walk. */
883
- static importsOf(imports, file) {
884
- return Object.hasOwn(imports, file) ? imports[file] ?? [] : [];
1199
+ /** The `rootDir` + `sourceDirectories` pair the type-verdict write path keys on, plus the runtime config file. */
1200
+ typeVerdictTarget() {
1201
+ return {
1202
+ rootDir: this.rootDir,
1203
+ ...this.runtimeConfig === void 0 ? {} : { runtimeConfigFile: this.runtimeConfig.file },
1204
+ ...this.sourceDirectories === void 0 ? {} : { sourceDirectories: this.sourceDirectories }
1205
+ };
885
1206
  }
886
1207
  /**
887
- * The chunks that hold the loader file of each package with a loader. A loader whose chunk the walk did not
888
- * reach, or is in the static start closure, or holds the loader of another package, gives no chunks.
1208
+ * The diagnostic for a topology read that threw. The reader puts the code of a known failure on the error
1209
+ * and at the start of its message; the diagnostic carries the code once, in its own field.
889
1210
  */
890
- loaderChunksOf(generated, loaders) {
891
- const loaderFiles = new Set(Object.values(loaders));
892
- const startFiles = new Set(this.staticStartFiles());
893
- const chunksByLoader = /* @__PURE__ */ new Map();
894
- for (const [chunk, files] of Object.entries(generated)) for (const file of files) if (loaderFiles.has(file)) chunksByLoader.set(file, [...chunksByLoader.get(file) ?? [], chunk]);
895
- const chunks = /* @__PURE__ */ new Map();
896
- for (const [identity, loader] of Object.entries(loaders)) {
897
- const holders = chunksByLoader.get(loader) ?? [];
898
- const isOwnChunk = holders.every((chunk) => this.bytesByFile.has(chunk) && !startFiles.has(chunk) && (Object.hasOwn(generated, chunk) ? generated[chunk] ?? [] : []).every((file) => file === loader || !loaderFiles.has(file)));
899
- if (holders.length > 0 && isOwnChunk) chunks.set(identity, holders);
900
- }
901
- return chunks;
902
- }
903
- /** The bytes of one file that belong to each package, by package name. */
904
- packagesOfFile(file) {
905
- const fileBytes = this.bytesByFile.get(file) ?? 0;
906
- const rendered = Object.hasOwn(this.chunks, file) ? this.chunks[file] : void 0;
907
- if (rendered !== void 0) {
908
- const total = Object.values(rendered).reduce((sum, bytes) => sum + bytes, 0);
909
- return total === 0 ? {} : Object.fromEntries(Object.entries(rendered).map(([name, bytes]) => [name, Math.round(fileBytes * bytes / total)]));
910
- }
911
- const name = StartupBuiltCode.installedPackageOf(file);
912
- return name === void 0 ? {} : { [name]: fileBytes };
913
- }
914
- /** The package of a file in a `node_modules` directory of the output, or `undefined`. */
915
- static installedPackageOf(file) {
916
- const index = file.lastIndexOf(StartupBuiltCode.packageDirectory);
917
- if (index === -1 || index > 0 && file[index - 1] !== "/") return;
918
- const segments = file.slice(index + StartupBuiltCode.packageDirectory.length).split("/");
919
- const length = segments[0]?.startsWith("@") === true ? 2 : 1;
920
- return segments.length > length ? segments.slice(0, length).join("/") : void 0;
1211
+ topologyFailure(error) {
1212
+ const message = error instanceof Error ? error.message : String(error);
1213
+ const code = error?.code;
1214
+ const knownCode = Object.values(DiagnosticCode).find((candidate) => candidate === code);
1215
+ return {
1216
+ severity: DiagnosticSeverity.Error,
1217
+ message: knownCode !== void 0 && message.startsWith(`[${knownCode}] `) ? message.slice(knownCode.length + 3) : message,
1218
+ location: this.rootDir,
1219
+ hint: ProjectCompileSession.topologyFailureHint,
1220
+ ...knownCode === void 0 ? {} : { code: knownCode }
1221
+ };
921
1222
  }
922
1223
  };
923
1224
  //#endregion
924
- //#region src/startup-entry-reasons.ts
1225
+ //#region src/source-directories.ts
925
1226
  /**
926
- * The reasons of the entries report, named by the kind that the compile records. A reason that the compile
927
- * does not record is "reason not recorded": the report does not guess a kind for it.
1227
+ * Resolves which directories the host-agnostic compile commands (`check`, `graph`, `routes`) scan for Heximon
1228
+ * source. The compiler's own default is `<rootDir>/src`; a Nitro/Nuxt host instead keeps its modules under
1229
+ * `server/` and passes that directory to the compiler from its own build. The standalone CLI is just another
1230
+ * host, so it detects that layout and passes `server/` too — otherwise its compile finds no modules.
928
1231
  */
929
- var StartupEntryReasons = class StartupEntryReasons {
930
- /** The kind of code that a loaded file imports, and that is not a composed package. */
931
- static importKind = "import";
932
- /** The kind of a module whose reason the compile does not record. */
933
- static notRecordedKind = "not-recorded";
934
- /** The entries of the report, as `<kind> <key>`. */
935
- places;
936
- /** The identities of the composed packages of the report. */
937
- packages;
938
- /** @param report - The start report of the app. */
939
- constructor(report) {
940
- this.places = new Set(report.entries.map((entry) => `${entry.kind} ${entry.key}`));
941
- this.packages = /* @__PURE__ */ new Set([
942
- ...report.start.map((entry) => entry.package),
943
- ...report.entries.flatMap((entry) => entry.packages),
944
- ...(report.loads?.asyncRegistries ?? []).flatMap((registry) => [registry.owner, ...registry.packages.map((entry) => entry.package)])
945
- ]);
946
- }
947
- /** The reason of code that a loaded file imports, and that is not a composed package. */
948
- static imported() {
949
- return {
950
- kind: StartupEntryReasons.importKind,
951
- text: "import of a loaded file, not a composed package"
952
- };
953
- }
954
- /** The reason of a module whose reason the compile does not record. */
955
- static notRecorded() {
956
- return {
957
- kind: StartupEntryReasons.notRecordedKind,
958
- text: "reason not recorded"
959
- };
960
- }
1232
+ var SourceDirectories = class SourceDirectories {
1233
+ /** Host-framework config basenames whose presence marks a project that roots its modules under `server/`. */
1234
+ static serverHostConfigNames = [
1235
+ "nuxt.config.ts",
1236
+ "nuxt.config.mts",
1237
+ "nuxt.config.js",
1238
+ "nuxt.config.mjs",
1239
+ "nitro.config.ts",
1240
+ "nitro.config.mts",
1241
+ "nitro.config.js",
1242
+ "nitro.config.mjs"
1243
+ ];
961
1244
  /**
962
- * One reason of the start report, with its text.
1245
+ * The absolute source directories to scan, or `undefined` to accept the compiler's own `<rootDir>/src`
1246
+ * default. An explicit `--src` (comma-separated) always wins; otherwise, when the project has no `src/` but
1247
+ * is a Nitro/Nuxt host carrying a `server/` directory, that directory is scanned.
963
1248
  *
964
- * @param reason - The reason, as the compile records it.
1249
+ * @param rootDir - The absolute project root.
1250
+ * @param sourceOption - The raw `--src` argument, when the caller passed one.
1251
+ * @returns Absolute directories, or `undefined` for the compiler default.
965
1252
  */
966
- describe(reason) {
967
- return {
968
- kind: reason.kind,
969
- ...reason.source === void 0 ? {} : { source: reason.source },
970
- ...reason.tokens === void 0 ? {} : { tokens: reason.tokens },
971
- text: this.textOf(reason)
972
- };
973
- }
974
- /** The text of one reason. */
975
- textOf(reason) {
976
- const { source } = reason;
977
- switch (reason.kind) {
978
- case StartReasonKind.Dependency: return this.dependencyText(reason);
979
- case StartReasonKind.SealGroup: return `seal group of the sync registry ${source ?? "(registry not recorded)"}`;
980
- case StartReasonKind.ContributesTo: return `contributor to the registry ${source ?? "(registry not recorded)"}`;
981
- case StartReasonKind.ContributionCannotWait: return `contribution section that cannot wait${source === void 0 ? "" : `: ${source}`}`;
982
- case StartReasonKind.RegistrarOptions: return `registrar options of the plugin ${source ?? "(plugin not recorded)"}`;
983
- case StartReasonKind.PluginNeedsAtStart: return `a compiler plugin needs it at the start${source === void 0 ? "" : `: ${source}`}`;
984
- case StartReasonKind.LazyRead: return `Lazy<T> read${source === void 0 ? "" : `: ${source}`}`;
985
- case StartReasonKind.EagerProvider: return `eager provider${source === void 0 ? "" : ` ${source}`}`;
986
- case StartReasonKind.BootHook: return "boot hook";
987
- case StartReasonKind.ConfigSection: return "config section";
988
- case StartReasonKind.DispatchInventory: return "DispatchInventory read";
989
- case StartReasonKind.NotDeferred: return "the target does not defer packages";
990
- default: return source === void 0 ? String(reason.kind) : `${String(reason.kind)}: ${source}`;
1253
+ static resolve(rootDir, sourceOption) {
1254
+ if (sourceOption !== void 0 && sourceOption.trim() !== "") {
1255
+ const directories = sourceOption.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0).map((entry) => resolve(rootDir, entry));
1256
+ if (directories.length > 0) return directories;
991
1257
  }
1258
+ if (SourceDirectories.isDirectory(join(rootDir, "src"))) return;
1259
+ if (SourceDirectories.isServerHost(rootDir) && SourceDirectories.isDirectory(join(rootDir, "server"))) return [join(rootDir, "server")];
992
1260
  }
993
- /** The text of a dependency: on the first use of an entry, or a wait of a package with its DI tokens. */
994
- dependencyText(reason) {
995
- const { source, tokens } = reason;
996
- if (source === void 0) return "dependency (source not recorded)";
997
- if (this.places.has(source)) return `first use of the entry '${source}'`;
998
- if (!this.packages.has(source)) return `dependency of ${source}`;
999
- return tokens === void 0 || tokens.length === 0 ? `dependency of ${source} (token not recorded)` : `DI dependency of ${source}, ${tokens.length === 1 ? "token" : "tokens"} ${tokens.join(", ")}`;
1261
+ /** Whether the root carries a Nitro/Nuxt host config, which roots Heximon modules under `server/`. */
1262
+ static isServerHost(rootDir) {
1263
+ return SourceDirectories.serverHostConfigNames.some((name) => existsSync(join(rootDir, name)));
1264
+ }
1265
+ /** Whether `path` exists and is a directory. */
1266
+ static isDirectory(path) {
1267
+ try {
1268
+ return statSync(path).isDirectory();
1269
+ } catch {
1270
+ return false;
1271
+ }
1000
1272
  }
1001
1273
  };
1002
1274
  //#endregion
1003
- //#region src/startup-size-check.ts
1275
+ //#region src/startup-baseline.ts
1004
1276
  /**
1005
- * The size half of `heximon check --startup`: it measures the built server code from the entry that the last
1006
- * build recorded ({@link ServerBuildRecord}), and compares the measures with the `size` section of
1007
- * `heximon.startup.json`. Without build output, the check skips it.
1277
+ * The command side of the committed startup baseline: it reads and writes `heximon.startup.json`, and turns a
1278
+ * comparison into the errors and notes of `heximon check --startup`.
1008
1279
  */
1009
- var StartupSizeCheck = class StartupSizeCheck {
1280
+ var StartupBaseline = class StartupBaseline {
1010
1281
  /** The command that writes the file. */
1011
1282
  static updateCommand = "heximon check --startup --update";
1012
- /** How many requests that the walk could not follow a note names. */
1013
- static namedGapCount = 5;
1014
1283
  /**
1015
- * Measure the server code of the last build.
1284
+ * Compares the start reports of a compile with the committed file.
1016
1285
  *
1017
- * @param rootDir - The app root.
1018
- * @returns The measurement, or why there is none.
1286
+ * @param rootDir - The app root that holds the committed file.
1287
+ * @param reports - The start reports of the compile.
1019
1288
  */
1020
- static measure(rootDir) {
1021
- const reading = ServerBuildRecord.read(rootDir);
1022
- const skip = (reason, message) => ({
1023
- kind: "skipped",
1024
- result: {
1025
- action: "skipped",
1026
- reason,
1027
- record: reading.file
1028
- },
1029
- message: `${message} The size check of the server code is skipped.`
1030
- });
1031
- if (reading.kind === "absent") return skip("no-build-output", `There is no build output: the build writes ${ServerBuildRecord.relativePath}, and the file is absent. Build the app before the check to check the size of its server code.`);
1032
- if (reading.kind === "unreadable") return skip("record-unreadable", `${reading.message} Build the app again.`);
1033
- const names = Object.keys(reading.entries).sort();
1034
- const missing = names.map((name) => reading.entries[name].path).find((path) => !StartupSizeCheck.isFile(path) || !existsSync(reading.outputDirectory));
1035
- if (missing !== void 0) return skip("entry-missing", `The build record names the server entry ${relative(rootDir, missing)}, and the file does not exist. Build the app again.`);
1036
- const entries = names.map((name) => {
1037
- const entry = reading.entries[name];
1038
- const graph = ServerCodeWalk.graph(rootDir, reading.outputDirectory, entry.path, entry.target);
1039
- return {
1040
- name,
1041
- measurement: graph.measurement,
1042
- staticImports: graph.staticImports,
1043
- dynamicImports: graph.dynamicImports
1044
- };
1045
- });
1046
- return {
1047
- kind: "measured",
1048
- entries,
1049
- section: Object.fromEntries(entries.map(({ name, measurement }) => [name, StartupSizeBudget.recordOf(measurement)])),
1050
- ...reading.chunks === void 0 ? {} : { chunks: reading.chunks },
1051
- ...reading.generated === void 0 ? {} : { generated: reading.generated }
1052
- };
1053
- }
1054
- /**
1055
- * Compare a measurement with the committed file.
1056
- *
1057
- * @param committed - The committed file, parsed, or `undefined` when there is no usable file. The startup
1058
- * check reports that case, so the size check adds no error.
1059
- * @param measured - The measurement.
1060
- */
1061
- static compare(committed, measured) {
1062
- const file = StartupBaselineFile.fileName;
1063
- const notes = StartupSizeCheck.measurementLines(measured);
1289
+ static check(rootDir, reports) {
1290
+ const target = join(rootDir, StartupBaselineFile.fileName);
1291
+ const committed = StartupBaseline.readCommitted(target);
1064
1292
  const cliCodes = /* @__PURE__ */ new Map();
1065
- if (committed === void 0) return {
1066
- result: {
1067
- action: "compare",
1068
- entries: StartupSizeCheck.entriesOf(measured, void 0),
1069
- committed: false,
1070
- reason: "no-baseline"
1071
- },
1072
- diagnostics: [],
1073
- cliCodes,
1074
- notes
1075
- };
1076
- const baseline = StartupSizeBudget.parse(committed);
1077
- if (baseline === null || baseline === void 0) {
1293
+ if (committed === void 0 || committed.records === void 0) {
1294
+ const missing = committed === void 0;
1078
1295
  const diagnostic = {
1079
1296
  severity: DiagnosticSeverity.Error,
1080
- message: baseline === null ? `${file} has no size section, and the build output exists (${measured.entries.map(({ measurement }) => measurement.entry).join(", ")}), so the size check has nothing to compare with.` : `The size section of ${file} has another shape, so the size check cannot read it.`,
1081
- hint: `Run \`${StartupSizeCheck.updateCommand}\` after the build and commit the file.`
1297
+ message: missing ? `there is no committed ${StartupBaselineFile.fileName}, so the startup check has nothing to compare with.` : `${StartupBaselineFile.fileName} is not a version ${StartupBaselineFile.version} startup baseline, so the startup check cannot read it.`,
1298
+ hint: `Run \`${StartupBaseline.updateCommand}\` and commit the file.`
1082
1299
  };
1083
- cliCodes.set(diagnostic, baseline === null ? CheckDiagnosticCode.StartupSizeUnrecorded : CheckDiagnosticCode.StartupBaselineUnreadable);
1300
+ cliCodes.set(diagnostic, missing ? CheckDiagnosticCode.StartupBaselineMissing : CheckDiagnosticCode.StartupBaselineUnreadable);
1084
1301
  return {
1085
1302
  result: {
1086
1303
  action: "compare",
1087
- entries: StartupSizeCheck.entriesOf(measured, void 0),
1304
+ path: target,
1088
1305
  committed: false,
1089
- reason: baseline === null ? "unrecorded" : "unreadable"
1306
+ reason: missing ? "missing" : "unreadable"
1090
1307
  },
1091
1308
  diagnostics: [diagnostic],
1092
1309
  cliCodes,
1093
- notes
1310
+ notes: []
1094
1311
  };
1095
1312
  }
1096
- const comparison = StartupSizeBudget.compare(baseline, measured.section);
1313
+ const comparison = StartupBaselineFile.compareRecords(committed.records, reports);
1097
1314
  const diagnostics = comparison.growth.map((change) => {
1098
- const isAdded = change.kind === StartupSizeChangeKind.EntryAdded;
1099
1315
  const diagnostic = {
1100
1316
  severity: DiagnosticSeverity.Error,
1101
- message: isAdded ? `The build has the server entry '${change.name}' (${String(change.current)}), and the size section of ${file} does not record it, so the size check has nothing to compare it with.` : StartupSizeCheck.growthMessage(change, measured.section[change.name]?.entry ?? change.name),
1102
- hint: isAdded ? `Run \`${StartupSizeCheck.updateCommand}\` after the build and commit the file.` : `Find what the new files bring into the server code (a static import that can be an \`import()\`, or a new package), or accept the growth: run \`${StartupSizeCheck.updateCommand}\` after the build and commit the file.`
1317
+ message: StartupBaseline.growthMessage(change),
1318
+ hint: change.kind === StartupChangeKind.HostlessGrowth ? `Find the import that brings the module into the hostless app, or accept the growth: run \`${StartupBaseline.updateCommand}\` and commit the file.` : `Make the package wait for its first use (see the reasons), or accept the growth: run \`${StartupBaseline.updateCommand}\` and commit the file.`
1103
1319
  };
1104
- cliCodes.set(diagnostic, isAdded ? CheckDiagnosticCode.StartupSizeUnrecorded : CheckDiagnosticCode.StartupSizeGrowth);
1320
+ cliCodes.set(diagnostic, CheckDiagnosticCode.StartupGrowth);
1105
1321
  return diagnostic;
1106
1322
  });
1107
1323
  return {
1108
1324
  result: {
1109
1325
  action: "compare",
1110
- entries: StartupSizeCheck.entriesOf(measured, baseline),
1326
+ path: target,
1111
1327
  committed: true,
1112
1328
  growth: comparison.growth,
1113
1329
  notes: comparison.notes
1114
1330
  },
1115
1331
  diagnostics,
1116
1332
  cliCodes,
1117
- notes: [...notes, ...StartupSizeCheck.noteLines(comparison.notes, measured.section)]
1333
+ notes: StartupBaseline.noteLines(comparison.notes)
1118
1334
  };
1119
1335
  }
1120
1336
  /**
1121
- * The outcome of `--startup --update` for a measurement.
1337
+ * The committed file, parsed, when it is a startup baseline that this version reads.
1122
1338
  *
1123
- * @param measured - The measurement.
1124
- * @param written - Whether the file was written or confirmed.
1339
+ * @param rootDir - The app root that holds the committed file.
1125
1340
  */
1126
- static updated(measured, written) {
1127
- return {
1128
- result: {
1129
- action: "update",
1130
- entries: StartupSizeCheck.entriesOf(measured, void 0),
1131
- written
1132
- },
1133
- notes: StartupSizeCheck.measurementLines(measured)
1134
- };
1341
+ static committedDocument(rootDir) {
1342
+ const committed = StartupBaseline.readCommitted(join(rootDir, StartupBaselineFile.fileName));
1343
+ return committed?.records === void 0 ? void 0 : committed.document;
1135
1344
  }
1136
1345
  /**
1137
- * A number of bytes for a person to read: bytes, KiB with one decimal, or MiB with two.
1346
+ * Writes the file for the start reports of a compile when it differs from the committed one. The other
1347
+ * top-level sections of the committed file stay as they are.
1138
1348
  *
1139
- * @param bytes - The number of bytes.
1349
+ * @param rootDir - The app root that holds the committed file.
1350
+ * @param reports - The start reports of the compile.
1351
+ * @param size - The size of the built server code. Without it, the committed size section stays.
1352
+ * @returns The path, and whether the content changed.
1140
1353
  */
1141
- static formatBytes(bytes) {
1142
- if (bytes < 1024) return `${bytes} B`;
1143
- if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KiB`;
1144
- return `${(bytes / 1048576).toFixed(2)} MiB`;
1145
- }
1146
- /** The entries of a result, each with the measures that the committed section records for its name. */
1147
- static entriesOf(measured, baseline) {
1148
- return measured.entries.map(({ name, measurement }) => {
1149
- const recorded = baseline !== void 0 && Object.hasOwn(baseline, name) ? baseline[name] : void 0;
1150
- return {
1151
- name,
1152
- entry: measurement.entry,
1153
- measured: {
1154
- start: measurement.start,
1155
- total: measurement.total
1156
- },
1157
- ...recorded === void 0 ? {} : { baseline: {
1158
- start: recorded.start,
1159
- total: recorded.total
1160
- } },
1161
- gaps: measurement.gaps,
1162
- unparsed: measurement.unparsed
1163
- };
1164
- });
1165
- }
1166
- /** The summary and gap lines of each measured entry. */
1167
- static measurementLines(measured) {
1168
- return measured.entries.flatMap(({ measurement }) => [StartupSizeCheck.summaryLine(measurement), ...StartupSizeCheck.gapLines(measurement)]);
1169
- }
1170
- /** The line with the measures. */
1171
- static summaryLine(measurement) {
1172
- const size = (value) => `${value.files} file${value.files === 1 ? "" : "s"}, ${StartupSizeCheck.formatBytes(value.bytes)}`;
1173
- return `Server code of ${measurement.entry}: the static start closure has ${size(measurement.start)}; the total server code has ${size(measurement.total)}.`;
1174
- }
1175
- /** The lines about requests that the walk could not follow, and files that do not parse. */
1176
- static gapLines(measurement) {
1177
- const lines = [];
1178
- const gaps = measurement.gaps;
1179
- if (gaps.length > 0) {
1180
- const named = gaps.slice(0, StartupSizeCheck.namedGapCount).map((gap) => `${gap.importer} → ${gap.request}`).join("; ");
1181
- lines.push(`The size walk could not follow ${gaps.length} request${gaps.length === 1 ? "" : "s"} (${named}${gaps.length > StartupSizeCheck.namedGapCount ? "; …" : ""}), so the measures can be too small.`);
1182
- }
1183
- if (measurement.unparsed.length > 0) lines.push(`The size walk could not parse ${measurement.unparsed.join(", ")}, so the imports of ${measurement.unparsed.length === 1 ? "that file are" : "those files are"} not counted.`);
1184
- return lines;
1354
+ static update(rootDir, reports, size) {
1355
+ const target = join(rootDir, StartupBaselineFile.fileName);
1356
+ const committed = StartupBaseline.readCommitted(target);
1357
+ const content = StartupBaselineFile.compose(reports, committed?.document, size === void 0 ? {} : { [StartupSizeBudget.sectionKey]: size });
1358
+ const changed = committed?.content !== content;
1359
+ if (changed) writeFileSync(target, content);
1360
+ return {
1361
+ target,
1362
+ changed
1363
+ };
1185
1364
  }
1186
1365
  /** The error text of one growth. */
1187
- static growthMessage(change, entry) {
1188
- const measure = change.measure ?? StartupSizeMeasure.StartBytes;
1189
- const format = (value) => typeof value === "number" ? StartupSizeCheck.formatValue(measure, value) : String(value);
1190
- const files = (change.files ?? []).map((file) => `${file.path} (${file.isNew ? `${StartupSizeCheck.formatBytes(file.bytes)}, new` : `+${StartupSizeCheck.formatBytes(file.growth)}`})`).join(", ");
1191
- return `${StartupSizeCheck.measureName(measure)} of ${entry} is now ${format(change.current)}, and ${StartupBaselineFile.fileName} records ${format(change.committed)} with a slack of ${format(change.slack ?? 0)}.${files.length > 0 ? ` Largest new or grown files: ${files}.` : ""}`;
1192
- }
1193
- /** The note lines of the changes that do not fail. */
1194
- static noteLines(notes, section) {
1366
+ static growthMessage(change) {
1195
1367
  const file = StartupBaselineFile.fileName;
1368
+ switch (change.kind) {
1369
+ case StartupChangeKind.NewApp: return `app '${change.app}' has no record in ${file}, so every package of its start is new.`;
1370
+ case StartupChangeKind.EntryGrowth: return `app '${change.app}': the first use of '${change.place}' now loads '${change.package}', and ${file} does not list it for this entry.`;
1371
+ case StartupChangeKind.HostlessGrowth: return `hostless app '${change.app}': the module '${change.module}' is now in the app, and ${file} does not list it there.`;
1372
+ default: return `app '${change.app}': '${change.package}' now loads at the start, and ${file} does not list it there. Reasons: ${(change.reasons ?? []).join("; ")}.`;
1373
+ }
1374
+ }
1375
+ /** The note lines: one per change that does not fail, and one line that says the file can be smaller. */
1376
+ static noteLines(notes) {
1196
1377
  const lines = notes.map((change) => {
1197
- if (change.kind === StartupSizeChangeKind.EntryChanged) return `The server entry '${change.name}' is now ${String(change.current)}, and ${file} records ${String(change.committed)}.`;
1198
- if (change.kind === StartupSizeChangeKind.EntryRemoved) return `The build no longer has the server entry '${change.name}' (${String(change.committed)}) that ${file} records.`;
1199
- const measure = change.measure ?? StartupSizeMeasure.StartBytes;
1200
- return `${StartupSizeCheck.measureName(measure)} of ${section[change.name]?.entry ?? change.name} is now ${StartupSizeCheck.formatValue(measure, Number(change.current))}, less than the ${StartupSizeCheck.formatValue(measure, Number(change.committed))} that ${file} records.`;
1378
+ switch (change.kind) {
1379
+ case StartupChangeKind.StartShrink: return `app '${change.app}': '${change.package}' no longer loads at the start.`;
1380
+ case StartupChangeKind.EntryShrink: return `app '${change.app}': the first use of '${change.place}' no longer loads '${change.package}'.`;
1381
+ case StartupChangeKind.NewEntry: return `app '${change.app}': '${change.place}' is a new entry.`;
1382
+ case StartupChangeKind.RemovedEntry: return `app '${change.app}': '${change.place}' is no longer an entry.`;
1383
+ case StartupChangeKind.RemovedApp: return `app '${change.app}' is no longer built.`;
1384
+ case StartupChangeKind.TargetChanged: return `app '${change.app}': the deploy target changed whether it defers packages.`;
1385
+ case StartupChangeKind.HostlessShrink: return `hostless app '${change.app}': the module '${change.module}' is no longer in the app.`;
1386
+ case StartupChangeKind.NewHostless: return `hostless app '${change.app}' is new.`;
1387
+ case StartupChangeKind.RemovedHostless: return `hostless app '${change.app}' is no longer built.`;
1388
+ default: return `app '${change.app}': '${change.package}' loads at the start for other reasons: ${(change.reasons ?? []).join("; ")}.`;
1389
+ }
1201
1390
  });
1202
1391
  if (lines.length === 0) return [];
1203
- return [...lines, `Run \`${StartupSizeCheck.updateCommand}\` after the build to record the new size of the server code.`];
1392
+ const shrinks = notes.some((change) => change.kind === StartupChangeKind.StartShrink || change.kind === StartupChangeKind.EntryShrink || change.kind === StartupChangeKind.HostlessShrink);
1393
+ return [...lines, shrinks ? `The app loads less than ${StartupBaselineFile.fileName} records. Run \`${StartupBaseline.updateCommand}\` to make the baseline smaller.` : `Run \`${StartupBaseline.updateCommand}\` to record these changes.`];
1204
1394
  }
1205
- /** The name of a measure, at the start of a sentence. */
1206
- static measureName(measure) {
1207
- switch (measure) {
1208
- case StartupSizeMeasure.StartFiles: return "The file count of the static start closure";
1209
- case StartupSizeMeasure.TotalBytes: return "The total server code";
1210
- default: return "The static start closure";
1395
+ /** The committed file's text, its parsed form, and its app records, or `undefined` when the file is absent. */
1396
+ static readCommitted(target) {
1397
+ let content;
1398
+ try {
1399
+ content = readFileSync(target, "utf8");
1400
+ } catch {
1401
+ return;
1211
1402
  }
1212
- }
1213
- /** A value of a measure for a person to read. */
1214
- static formatValue(measure, value) {
1215
- return measure === StartupSizeMeasure.StartFiles ? `${value} file${value === 1 ? "" : "s"}` : StartupSizeCheck.formatBytes(value);
1216
- }
1217
- static isFile(path) {
1218
- return existsSync(path) && statSync(path).isFile();
1403
+ let document;
1404
+ try {
1405
+ document = JSON.parse(content);
1406
+ } catch {
1407
+ document = void 0;
1408
+ }
1409
+ return {
1410
+ content,
1411
+ document,
1412
+ records: StartupBaselineFile.parseRecords(document)
1413
+ };
1219
1414
  }
1220
1415
  };
1221
1416
  //#endregion
1222
- //#region src/startup-entries-report.ts
1417
+ //#region src/startup-built-code.ts
1223
1418
  /**
1224
- * The entries report of `heximon check --startup --entries`: for each app, the entries grouped by the packages
1225
- * that their first use loads, and the built code that each group adds after the start. It walks the code with
1226
- * the size walk of the check ({@link StartupSizeCheck}), and finds the code of each package from the build
1227
- * record. It is a report: it fails nothing and writes nothing.
1419
+ * The built server code of one entry, as the size walk read it, with the packages of each file. It finds the
1420
+ * files that hold the code of a package, and the files that some files load when they run.
1421
+ *
1422
+ * The code of a package starts at the chunk of its generated loader, when the start report names the loader and
1423
+ * the build record names the chunk. So two roots of one npm package each get their own files. Otherwise a file
1424
+ * holds the code of a package when the build record gives the package bytes in the file, or when the file is in
1425
+ * the `node_modules` directory of the package in the output, without the files that only the other roots of the
1426
+ * package reach. From these files, the code of a package is every file that they import, with a static import or
1427
+ * with `import()`, up to the loader chunk of another package.
1228
1428
  */
1229
- var StartupEntriesReport = class StartupEntriesReport {
1230
- /** How many modules each group names. */
1231
- static namedModuleCount = 5;
1232
- /** How many modules of the heavy entries the summary names. */
1233
- static namedHeavyModuleCount = 5;
1234
- /** How many packages of a list a line names before it stops. */
1235
- static namedPackageCount = 8;
1236
- /** How many contributors of an async registry a line names before it stops. */
1237
- static namedContributorCount = 5;
1238
- /**
1239
- * The report of the start reports of a compile.
1240
- *
1241
- * @param reports - The start report of each app.
1242
- * @param measuring - The measurement of the build output by the size check.
1243
- * @param top - The number of module sets and async registries to show for each app. All when absent.
1244
- */
1245
- static report(reports, measuring, top) {
1246
- const measured = measuring.kind === "measured" ? measuring : void 0;
1247
- const serverEntry = measured?.entries.find((entry) => entry.name === ServerBuildRecord.mainEntryName) ?? measured?.entries[0];
1248
- const chunks = serverEntry === void 0 ? void 0 : measured?.chunks;
1249
- const bytesUnavailable = measuring.kind === "skipped" ? measuring.result.reason : chunks === void 0 ? "no-chunk-record" : void 0;
1250
- const apps = reports.map((report) => StartupEntriesReport.appReport(report, serverEntry === void 0 || chunks === void 0 ? void 0 : new StartupBuiltCode(serverEntry, chunks, measured?.generated, report.loads?.loaders), top));
1251
- const notice = measuring.kind === "skipped" ? `${measuring.message.replace(" The size check of the server code is skipped.", "")} The entries report has no bytes.` : chunks === void 0 ? `The build record ${ServerBuildRecord.relativePath} does not have the packages of its chunks, so the entries report has no bytes. Build the app again with this version of Heximon.` : void 0;
1252
- return {
1253
- result: {
1254
- ...serverEntry === void 0 ? {} : { serverEntry: serverEntry.measurement.entry },
1255
- ...bytesUnavailable === void 0 ? {} : { bytesUnavailable },
1256
- apps
1257
- },
1258
- lines: [...notice === void 0 ? [] : [notice], ...apps.map((app) => StartupEntriesReport.appText(app, serverEntry?.measurement.entry))]
1259
- };
1260
- }
1261
- /** The report of one app. */
1262
- static appReport(report, code, top) {
1263
- const reasonsByPlace = new Map((report.loads?.entries ?? []).map((entry) => [StartupEntriesReport.placeOf(entry.kind, entry.key), new Map(entry.packages.map((loaded) => [loaded.package, loaded.reasons]))]));
1264
- const groupsByKey = /* @__PURE__ */ new Map();
1265
- for (const entry of report.entries) {
1266
- const key = entry.packages.join("\n");
1267
- const group = groupsByKey.get(key) ?? {
1268
- packages: entry.packages,
1269
- places: []
1270
- };
1271
- group.places.push(StartupEntriesReport.placeOf(entry.kind, entry.key));
1272
- groupsByKey.set(key, group);
1429
+ var StartupBuiltCode = class StartupBuiltCode {
1430
+ measured;
1431
+ chunks;
1432
+ /** The directory of the installed packages in a path of the output. */
1433
+ static packageDirectory = "node_modules/";
1434
+ /** The bytes of each file that the walk reached, by path in the output directory. */
1435
+ bytesByFile;
1436
+ /** The files that hold the code of each package, by package name. */
1437
+ filesByPackage;
1438
+ /** The chunks that hold the loader of each package with a known loader, by package identity. */
1439
+ loaderChunks;
1440
+ /** The files that the first load of each package with a known loader reaches, by package identity. */
1441
+ loaderClosures = /* @__PURE__ */ new Map();
1442
+ /** The static start closure of the walk. */
1443
+ staticStart;
1444
+ /**
1445
+ * @param measured - The measurement of the entry, with the imports of each file.
1446
+ * @param chunks - The packages of each chunk of the build, from the build record.
1447
+ * @param generated - The generated wiring files of each chunk of the build, from the build record.
1448
+ * @param loaders - The generated loader file of each package, by identity, from the start report.
1449
+ */
1450
+ constructor(measured, chunks, generated = {}, loaders = {}) {
1451
+ this.measured = measured;
1452
+ this.chunks = chunks;
1453
+ const filesByPackage = /* @__PURE__ */ new Map();
1454
+ this.bytesByFile = new Map(measured.measurement.files.map((file) => [file.path, file.bytes]));
1455
+ for (const file of measured.measurement.files) {
1456
+ const names = new Set(Object.keys(this.packagesOfFile(file.path)));
1457
+ for (const name of names) filesByPackage.set(name, [...filesByPackage.get(name) ?? [], file.path]);
1273
1458
  }
1274
- const startLoaded = code?.startFiles(report.start.map((entry) => entry.package));
1275
- const asyncRegistries = report.loads?.asyncRegistries ?? [];
1276
- const sortedGroups = [...groupsByKey.values()].map((group) => StartupEntriesReport.groupReport(group, new StartupEntryReasons(report), reasonsByPlace.get(group.places[0]) ?? /* @__PURE__ */ new Map(), asyncRegistries, code, startLoaded)).sort((first, second) => (second.added?.bytes ?? 0) - (first.added?.bytes ?? 0) || second.entries.length - first.entries.length || StartupEntriesReport.compareText(first.example, second.example));
1277
- const registries = asyncRegistries.map((registry) => StartupEntriesReport.asyncRegistryReport(registry, code, startLoaded)).sort((first, second) => (second.added?.bytes ?? 0) - (first.added?.bytes ?? 0) || StartupEntriesReport.compareText(first.owner, second.owner) || StartupEntriesReport.compareText(first.registry, second.registry));
1278
- return {
1279
- app: report.app,
1280
- defersPackages: report.defersPackages,
1281
- entries: report.entries.length,
1282
- groupCount: sortedGroups.length,
1283
- ...code === void 0 || startLoaded === void 0 ? {} : {
1284
- start: code.sizeOf(startLoaded),
1285
- ...StartupEntriesReport.byPackageNameOf(code, report.start.map((entry) => entry.package), "startByPackageName"),
1286
- byPackageNameOnly: !code.hasLoaders()
1287
- },
1288
- groups: top === void 0 ? sortedGroups : sortedGroups.slice(0, top),
1289
- summary: StartupEntriesReport.summaryOf(report, sortedGroups, code, startLoaded),
1290
- asyncRegistryCount: registries.length,
1291
- asyncRegistries: top === void 0 ? registries : registries.slice(0, top)
1292
- };
1459
+ this.filesByPackage = filesByPackage;
1460
+ this.loaderChunks = this.loaderChunksOf(generated, loaders);
1461
+ this.staticStart = this.reach(this.staticStartFiles(), /* @__PURE__ */ new Set(), void 0);
1293
1462
  }
1294
- /** The report of one group of entries. */
1295
- static groupReport(group, reasonNames, reasons, asyncRegistries, code, startLoaded) {
1296
- const places = [...group.places].sort((first, second) => StartupEntriesReport.compareText(first, second));
1297
- const addedFiles = code === void 0 || startLoaded === void 0 ? void 0 : code.codeOf(group.packages, startLoaded);
1298
- const bytesByPackage = code === void 0 || addedFiles === void 0 ? /* @__PURE__ */ new Map() : code.packageBytes(addedFiles);
1299
- const identitiesByName = /* @__PURE__ */ new Map();
1300
- for (const identity of group.packages) {
1301
- const name = StartupBuiltCode.packageNameOf(identity);
1302
- identitiesByName.set(name, [...identitiesByName.get(name) ?? [], identity]);
1303
- }
1304
- const modules = [...bytesByPackage].filter(([, bytes]) => bytes > 0).map(([name, bytes]) => {
1305
- const identities = identitiesByName.get(name);
1306
- if (identities === void 0) return {
1307
- module: name,
1308
- bytes,
1309
- reasons: [StartupEntryReasons.imported()]
1310
- };
1311
- const described = [...new Map(identities.flatMap((identity) => reasons.get(identity) ?? []).map((reason) => reasonNames.describe(reason)).map((named) => [named.text, named])).values()];
1312
- return {
1313
- module: identities.join(", "),
1314
- bytes,
1315
- reasons: described.length === 0 ? [StartupEntryReasons.notRecorded()] : described
1316
- };
1317
- }).sort((first, second) => second.bytes - first.bytes || StartupEntriesReport.compareText(first.module, second.module)).slice(0, StartupEntriesReport.namedModuleCount);
1318
- const sealPackages = /* @__PURE__ */ new Map();
1319
- for (const identity of group.packages) for (const reason of reasons.get(identity) ?? []) if (reason.kind === StartReasonKind.SealGroup && reason.source !== void 0) sealPackages.set(reason.source, [...sealPackages.get(reason.source) ?? [], identity]);
1320
- const sealGroups = [...sealPackages].sort(([first], [second]) => StartupEntriesReport.compareText(first, second)).map(([registry, packages]) => ({
1321
- registry,
1322
- packages,
1323
- ...addedFiles === void 0 ? {} : { bytes: [...new Set(packages.map((identity) => StartupBuiltCode.packageNameOf(identity)))].reduce((sum, name) => sum + (bytesByPackage.get(name) ?? 0), 0) }
1324
- }));
1325
- const loadedWithEntry = startLoaded === void 0 || addedFiles === void 0 ? void 0 : /* @__PURE__ */ new Set([...startLoaded, ...addedFiles]);
1326
- return {
1327
- packages: group.packages,
1328
- entries: places,
1329
- example: places[0],
1330
- ...code === void 0 || addedFiles === void 0 ? {} : { added: code.sizeOf(addedFiles) },
1331
- modules,
1332
- sealGroups,
1333
- onRead: asyncRegistries.filter((registry) => group.packages.includes(registry.owner)).map((registry) => ({
1334
- registry: registry.registry,
1335
- owner: registry.owner,
1336
- ...code === void 0 || loadedWithEntry === void 0 ? {} : { added: code.sizeOf(code.codeOf(registry.packages.map((loaded) => loaded.package), loadedWithEntry)) }
1337
- })),
1338
- ...code === void 0 ? {} : StartupEntriesReport.byPackageNameOf(code, group.packages, "byPackageName")
1339
- };
1463
+ /**
1464
+ * The package name of a package identity: `@acme/orders/admin#OrdersModule` gives `@acme/orders`.
1465
+ *
1466
+ * @param identity - The identity, as `<specifier>#<module class>`.
1467
+ */
1468
+ static packageNameOf(identity) {
1469
+ const specifier = identity.slice(0, identity.lastIndexOf("#") === -1 ? void 0 : identity.lastIndexOf("#"));
1470
+ return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
1340
1471
  }
1341
- /** A field that names the packages whose files `code` finds by npm package name, or no field. */
1342
- static byPackageNameOf(code, identities, field) {
1343
- const byPackageName = code.byPackageName(identities);
1344
- return byPackageName.length === 0 ? {} : { [field]: byPackageName };
1472
+ /** The files that the entry loads when it runs: the static start closure of the walk. */
1473
+ staticStartFiles() {
1474
+ return this.measured.measurement.files.filter((file) => file.isStart).map((file) => file.path);
1345
1475
  }
1346
1476
  /**
1347
- * The report of one async registry: the code of its first `load()` call beyond the start and the code that
1348
- * loads with the owner.
1477
+ * The files that the first load of some packages reaches, without the files that are loaded already: from the
1478
+ * chunk of each loader, or the files of the npm package ({@link byPackageName}), every file that they import
1479
+ * with a static import or with `import()`. The walk does not go into the loader chunk of another package
1480
+ * through `import()`, as that chunk loads on the first use of that package.
1481
+ *
1482
+ * @param identities - The packages, by identity.
1483
+ * @param loaded - The files that are loaded already. The walk does not pass through them.
1349
1484
  */
1350
- static asyncRegistryReport(registry, code, startLoaded) {
1351
- const packages = registry.packages.map((loaded) => loaded.package);
1352
- let added;
1353
- if (code !== void 0 && startLoaded !== void 0) {
1354
- const loaded = /* @__PURE__ */ new Set([...startLoaded, ...code.codeOf([registry.owner, ...registry.ownerPackages], startLoaded)]);
1355
- added = code.sizeOf(code.codeOf(packages, loaded));
1356
- }
1357
- return {
1358
- registry: registry.registry,
1359
- owner: registry.owner,
1360
- inputKey: registry.inputKey,
1361
- contributors: registry.contributors,
1362
- packages,
1363
- ...added === void 0 ? {} : { added },
1364
- ...code === void 0 ? {} : StartupEntriesReport.byPackageNameOf(code, packages, "byPackageName")
1365
- };
1485
+ codeOf(identities, loaded = /* @__PURE__ */ new Set()) {
1486
+ return this.reach(this.seedsOf(identities), loaded, this.loaderChunksOutside(new Set(identities)));
1366
1487
  }
1367
- /** The summary of the entries of one app, over every group. */
1368
- static summaryOf(report, groups, code, startLoaded) {
1369
- const kinds = /* @__PURE__ */ new Map();
1370
- for (const entry of report.entries) kinds.set(entry.kind, [...kinds.get(entry.kind) ?? [], entry.packages]);
1371
- const everyEntry = [...kinds].filter(([, sets]) => sets.length > 1).sort(([first], [second]) => StartupEntriesReport.compareText(first, second)).flatMap(([kind, sets]) => {
1372
- const shared = sets[0].filter((identity) => sets.every((set) => set.includes(identity)));
1373
- return shared.length === 0 ? [] : [{
1374
- kind,
1375
- entries: sets.length,
1376
- packages: shared,
1377
- ...code === void 0 || startLoaded === void 0 ? {} : { added: code.sizeOf(code.codeOf(shared, startLoaded)) }
1378
- }];
1379
- });
1380
- if (code === void 0 || report.entries.length === 0) return { everyEntry };
1381
- const entryBytes = groups.flatMap((group) => group.entries.map(() => group.added?.bytes ?? 0)).sort((first, second) => first - second);
1382
- const p75 = StartupEntriesReport.percentile(entryBytes, .75);
1383
- const heavyGroups = groups.filter((group) => {
1384
- const bytes = group.added?.bytes ?? 0;
1385
- return bytes > 0 && bytes >= p75;
1386
- });
1387
- const heavyCounts = /* @__PURE__ */ new Map();
1388
- for (const group of heavyGroups) for (const identity of group.packages) heavyCounts.set(identity, (heavyCounts.get(identity) ?? 0) + group.entries.length);
1488
+ /**
1489
+ * The files that the app loads before it is ready: the static start closure, and the code of the start
1490
+ * packages ({@link codeOf}), also where it passes through the static start.
1491
+ *
1492
+ * @param identities - The start packages, by identity.
1493
+ */
1494
+ startFiles(identities) {
1495
+ return /* @__PURE__ */ new Set([...this.staticStart, ...this.codeOf(identities)]);
1496
+ }
1497
+ /** Whether the code finds the files of some package by its loader chunk. */
1498
+ hasLoaders() {
1499
+ return this.loaderChunks.size > 0;
1500
+ }
1501
+ /**
1502
+ * The packages whose files {@link codeOf} finds by npm package name, because the build record names no
1503
+ * chunk of a loader of theirs. Their bytes are less exact.
1504
+ *
1505
+ * @param identities - The packages, by identity.
1506
+ */
1507
+ byPackageName(identities) {
1508
+ return identities.filter((identity) => !this.loaderChunks.has(identity));
1509
+ }
1510
+ /**
1511
+ * How many files a set has, and their bytes.
1512
+ *
1513
+ * @param files - The files.
1514
+ */
1515
+ sizeOf(files) {
1516
+ let bytes = 0;
1517
+ for (const file of files) bytes += this.bytesByFile.get(file) ?? 0;
1389
1518
  return {
1390
- bytes: {
1391
- median: StartupEntriesReport.percentile(entryBytes, .5),
1392
- p75,
1393
- max: entryBytes.at(-1) ?? 0
1394
- },
1395
- everyEntry,
1396
- heavy: {
1397
- entries: heavyGroups.reduce((sum, group) => sum + group.entries.length, 0),
1398
- modules: [...heavyCounts].sort(([firstModule, firstCount], [secondModule, secondCount]) => secondCount - firstCount || StartupEntriesReport.compareText(firstModule, secondModule)).slice(0, StartupEntriesReport.namedHeavyModuleCount).map(([module, entries]) => ({
1399
- module,
1400
- entries
1401
- }))
1402
- }
1519
+ files: files.size,
1520
+ bytes
1403
1521
  };
1404
1522
  }
1405
- /** The text of the report of one app. */
1406
- static appText(app, serverEntry) {
1407
- if (app.entries === 0) return `App '${app.app}' has no entries: the first use of each entry loads no package beyond the start.` + StartupEntriesReport.asyncRegistriesText(app);
1408
- const lines = [`Entries of app '${app.app}': ${StartupEntriesReport.count(app.entries, "entry", "entries")} in ${StartupEntriesReport.count(app.groupCount, "module set", "module sets")}.` + (app.start === void 0 || serverEntry === void 0 ? "" : ` Each row gives the code that the first use of an entry loads after the start (${StartupEntriesReport.sizeText(app.start)}), in the build of ${serverEntry}.`)];
1409
- if (app.byPackageNameOnly === true) lines.push("The build record names no loader chunk of a package, so the report finds the code of each package by its npm package name. Two roots of one npm package then share their code.");
1410
- if (app.groups.length < app.groupCount) lines.push(`The ${app.groups.length} largest of the ${app.groupCount} module sets (--top):`);
1411
- for (const [index, group] of app.groups.entries()) {
1412
- lines.push(`${index + 1}. ${StartupEntriesReport.count(group.entries.length, "entry", "entries")}, for example '${group.example}'` + (group.added === void 0 ? "." : `: ${StartupEntriesReport.sizeText(group.added)}.`), ` Module set: ${group.packages.length === 0 ? "no package beyond the start" : StartupEntriesReport.listText(group.packages)}.`);
1413
- for (const module of group.modules) lines.push(` - ${module.module}: ${StartupSizeCheck.formatBytes(module.bytes)} (${module.reasons.map((reason) => reason.text).join("; ")})`);
1414
- for (const sealGroup of group.sealGroups) lines.push(` - The seal group of ${sealGroup.registry} loads ${StartupEntriesReport.count(sealGroup.packages.length, "package", "packages")}` + (sealGroup.bytes === void 0 ? "" : ` (${StartupSizeCheck.formatBytes(sealGroup.bytes)})`) + " with these entries. Extend AsyncContributions<T> for the registry, so that its contributors load on its first load() call.");
1415
- if (app.byPackageNameOnly !== true && group.byPackageName !== void 0) lines.push(` - Found by npm package name, as the build record names no loader chunk: ${StartupEntriesReport.listText(group.byPackageName)}.`);
1416
- for (const onRead of group.onRead) lines.push(` - On read: a load() call of '${onRead.registry}' of ${onRead.owner} can add ` + (onRead.added === void 0 ? "the code of its contributors." : `${StartupEntriesReport.sizeText(onRead.added)}. The row above does not count it.`));
1523
+ /**
1524
+ * About how many bytes of some files belong to each package. A chunk gives each of its packages a part of its
1525
+ * bytes, in the ratio of their rendered code. A file of a package's `node_modules` directory belongs to the
1526
+ * package. Other bytes, such as a runtime helper of the bundler, belong to no package.
1527
+ *
1528
+ * @param files - The files.
1529
+ * @returns The bytes of each package, by package name.
1530
+ */
1531
+ packageBytes(files) {
1532
+ const bytesByPackage = /* @__PURE__ */ new Map();
1533
+ for (const file of files) for (const [name, bytes] of Object.entries(this.packagesOfFile(file))) bytesByPackage.set(name, (bytesByPackage.get(name) ?? 0) + bytes);
1534
+ return bytesByPackage;
1535
+ }
1536
+ /**
1537
+ * Some files and every file that they import, without the files that are loaded already. With `boundary`, the
1538
+ * walk follows `import()` too, but not into a file of `boundary`.
1539
+ */
1540
+ reach(seeds, loaded, boundary) {
1541
+ const reached = /* @__PURE__ */ new Set();
1542
+ const pending = seeds.filter((file) => !loaded.has(file));
1543
+ for (let file = pending.pop(); file !== void 0; file = pending.pop()) {
1544
+ if (reached.has(file)) continue;
1545
+ reached.add(file);
1546
+ const targets = [...StartupBuiltCode.importsOf(this.measured.staticImports, file), ...boundary === void 0 ? [] : StartupBuiltCode.importsOf(this.measured.dynamicImports, file).filter((target) => !boundary.has(target))];
1547
+ for (const target of targets) if (!loaded.has(target) && !reached.has(target)) pending.push(target);
1417
1548
  }
1418
- const { summary } = app;
1419
- if (summary.bytes !== void 0) lines.push(`Per entry: median ${StartupSizeCheck.formatBytes(summary.bytes.median)}, p75 ${StartupSizeCheck.formatBytes(summary.bytes.p75)}, max ${StartupSizeCheck.formatBytes(summary.bytes.max)}.`);
1420
- for (const every of summary.everyEntry) lines.push(`Every '${every.kind}' entry (${every.entries}) loads ${StartupEntriesReport.count(every.packages.length, "package", "packages")}` + (every.added === void 0 ? "" : ` (${StartupSizeCheck.formatBytes(every.added.bytes)})`) + `: ${StartupEntriesReport.listText(every.packages)}.`);
1421
- if (summary.heavy !== void 0 && summary.heavy.modules.length > 0) lines.push(`The ${StartupEntriesReport.count(summary.heavy.entries, "heavy entry", "heavy entries")} (p75 or more) load these packages most: ${summary.heavy.modules.map((module) => `${module.module} (${module.entries})`).join(", ")}.`);
1422
- return lines.join("\n") + StartupEntriesReport.asyncRegistriesText(app);
1549
+ return reached;
1423
1550
  }
1424
- /** The lines of the async registries of one app, with a newline before them, or nothing. */
1425
- static asyncRegistriesText(app) {
1426
- if (app.asyncRegistryCount === 0) return "";
1427
- return `\n${[`Async registries: the first load() call of each one loads its contributors. No entry counts this code${app.asyncRegistries.length < app.asyncRegistryCount ? ` (the ${app.asyncRegistries.length} largest of ${app.asyncRegistryCount}, --top)` : ""}.`, ...app.asyncRegistries.map((registry) => `- '${registry.registry}' of ${registry.owner}: ${StartupEntriesReport.count(registry.contributors.length, "contributor", "contributors")} (${StartupEntriesReport.listText(registry.contributors, StartupEntriesReport.namedContributorCount)}), ${StartupEntriesReport.count(registry.packages.length, "package", "packages")} beyond the start` + (registry.added === void 0 ? "." : `, ${StartupEntriesReport.sizeText(registry.added)}.`))].join("\n")}`;
1551
+ /** The chunk of the loader of each package, or the files of its npm package. */
1552
+ seedsOf(identities) {
1553
+ return [...new Set(identities.flatMap((identity) => this.loaderChunks.get(identity) ?? this.packageNameFilesOf(identity)))];
1428
1554
  }
1429
- /** Files and bytes for a person to read. */
1430
- static sizeText(size) {
1431
- return `${StartupEntriesReport.count(size.files, "file", "files")}, ${StartupSizeCheck.formatBytes(size.bytes)}`;
1555
+ /** The loader chunks of the packages that are not in `identities`. */
1556
+ loaderChunksOutside(identities) {
1557
+ return new Set([...this.loaderChunks].filter(([identity]) => !identities.has(identity)).flatMap(([, chunks]) => chunks));
1432
1558
  }
1433
- /** A list of names, with the count of the rest when it is long. */
1434
- static listText(names, limit = StartupEntriesReport.namedPackageCount) {
1435
- const named = names.slice(0, limit).join(", ");
1436
- const rest = names.length - limit;
1437
- return rest > 0 ? `${named} and ${rest} more` : named;
1559
+ /**
1560
+ * The files of the npm package of a root, without the files that only the other roots of the package reach
1561
+ * beyond the static start: those load on the first use of the other roots. A file that the root reaches from
1562
+ * its own files stays, as the walk cannot show that only the other roots load it.
1563
+ */
1564
+ packageNameFilesOf(identity) {
1565
+ const name = StartupBuiltCode.packageNameOf(identity);
1566
+ const files = this.filesByPackage.get(name) ?? [];
1567
+ const others = [...this.loaderChunks].filter(([other]) => other !== identity && StartupBuiltCode.packageNameOf(other) === name);
1568
+ if (others.length === 0) return files;
1569
+ const otherFiles = new Set(others.flatMap(([other, chunks]) => {
1570
+ const closure = this.loaderClosures.get(other) ?? this.reach(chunks, this.staticStart, this.loaderChunksOutside(/* @__PURE__ */ new Set([other])));
1571
+ this.loaderClosures.set(other, closure);
1572
+ return [...closure];
1573
+ }));
1574
+ const ownFiles = this.reach(files.filter((file) => !otherFiles.has(file)), /* @__PURE__ */ new Set(), this.loaderChunksOutside(/* @__PURE__ */ new Set([identity])));
1575
+ return files.filter((file) => !otherFiles.has(file) || ownFiles.has(file));
1438
1576
  }
1439
- /** A count with the noun in the singular or the plural. */
1440
- static count(value, singular, plural) {
1441
- return `${value} ${value === 1 ? singular : plural}`;
1577
+ /** The targets of one file in an import table of the walk. */
1578
+ static importsOf(imports, file) {
1579
+ return Object.hasOwn(imports, file) ? imports[file] ?? [] : [];
1442
1580
  }
1443
- /** An entry as `<kind> <key>`, as `heximon.startup.json` names it. */
1444
- static placeOf(kind, key) {
1445
- return `${kind} ${key}`;
1581
+ /**
1582
+ * The chunks that hold the loader file of each package with a loader. A loader whose chunk the walk did not
1583
+ * reach, or is in the static start closure, or holds the loader of another package, gives no chunks.
1584
+ */
1585
+ loaderChunksOf(generated, loaders) {
1586
+ const loaderFiles = new Set(Object.values(loaders));
1587
+ const startFiles = new Set(this.staticStartFiles());
1588
+ const chunksByLoader = /* @__PURE__ */ new Map();
1589
+ for (const [chunk, files] of Object.entries(generated)) for (const file of files) if (loaderFiles.has(file)) chunksByLoader.set(file, [...chunksByLoader.get(file) ?? [], chunk]);
1590
+ const chunks = /* @__PURE__ */ new Map();
1591
+ for (const [identity, loader] of Object.entries(loaders)) {
1592
+ const holders = chunksByLoader.get(loader) ?? [];
1593
+ const isOwnChunk = holders.every((chunk) => this.bytesByFile.has(chunk) && !startFiles.has(chunk) && (Object.hasOwn(generated, chunk) ? generated[chunk] ?? [] : []).every((file) => file === loader || !loaderFiles.has(file)));
1594
+ if (holders.length > 0 && isOwnChunk) chunks.set(identity, holders);
1595
+ }
1596
+ return chunks;
1446
1597
  }
1447
- /** The value at a fraction of sorted values, by the nearest rank. */
1448
- static percentile(sorted, fraction) {
1449
- return sorted[Math.max(0, Math.ceil(fraction * sorted.length) - 1)] ?? 0;
1598
+ /** The bytes of one file that belong to each package, by package name. */
1599
+ packagesOfFile(file) {
1600
+ const fileBytes = this.bytesByFile.get(file) ?? 0;
1601
+ const rendered = Object.hasOwn(this.chunks, file) ? this.chunks[file] : void 0;
1602
+ if (rendered !== void 0) {
1603
+ const total = Object.values(rendered).reduce((sum, bytes) => sum + bytes, 0);
1604
+ return total === 0 ? {} : Object.fromEntries(Object.entries(rendered).map(([name, bytes]) => [name, Math.round(fileBytes * bytes / total)]));
1605
+ }
1606
+ const name = StartupBuiltCode.installedPackageOf(file);
1607
+ return name === void 0 ? {} : { [name]: fileBytes };
1450
1608
  }
1451
- static compareText(first, second) {
1452
- return first < second ? -1 : first > second ? 1 : 0;
1609
+ /** The package of a file in a `node_modules` directory of the output, or `undefined`. */
1610
+ static installedPackageOf(file) {
1611
+ const index = file.lastIndexOf(StartupBuiltCode.packageDirectory);
1612
+ if (index === -1 || index > 0 && file[index - 1] !== "/") return;
1613
+ const segments = file.slice(index + StartupBuiltCode.packageDirectory.length).split("/");
1614
+ const length = segments[0]?.startsWith("@") === true ? 2 : 1;
1615
+ return segments.length > length ? segments.slice(0, length).join("/") : void 0;
1453
1616
  }
1454
1617
  };
1455
1618
  //#endregion
1456
- //#region src/project-modules.ts
1619
+ //#region src/startup-entry-reasons.ts
1457
1620
  /**
1458
- * Imports packages the way the generated wiring imports them: through a small module written into the
1459
- * compile output directory, which sits in the project. The specifiers inside it resolve from the project, so
1460
- * the command gets the copy of a package that the wiring gets. A package the command imported from its own
1461
- * install would be a second set of class objects, and `app.from(CoreModule)` would not know them.
1621
+ * The reasons of the entries report, named by the kind that the compile records. A reason that the compile
1622
+ * does not record is "reason not recorded": the report does not guess a kind for it.
1462
1623
  */
1463
- var ProjectModules = class ProjectModules {
1464
- /**
1465
- * Import `specifiers` of the project.
1466
- *
1467
- * @param directory - A directory inside the project, with write access (the compile output directory).
1468
- * @param fileName - The name of the module to write, unique among the calls for one directory.
1469
- * @param source - The module source: `export … from "<specifier>"` lines.
1470
- * @returns The namespace of the written module.
1471
- */
1472
- static async import(directory, fileName, source) {
1473
- const file = join(directory, fileName);
1474
- writeFileSync(file, source);
1475
- return await import(pathToFileURL(file).href);
1624
+ var StartupEntryReasons = class StartupEntryReasons {
1625
+ /** The kind of code that a loaded file imports, and that is not a composed package. */
1626
+ static importKind = "import";
1627
+ /** The kind of a module whose reason the compile does not record. */
1628
+ static notRecordedKind = "not-recorded";
1629
+ /** The entries of the report, as `<kind> <key>`. */
1630
+ places;
1631
+ /** The identities of the composed packages of the report. */
1632
+ packages;
1633
+ /** @param report - The start report of the app. */
1634
+ constructor(report) {
1635
+ this.places = new Set(report.entries.map((entry) => `${entry.kind} ${entry.key}`));
1636
+ this.packages = /* @__PURE__ */ new Set([
1637
+ ...report.start.map((entry) => entry.package),
1638
+ ...report.entries.flatMap((entry) => entry.packages),
1639
+ ...(report.loads?.asyncRegistries ?? []).flatMap((registry) => [registry.owner, ...registry.packages.map((entry) => entry.package)])
1640
+ ]);
1476
1641
  }
1477
- /** The runtime of the project: everything the command asks of `@heximon/runtime`. */
1478
- static runtime(directory) {
1479
- return ProjectModules.import(directory, "project-runtime.js", "export * from \"@heximon/runtime\";\n");
1642
+ /** The reason of code that a loaded file imports, and that is not a composed package. */
1643
+ static imported() {
1644
+ return {
1645
+ kind: StartupEntryReasons.importKind,
1646
+ text: "import of a loaded file, not a composed package"
1647
+ };
1480
1648
  }
1481
- };
1482
- //#endregion
1483
- //#region src/nitro-host.ts
1484
- /**
1485
- * The production inputs of a Nitro host project, for the preset that was read from its config files. The
1486
- * preset picks the deploy platform, and the compile adds the Nitro host plugin, so a compile that reads the
1487
- * sidecar alone would build another graph. `@heximon/nitro` of the project makes the inputs from the preset
1488
- * name. Both packages load from the project, so the plugins, the strategy and the compiler are one copy. No
1489
- * Nitro or Vite config runs.
1490
- */
1491
- var NitroHost = class NitroHost {
1492
- context;
1493
- aliases;
1494
- constructor(context, aliases) {
1495
- this.context = context;
1496
- this.aliases = aliases;
1649
+ /** The reason of a module whose reason the compile does not record. */
1650
+ static notRecorded() {
1651
+ return {
1652
+ kind: StartupEntryReasons.notRecordedKind,
1653
+ text: "reason not recorded"
1654
+ };
1497
1655
  }
1498
1656
  /**
1499
- * Resolve the inputs of the Nitro host.
1657
+ * One reason of the start report, with its text.
1500
1658
  *
1501
- * @param rootDir - The project root.
1502
- * @param directory - A directory inside the project to write the import module into.
1503
- * @param request - The preset (or the choice to take the platform from the sidecar), the literal source
1504
- * directories of the Nitro config, and the module aliases of the project (the tsconfig `paths`).
1505
- * @throws {Error} When `@heximon/nitro` is not installed in the project.
1659
+ * @param reason - The reason, as the compile records it.
1506
1660
  */
1507
- static async open(rootDir, directory, request) {
1508
- const modules = await ProjectModules.import(directory, "project-nitro.js", "export { resolveNitroPresetInputs } from \"@heximon/nitro/module\";\n");
1509
- return new NitroHost(await modules.resolveNitroPresetInputs({
1510
- rootDirectory: rootDir,
1511
- preset: request.preset,
1512
- aliases: request.aliases.prefixes,
1513
- ...request.serverDir === void 0 ? {} : { serverDir: request.serverDir },
1514
- ...request.scanDirs === void 0 ? {} : { scanDirs: request.scanDirs },
1515
- ...request.platformFromSidecar === true ? { platformFromSidecar: true } : {}
1516
- }), request.aliases);
1661
+ describe(reason) {
1662
+ return {
1663
+ kind: reason.kind,
1664
+ ...reason.source === void 0 ? {} : { source: reason.source },
1665
+ ...reason.tokens === void 0 ? {} : { tokens: reason.tokens },
1666
+ text: this.textOf(reason)
1667
+ };
1517
1668
  }
1518
- /** Whether the sidecar declares the deploy platform. */
1519
- hasSidecarPlatform() {
1520
- return this.context.config?.platform !== void 0;
1669
+ /** The text of one reason. */
1670
+ textOf(reason) {
1671
+ const { source } = reason;
1672
+ switch (reason.kind) {
1673
+ case StartReasonKind.Dependency: return this.dependencyText(reason);
1674
+ case StartReasonKind.SealGroup: return `seal group of the sync registry ${source ?? "(registry not recorded)"}`;
1675
+ case StartReasonKind.ContributesTo: return `contributor to the registry ${source ?? "(registry not recorded)"}`;
1676
+ case StartReasonKind.ContributionCannotWait: return `contribution section that cannot wait${source === void 0 ? "" : `: ${source}`}`;
1677
+ case StartReasonKind.RegistrarOptions: return `registrar options of the plugin ${source ?? "(plugin not recorded)"}`;
1678
+ case StartReasonKind.PluginNeedsAtStart: return `a compiler plugin needs it at the start${source === void 0 ? "" : `: ${source}`}`;
1679
+ case StartReasonKind.LazyRead: return `Lazy<T> read${source === void 0 ? "" : `: ${source}`}`;
1680
+ case StartReasonKind.EagerProvider: return `eager provider${source === void 0 ? "" : ` ${source}`}`;
1681
+ case StartReasonKind.BootHook: return "boot hook";
1682
+ case StartReasonKind.ConfigSection: return "config section";
1683
+ case StartReasonKind.DispatchInventory: return "DispatchInventory read";
1684
+ case StartReasonKind.NotDeferred: return "the target does not defer packages";
1685
+ default: return source === void 0 ? String(reason.kind) : `${String(reason.kind)}: ${source}`;
1686
+ }
1521
1687
  }
1522
- /** The production compile inputs of the host: the strategy, the plugins, the sidecar, the source directories. */
1523
- inputs() {
1524
- return this.context;
1688
+ /** The text of a dependency: on the first use of an entry, or a wait of a package with its DI tokens. */
1689
+ dependencyText(reason) {
1690
+ const { source, tokens } = reason;
1691
+ if (source === void 0) return "dependency (source not recorded)";
1692
+ if (this.places.has(source)) return `first use of the entry '${source}'`;
1693
+ if (!this.packages.has(source)) return `dependency of ${source}`;
1694
+ return tokens === void 0 || tokens.length === 0 ? `dependency of ${source} (token not recorded)` : `DI dependency of ${source}, ${tokens.length === 1 ? "token" : "tokens"} ${tokens.join(", ")}`;
1525
1695
  }
1696
+ };
1697
+ //#endregion
1698
+ //#region src/startup-size-check.ts
1699
+ /**
1700
+ * The size half of `heximon check --startup`: it measures the built server code from the entry that the last
1701
+ * build recorded ({@link ServerBuildRecord}), and compares the measures with the `size` section of
1702
+ * `heximon.startup.json`. Without build output, the check skips it.
1703
+ */
1704
+ var StartupSizeCheck = class StartupSizeCheck {
1705
+ /** The command that writes the file. */
1706
+ static updateCommand = "heximon check --startup --update";
1707
+ /** How many requests that the walk could not follow a note names. */
1708
+ static namedGapCount = 5;
1526
1709
  /**
1527
- * Run the compile the host's production build runs.
1710
+ * Measure the server code of the last build.
1528
1711
  *
1529
- * @param rootDir - The project root.
1530
- * @param outputDirectory - Where the generated files will be written.
1531
- * @param sourceDirectories - The source directories to scan instead of the host's, when the caller has some.
1712
+ * @param rootDir - The app root.
1713
+ * @returns The measurement, or why there is none.
1532
1714
  */
1533
- compile(rootDir, outputDirectory, sourceDirectories) {
1534
- const context = this.context;
1535
- const config = context.config;
1536
- const compiler = new ProjectCompiler();
1715
+ static measure(rootDir) {
1716
+ const reading = ServerBuildRecord.read(rootDir);
1717
+ const skip = (reason, message) => ({
1718
+ kind: "skipped",
1719
+ result: {
1720
+ action: "skipped",
1721
+ reason,
1722
+ record: reading.file
1723
+ },
1724
+ message: `${message} The size check of the server code is skipped.`
1725
+ });
1726
+ if (reading.kind === "absent") return skip("no-build-output", `There is no build output: the build writes ${ServerBuildRecord.relativePath}, and the file is absent. Build the app before the check to check the size of its server code.`);
1727
+ if (reading.kind === "unreadable") return skip("record-unreadable", `${reading.message} Build the app again.`);
1728
+ const names = Object.keys(reading.entries).sort();
1729
+ const missing = names.map((name) => reading.entries[name].path).find((path) => !StartupSizeCheck.isFile(path) || !existsSync(reading.outputDirectory));
1730
+ if (missing !== void 0) return skip("entry-missing", `The build record names the server entry ${relative(rootDir, missing)}, and the file does not exist. Build the app again.`);
1731
+ const entries = names.map((name) => {
1732
+ const entry = reading.entries[name];
1733
+ const graph = ServerCodeWalk.graph(rootDir, reading.outputDirectory, entry.path, entry.target);
1734
+ return {
1735
+ name,
1736
+ measurement: graph.measurement,
1737
+ staticImports: graph.staticImports,
1738
+ dynamicImports: graph.dynamicImports
1739
+ };
1740
+ });
1537
1741
  return {
1538
- output: compiler.compile({
1539
- rootDir,
1540
- outputDirectory,
1541
- sourceDirectories: sourceDirectories ?? context.sourceDirectories,
1542
- aliases: this.aliases.prefixes,
1543
- exactAliases: this.aliases.exact,
1544
- plugins: context.plugins,
1545
- strategy: context.strategy,
1546
- ...context.wiringMode === void 0 ? {} : { wiringMode: context.wiringMode },
1547
- ...config === void 0 ? {} : { config },
1548
- ...context.runtimeConfig === void 0 ? {} : { runtimeConfig: context.runtimeConfig },
1549
- ...config?.root === void 0 ? {} : { apps: { main: config.root } },
1550
- ...context.workspaceSubscribers === void 0 ? {} : { workspaceSubscribers: context.workspaceSubscribers }
1551
- }),
1552
- compiler,
1553
- platformName: context.strategy.platformName
1742
+ kind: "measured",
1743
+ entries,
1744
+ section: Object.fromEntries(entries.map(({ name, measurement }) => [name, StartupSizeBudget.recordOf(measurement)])),
1745
+ ...reading.chunks === void 0 ? {} : { chunks: reading.chunks },
1746
+ ...reading.generated === void 0 ? {} : { generated: reading.generated }
1554
1747
  };
1555
1748
  }
1556
- };
1557
- //#endregion
1558
- //#region src/nitro-static-config.ts
1559
- /**
1560
- * Reads the Nitro options that choose the graph of a build (`preset`, `serverDir`, `scanDirs`) from the source of
1561
- * the config files, without running them. A config file is project code: it can read the environment, call a
1562
- * service, or write a file. So the files are parsed with oxc, and the reader ACCEPTS only a shape that it can
1563
- * prove. Everything else is "computed", and the command then refuses or asks for an explicit input.
1564
- *
1565
- * Accepted in `nitro.config.*`: `export default {…}`, or `export default defineNitroConfig({…})` with
1566
- * `defineNitroConfig` imported from `nitro` or `nitro/config`, or either one through ONE top-level `const` that is
1567
- * never assigned again. The object has no spread. A `$production` or `$env.production` overlay applies; the other
1568
- * environments do not, because the command always compiles for production.
1569
- *
1570
- * Accepted in `vite.config.*`: ONE call of the Nitro plugin of `nitro/vite` (a named or a namespace import), as a
1571
- * direct element of the `plugins` array literal of the exported config (`export default {…}`, or `defineConfig`
1572
- * from `vite` over one, or either through one `const`). No ternary, no `&&`, no spread, no helper, no function.
1573
- *
1574
- * The precedence is Nitro's own: the options of the Vite config, then `NITRO_PRESET` / `SERVER_PRESET`, then the
1575
- * Nitro config file.
1576
- */
1577
- var NitroStaticConfig = class NitroStaticConfig {
1578
- static nitroConfigNames = [
1579
- "nitro.config.ts",
1580
- "nitro.config.mts",
1581
- "nitro.config.js",
1582
- "nitro.config.mjs"
1583
- ];
1584
- static viteConfigNames = [
1585
- "vite.config.ts",
1586
- "vite.config.mts",
1587
- "vite.config.js",
1588
- "vite.config.mjs"
1589
- ];
1590
- /** Nuxt creates its own Nitro, which a static read of these files cannot describe. */
1591
- static nuxtConfigNames = [
1592
- "nuxt.config.ts",
1593
- "nuxt.config.mts",
1594
- "nuxt.config.js",
1595
- "nuxt.config.mjs"
1596
- ];
1597
- /** The package names a Nuxt app depends on: the release, or the nightly. */
1598
- static nuxtPackages = ["nuxt", "nuxt-nightly"];
1599
- /** The extensions c12 tries for a config file, scripts and data formats. */
1600
- static configExtensions = [
1601
- ".js",
1602
- ".ts",
1603
- ".mjs",
1604
- ".cjs",
1605
- ".mts",
1606
- ".cts",
1607
- ".json",
1608
- ".jsonc",
1609
- ".json5",
1610
- ".yaml",
1611
- ".yml",
1612
- ".toml"
1613
- ];
1614
- /** The exact name of the rc file c12 reads for Nitro. */
1615
- static resourceFileName = ".nitrorc";
1616
- /** The expression nodes that only wrap another expression. */
1617
- static wrapperTypes = [
1618
- "TSAsExpression",
1619
- "TSSatisfiesExpression",
1620
- "TSNonNullExpression",
1621
- "TSTypeAssertion",
1622
- "ParenthesizedExpression"
1623
- ];
1624
- /** The module that exports the Nitro Vite plugin. */
1625
- static nitroVitePackage = "nitro/vite";
1626
- /** The key of the Nitro config that holds the options of the Heximon compile. */
1627
- static heximonSection = "heximon";
1628
- /** The helper that returns its Nitro config unchanged, and where it is imported from. */
1629
- static nitroConfigHelper = {
1630
- name: "defineNitroConfig",
1631
- packages: ["nitro", "nitro/config"]
1632
- };
1633
- /** The helper that returns its Vite config unchanged, and where it is imported from. */
1634
- static viteConfigHelper = {
1635
- name: "defineConfig",
1636
- packages: ["vite", "vite-plus"]
1637
- };
1638
1749
  /**
1639
- * @param rootDir - The project root.
1640
- * @param environment - The environment to read `NITRO_PRESET` from; the process environment by default.
1750
+ * Compare a measurement with the committed file.
1751
+ *
1752
+ * @param committed - The committed file, parsed, or `undefined` when there is no usable file. The startup
1753
+ * check reports that case, so the size check adds no error.
1754
+ * @param measured - The measurement.
1641
1755
  */
1642
- static read(rootDir, environment = process.env) {
1643
- const find = (names) => names.map((name) => join(rootDir, name)).find((path) => existsSync(path));
1644
- const notAHost = {
1645
- isNitroHost: false,
1646
- preset: { kind: "none" },
1647
- serverDir: { kind: "none" },
1648
- scanDirs: { kind: "none" },
1649
- sourceDirectories: { kind: "none" }
1756
+ static compare(committed, measured) {
1757
+ const file = StartupBaselineFile.fileName;
1758
+ const notes = StartupSizeCheck.measurementLines(measured);
1759
+ const cliCodes = /* @__PURE__ */ new Map();
1760
+ if (committed === void 0) return {
1761
+ result: {
1762
+ action: "compare",
1763
+ entries: StartupSizeCheck.entriesOf(measured, void 0),
1764
+ committed: false,
1765
+ reason: "no-baseline"
1766
+ },
1767
+ diagnostics: [],
1768
+ cliCodes,
1769
+ notes
1650
1770
  };
1651
- if (NitroStaticConfig.isNuxtProject(rootDir)) return notAHost;
1652
- const configFiles = NitroStaticConfig.configFilesOf(rootDir);
1653
- const nitroFile = configFiles.length === 1 && NitroStaticConfig.nitroConfigNames.some((name) => join(rootDir, name) === configFiles[0]) ? configFiles[0] : void 0;
1654
- const viteFile = find(NitroStaticConfig.viteConfigNames);
1655
- const vite = viteFile === void 0 ? void 0 : NitroStaticConfig.readVite(viteFile);
1656
- const hasNitroSource = configFiles.length > 0 || vite?.usesNitroPlugin === true;
1657
- if (!hasNitroSource && !NitroStaticConfig.dependsOnNitro(rootDir)) return notAHost;
1658
- const viteSources = vite?.sources ?? [];
1659
- const fileSources = nitroFile === void 0 ? [] : NitroStaticConfig.readNitroConfig(nitroFile);
1660
- const hiddenSources = NitroStaticConfig.hiddenSources(rootDir, hasNitroSource, nitroFile === void 0 ? configFiles : []);
1661
- const all = [
1662
- ...viteSources,
1663
- ...fileSources,
1664
- ...hiddenSources
1665
- ];
1666
- const fromVite = NitroStaticConfig.scalar("preset", viteSources, true);
1667
- const fromEnvironment = environment["NITRO_PRESET"] || environment["SERVER_PRESET"];
1668
- const found = fromVite.kind !== "none" ? fromVite : fromEnvironment ? {
1669
- kind: "literal",
1670
- value: fromEnvironment
1671
- } : NitroStaticConfig.scalar("preset", [...fileSources, ...hiddenSources], true);
1672
- const unreadable = all.find((source) => source.kind === "unproven");
1771
+ const baseline = StartupSizeBudget.parse(committed);
1772
+ if (baseline === null || baseline === void 0) {
1773
+ const diagnostic = {
1774
+ severity: DiagnosticSeverity.Error,
1775
+ message: baseline === null ? `${file} has no size section, and the build output exists (${measured.entries.map(({ measurement }) => measurement.entry).join(", ")}), so the size check has nothing to compare with.` : `The size section of ${file} has another shape, so the size check cannot read it.`,
1776
+ hint: `Run \`${StartupSizeCheck.updateCommand}\` after the build and commit the file.`
1777
+ };
1778
+ cliCodes.set(diagnostic, baseline === null ? CheckDiagnosticCode.StartupSizeUnrecorded : CheckDiagnosticCode.StartupBaselineUnreadable);
1779
+ return {
1780
+ result: {
1781
+ action: "compare",
1782
+ entries: StartupSizeCheck.entriesOf(measured, void 0),
1783
+ committed: false,
1784
+ reason: baseline === null ? "unrecorded" : "unreadable"
1785
+ },
1786
+ diagnostics: [diagnostic],
1787
+ cliCodes,
1788
+ notes
1789
+ };
1790
+ }
1791
+ const comparison = StartupSizeBudget.compare(baseline, measured.section);
1792
+ const diagnostics = comparison.growth.map((change) => {
1793
+ const isAdded = change.kind === StartupSizeChangeKind.EntryAdded;
1794
+ const diagnostic = {
1795
+ severity: DiagnosticSeverity.Error,
1796
+ message: isAdded ? `The build has the server entry '${change.name}' (${String(change.current)}), and the size section of ${file} does not record it, so the size check has nothing to compare it with.` : StartupSizeCheck.growthMessage(change, measured.section[change.name]?.entry ?? change.name),
1797
+ hint: isAdded ? `Run \`${StartupSizeCheck.updateCommand}\` after the build and commit the file.` : `Find what the new files bring into the server code (a static import that can be an \`import()\`, or a new package), or accept the growth: run \`${StartupSizeCheck.updateCommand}\` after the build and commit the file.`
1798
+ };
1799
+ cliCodes.set(diagnostic, isAdded ? CheckDiagnosticCode.StartupSizeUnrecorded : CheckDiagnosticCode.StartupSizeGrowth);
1800
+ return diagnostic;
1801
+ });
1673
1802
  return {
1674
- isNitroHost: true,
1675
- preset: unreadable !== void 0 && found.kind !== "computed" ? {
1676
- kind: "computed",
1677
- file: unreadable.file,
1678
- reason: unreadable.reason
1679
- } : NitroStaticConfig.withHidden(found, all, ["static", "extends"], ["defaultPreset"]),
1680
- serverDir: NitroStaticConfig.withHidden(NitroStaticConfig.scalar("serverDir", all), all, [], ["extends"]),
1681
- scanDirs: NitroStaticConfig.withHiddenList(NitroStaticConfig.list("scanDirs", all), all),
1682
- sourceDirectories: NitroStaticConfig.withHiddenList(NitroStaticConfig.list("sourceDirectories", NitroStaticConfig.sectionSources(NitroStaticConfig.heximonSection, all)), all)
1803
+ result: {
1804
+ action: "compare",
1805
+ entries: StartupSizeCheck.entriesOf(measured, baseline),
1806
+ committed: true,
1807
+ growth: comparison.growth,
1808
+ notes: comparison.notes
1809
+ },
1810
+ diagnostics,
1811
+ cliCodes,
1812
+ notes: [...notes, ...StartupSizeCheck.noteLines(comparison.notes, measured.section)]
1683
1813
  };
1684
1814
  }
1685
1815
  /**
1686
- * The literal source directories of a Nitro host, or the first of `serverDir`, `scanDirs` and
1687
- * `heximon.sourceDirectories` that is computed. The build scans the union of the three, so the
1688
- * `heximon.sourceDirectories` join `scanDirs`.
1816
+ * The outcome of `--startup --update` for a measurement.
1689
1817
  *
1690
- * @param result - What {@link read} returned.
1818
+ * @param measured - The measurement.
1819
+ * @param written - Whether the file was written or confirmed.
1691
1820
  */
1692
- static sourceOptionsOf(result) {
1693
- for (const [option, value] of [
1694
- ["serverDir", result.serverDir],
1695
- ["scanDirs", result.scanDirs],
1696
- ["heximon.sourceDirectories", result.sourceDirectories]
1697
- ]) if (value.kind === "computed") return {
1698
- kind: "computed",
1699
- option,
1700
- file: value.file,
1701
- reason: value.reason
1702
- };
1703
- const scanDirs = [...result.scanDirs.kind === "literal" ? result.scanDirs.value : [], ...result.sourceDirectories.kind === "literal" ? result.sourceDirectories.value : []];
1821
+ static updated(measured, written) {
1704
1822
  return {
1705
- kind: "literal",
1706
- ...result.serverDir.kind === "literal" ? { serverDir: result.serverDir.value } : {},
1707
- ...result.scanDirs.kind === "literal" || result.sourceDirectories.kind === "literal" ? { scanDirs } : {}
1823
+ result: {
1824
+ action: "update",
1825
+ entries: StartupSizeCheck.entriesOf(measured, void 0),
1826
+ written
1827
+ },
1828
+ notes: StartupSizeCheck.measurementLines(measured)
1708
1829
  };
1709
1830
  }
1710
1831
  /**
1711
- * Whether the project is a Nuxt app: it has a `nuxt.config.*` file, or package.json lists `nuxt` (or
1712
- * `nuxt-nightly`) as a dependency. Nuxt creates its own Nitro, so {@link read} does not report such a project
1713
- * as a Nitro host, although it deploys through Nitro.
1832
+ * A number of bytes for a person to read: bytes, KiB with one decimal, or MiB with two.
1714
1833
  *
1715
- * @param rootDir - The project root.
1834
+ * @param bytes - The number of bytes.
1716
1835
  */
1717
- static isNuxtProject(rootDir) {
1718
- const manifest = NitroStaticConfig.manifestOf(rootDir);
1719
- const dependencies = manifest === void 0 || manifest === "invalid" ? {} : {
1720
- ...manifest.dependencies,
1721
- ...manifest.devDependencies
1722
- };
1723
- return NitroStaticConfig.nuxtConfigNames.some((name) => existsSync(join(rootDir, name))) || NitroStaticConfig.nuxtPackages.some((name) => name in dependencies);
1836
+ static formatBytes(bytes) {
1837
+ if (bytes < 1024) return `${bytes} B`;
1838
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KiB`;
1839
+ return `${(bytes / 1048576).toFixed(2)} MiB`;
1724
1840
  }
1725
- /**
1726
- * Sources of options that the project has but the reader cannot read: a `.nitrorc` file (in the project or the
1727
- * home directory), the `nitro` key of `package.json`, and a dependency on `nitro` when no config file or
1728
- * provable plugin call exists.
1729
- */
1730
- static hiddenSources(rootDir, hasNitroSource, unreadFiles) {
1731
- const unproven = (reason) => ({
1732
- kind: "unproven",
1733
- file: join(rootDir, "package.json"),
1734
- reason
1841
+ /** The entries of a result, each with the measures that the committed section records for its name. */
1842
+ static entriesOf(measured, baseline) {
1843
+ return measured.entries.map(({ name, measurement }) => {
1844
+ const recorded = baseline !== void 0 && Object.hasOwn(baseline, name) ? baseline[name] : void 0;
1845
+ return {
1846
+ name,
1847
+ entry: measurement.entry,
1848
+ measured: {
1849
+ start: measurement.start,
1850
+ total: measurement.total
1851
+ },
1852
+ ...recorded === void 0 ? {} : { baseline: {
1853
+ start: recorded.start,
1854
+ total: recorded.total
1855
+ } },
1856
+ gaps: measurement.gaps,
1857
+ unparsed: measurement.unparsed
1858
+ };
1735
1859
  });
1736
- const sources = [];
1737
- const resourceFile = [rootDir, homedir()].map((directory) => join(directory, NitroStaticConfig.resourceFileName)).find((path) => existsSync(path));
1738
- if (resourceFile !== void 0) sources.push(unproven(`the file ${resourceFile} sets Nitro options`));
1739
- if (unreadFiles.length > 0) sources.push(unproven(`the file ${unreadFiles[0]} sets Nitro options in a form the command does not read`));
1740
- const manifest = NitroStaticConfig.manifestOf(rootDir);
1741
- if (manifest === "invalid") sources.push(unproven("package.json is not valid JSON"));
1742
- else if (manifest !== void 0) {
1743
- if (manifest.nitro !== void 0) sources.push(unproven("the `nitro` key of package.json sets Nitro options"));
1744
- if (!hasNitroSource && NitroStaticConfig.dependsOnNitro(rootDir)) sources.push(unproven("the project depends on nitro, but no Nitro config file or Nitro Vite plugin call was found"));
1860
+ }
1861
+ /** The summary and gap lines of each measured entry. */
1862
+ static measurementLines(measured) {
1863
+ return measured.entries.flatMap(({ measurement }) => [StartupSizeCheck.summaryLine(measurement), ...StartupSizeCheck.gapLines(measurement)]);
1864
+ }
1865
+ /** The line with the measures. */
1866
+ static summaryLine(measurement) {
1867
+ const size = (value) => `${value.files} file${value.files === 1 ? "" : "s"}, ${StartupSizeCheck.formatBytes(value.bytes)}`;
1868
+ return `Server code of ${measurement.entry}: the static start closure has ${size(measurement.start)}; the total server code has ${size(measurement.total)}.`;
1869
+ }
1870
+ /** The lines about requests that the walk could not follow, and files that do not parse. */
1871
+ static gapLines(measurement) {
1872
+ const lines = [];
1873
+ const gaps = measurement.gaps;
1874
+ if (gaps.length > 0) {
1875
+ const named = gaps.slice(0, StartupSizeCheck.namedGapCount).map((gap) => `${gap.importer} → ${gap.request}`).join("; ");
1876
+ lines.push(`The size walk could not follow ${gaps.length} request${gaps.length === 1 ? "" : "s"} (${named}${gaps.length > StartupSizeCheck.namedGapCount ? "; …" : ""}), so the measures can be too small.`);
1745
1877
  }
1746
- return sources;
1878
+ if (measurement.unparsed.length > 0) lines.push(`The size walk could not parse ${measurement.unparsed.join(", ")}, so the imports of ${measurement.unparsed.length === 1 ? "that file are" : "those files are"} not counted.`);
1879
+ return lines;
1747
1880
  }
1748
- /**
1749
- * Every file or directory that the config loader of Nitro (c12) would take as its main config: the name
1750
- * `nitro.config` in the project, in `.config/`, and `.config/nitro`, bare, with each supported extension, and as
1751
- * a directory with an `index` file. The project's own script forms are among them.
1752
- */
1753
- static configFilesOf(rootDir) {
1754
- return [
1755
- join(rootDir, "nitro.config"),
1756
- join(rootDir, ".config", "nitro.config"),
1757
- join(rootDir, ".config", "nitro")
1758
- ].flatMap((base) => ["", "/index"].flatMap((suffix) => ["", ...NitroStaticConfig.configExtensions].map((extension) => `${base}${suffix}${extension}`))).filter((path) => existsSync(path));
1881
+ /** The error text of one growth. */
1882
+ static growthMessage(change, entry) {
1883
+ const measure = change.measure ?? StartupSizeMeasure.StartBytes;
1884
+ const format = (value) => typeof value === "number" ? StartupSizeCheck.formatValue(measure, value) : String(value);
1885
+ const files = (change.files ?? []).map((file) => `${file.path} (${file.isNew ? `${StartupSizeCheck.formatBytes(file.bytes)}, new` : `+${StartupSizeCheck.formatBytes(file.growth)}`})`).join(", ");
1886
+ return `${StartupSizeCheck.measureName(measure)} of ${entry} is now ${format(change.current)}, and ${StartupBaselineFile.fileName} records ${format(change.committed)} with a slack of ${format(change.slack ?? 0)}.${files.length > 0 ? ` Largest new or grown files: ${files}.` : ""}`;
1759
1887
  }
1760
- /** The parsed package.json of the project, `undefined` when it has none, `"invalid"` when it is not JSON. */
1761
- static manifestOf(rootDir) {
1762
- const file = join(rootDir, "package.json");
1763
- if (!existsSync(file)) return;
1764
- try {
1765
- return JSON.parse(readFileSync(file, "utf8"));
1766
- } catch {
1767
- return "invalid";
1888
+ /** The note lines of the changes that do not fail. */
1889
+ static noteLines(notes, section) {
1890
+ const file = StartupBaselineFile.fileName;
1891
+ const lines = notes.map((change) => {
1892
+ if (change.kind === StartupSizeChangeKind.EntryChanged) return `The server entry '${change.name}' is now ${String(change.current)}, and ${file} records ${String(change.committed)}.`;
1893
+ if (change.kind === StartupSizeChangeKind.EntryRemoved) return `The build no longer has the server entry '${change.name}' (${String(change.committed)}) that ${file} records.`;
1894
+ const measure = change.measure ?? StartupSizeMeasure.StartBytes;
1895
+ return `${StartupSizeCheck.measureName(measure)} of ${section[change.name]?.entry ?? change.name} is now ${StartupSizeCheck.formatValue(measure, Number(change.current))}, less than the ${StartupSizeCheck.formatValue(measure, Number(change.committed))} that ${file} records.`;
1896
+ });
1897
+ if (lines.length === 0) return [];
1898
+ return [...lines, `Run \`${StartupSizeCheck.updateCommand}\` after the build to record the new size of the server code.`];
1899
+ }
1900
+ /** The name of a measure, at the start of a sentence. */
1901
+ static measureName(measure) {
1902
+ switch (measure) {
1903
+ case StartupSizeMeasure.StartFiles: return "The file count of the static start closure";
1904
+ case StartupSizeMeasure.TotalBytes: return "The total server code";
1905
+ default: return "The static start closure";
1768
1906
  }
1769
1907
  }
1770
- /** Whether package.json lists `nitro` as a dependency or a dev dependency. */
1771
- static dependsOnNitro(rootDir) {
1772
- const manifest = NitroStaticConfig.manifestOf(rootDir);
1773
- return manifest !== void 0 && manifest !== "invalid" && ("nitro" in (manifest.dependencies ?? {}) || "nitro" in (manifest.devDependencies ?? {}));
1908
+ /** A value of a measure for a person to read. */
1909
+ static formatValue(measure, value) {
1910
+ return measure === StartupSizeMeasure.StartFiles ? `${value} file${value === 1 ? "" : "s"}` : StartupSizeCheck.formatBytes(value);
1911
+ }
1912
+ static isFile(path) {
1913
+ return existsSync(path) && statSync(path).isFile();
1774
1914
  }
1915
+ };
1916
+ //#endregion
1917
+ //#region src/startup-entries-report.ts
1918
+ /**
1919
+ * The entries report of `heximon check --startup --entries`: for each app, the entries grouped by the packages
1920
+ * that their first use loads, and the built code that each group adds after the start. It walks the code with
1921
+ * the size walk of the check ({@link StartupSizeCheck}), and finds the code of each package from the build
1922
+ * record. It is a report: it fails nothing and writes nothing.
1923
+ */
1924
+ var StartupEntriesReport = class StartupEntriesReport {
1925
+ /** How many modules each group names. */
1926
+ static namedModuleCount = 5;
1927
+ /** How many modules of the heavy entries the summary names. */
1928
+ static namedHeavyModuleCount = 5;
1929
+ /** How many packages of a list a line names before it stops. */
1930
+ static namedPackageCount = 8;
1931
+ /** How many contributors of an async registry a line names before it stops. */
1932
+ static namedContributorCount = 5;
1775
1933
  /**
1776
- * Apply the keys that change a value without showing in it. A key in `always` (for the preset: `static`, which
1777
- * turns a preset into its static variant) makes the value unknown. A key in `whenUnset` (`defaultPreset`,
1778
- * `extends`: the layers sit below every other source) matters only when no literal was found.
1934
+ * The report of the start reports of a compile.
1935
+ *
1936
+ * @param reports - The start report of each app.
1937
+ * @param measuring - The measurement of the build output by the size check.
1938
+ * @param top - The number of module sets and async registries to show for each app. All when absent.
1779
1939
  */
1780
- static withHidden(value, sources, always, whenUnset) {
1781
- const hidden = (keys) => {
1782
- for (const source of sources) {
1783
- const key = source.kind === "object" ? keys.find((name) => source.entries.has(name)) : void 0;
1784
- if (source.kind === "object" && key !== void 0) return {
1785
- file: source.file,
1786
- key
1787
- };
1788
- }
1789
- };
1790
- const alwaysHidden = hidden(always);
1791
- const unsetHidden = value.kind === "none" ? hidden(whenUnset) : void 0;
1792
- const reason = alwaysHidden ?? unsetHidden;
1793
- return reason === void 0 ? value : {
1794
- kind: "computed",
1795
- file: reason.file,
1796
- reason: `\`${reason.key}\` can change the value`
1940
+ static report(reports, measuring, top) {
1941
+ const measured = measuring.kind === "measured" ? measuring : void 0;
1942
+ const serverEntry = measured?.entries.find((entry) => entry.name === ServerBuildRecord.mainEntryName) ?? measured?.entries[0];
1943
+ const chunks = serverEntry === void 0 ? void 0 : measured?.chunks;
1944
+ const bytesUnavailable = measuring.kind === "skipped" ? measuring.result.reason : chunks === void 0 ? "no-chunk-record" : void 0;
1945
+ const apps = reports.filter((report) => report.role !== StartReportRole.Hostless).map((report) => StartupEntriesReport.appReport(report, serverEntry === void 0 || chunks === void 0 ? void 0 : new StartupBuiltCode(serverEntry, chunks, measured?.generated, report.loads?.loaders), top));
1946
+ const notice = measuring.kind === "skipped" ? `${measuring.message.replace(" The size check of the server code is skipped.", "")} The entries report has no bytes.` : chunks === void 0 ? `The build record ${ServerBuildRecord.relativePath} does not have the packages of its chunks, so the entries report has no bytes. Build the app again with this version of Heximon.` : void 0;
1947
+ return {
1948
+ result: {
1949
+ ...serverEntry === void 0 ? {} : { serverEntry: serverEntry.measurement.entry },
1950
+ ...bytesUnavailable === void 0 ? {} : { bytesUnavailable },
1951
+ apps
1952
+ },
1953
+ lines: [...notice === void 0 ? [] : [notice], ...apps.map((app) => StartupEntriesReport.appText(app, serverEntry?.measurement.entry))]
1797
1954
  };
1798
1955
  }
1799
- /** A list gets every `extends` layer on top of it, so a layer makes it unknown. */
1800
- static withHiddenList(value, sources) {
1801
- const layered = sources.find((source) => source.kind === "object" && source.entries.has("extends"));
1802
- return layered === void 0 || layered.kind !== "object" ? value : {
1803
- kind: "computed",
1804
- file: layered.file,
1805
- reason: "`extends` can add values"
1956
+ /** The report of one app. */
1957
+ static appReport(report, code, top) {
1958
+ const reasonsByPlace = new Map((report.loads?.entries ?? []).map((entry) => [StartupEntriesReport.placeOf(entry.kind, entry.key), new Map(entry.packages.map((loaded) => [loaded.package, loaded.reasons]))]));
1959
+ const groupsByKey = /* @__PURE__ */ new Map();
1960
+ for (const entry of report.entries) {
1961
+ const key = entry.packages.join("\n");
1962
+ const group = groupsByKey.get(key) ?? {
1963
+ packages: entry.packages,
1964
+ places: []
1965
+ };
1966
+ group.places.push(StartupEntriesReport.placeOf(entry.kind, entry.key));
1967
+ groupsByKey.set(key, group);
1968
+ }
1969
+ const startLoaded = code?.startFiles(report.start.map((entry) => entry.package));
1970
+ const asyncRegistries = report.loads?.asyncRegistries ?? [];
1971
+ const sortedGroups = [...groupsByKey.values()].map((group) => StartupEntriesReport.groupReport(group, new StartupEntryReasons(report), reasonsByPlace.get(group.places[0]) ?? /* @__PURE__ */ new Map(), asyncRegistries, code, startLoaded)).sort((first, second) => (second.added?.bytes ?? 0) - (first.added?.bytes ?? 0) || second.entries.length - first.entries.length || StartupEntriesReport.compareText(first.example, second.example));
1972
+ const registries = asyncRegistries.map((registry) => StartupEntriesReport.asyncRegistryReport(registry, code, startLoaded)).sort((first, second) => (second.added?.bytes ?? 0) - (first.added?.bytes ?? 0) || StartupEntriesReport.compareText(first.owner, second.owner) || StartupEntriesReport.compareText(first.registry, second.registry));
1973
+ return {
1974
+ app: report.app,
1975
+ defersPackages: report.defersPackages,
1976
+ entries: report.entries.length,
1977
+ groupCount: sortedGroups.length,
1978
+ ...code === void 0 || startLoaded === void 0 ? {} : {
1979
+ start: code.sizeOf(startLoaded),
1980
+ ...StartupEntriesReport.byPackageNameOf(code, report.start.map((entry) => entry.package), "startByPackageName"),
1981
+ byPackageNameOnly: !code.hasLoaders()
1982
+ },
1983
+ groups: top === void 0 ? sortedGroups : sortedGroups.slice(0, top),
1984
+ summary: StartupEntriesReport.summaryOf(report, sortedGroups, code, startLoaded),
1985
+ asyncRegistryCount: registries.length,
1986
+ asyncRegistries: top === void 0 ? registries : registries.slice(0, top)
1806
1987
  };
1807
1988
  }
1808
- /**
1809
- * The option sources of a Nitro config file, highest priority first: the production overlays, then the
1810
- * object itself. An `extends` or `defaultPreset` key brings values that the source does not show, so it adds
1811
- * an unproven source below the object.
1812
- */
1813
- static readNitroConfig(file) {
1814
- const { program, imports } = NitroStaticConfig.parse(file);
1815
- const resolved = NitroStaticConfig.exportedObject(program, imports, NitroStaticConfig.nitroConfigHelper);
1816
- if (resolved.kind === "unproven") return [{
1817
- kind: "unproven",
1818
- file,
1819
- reason: resolved.reason
1820
- }];
1821
- const base = NitroStaticConfig.prove(resolved.node, file);
1822
- if (base.kind === "unproven") return [base];
1823
- const overlay = /* @__PURE__ */ new Map();
1824
- const sources = [];
1825
- const overlays = [base.entries.get("$production")];
1826
- const environments = base.entries.get("$env");
1827
- if (environments !== void 0) {
1828
- const proven = NitroStaticConfig.prove(environments, file);
1829
- if (proven.kind === "unproven") sources.push(proven);
1830
- else overlays.push(proven.entries.get("production"));
1831
- }
1832
- for (const node of overlays) {
1833
- if (node === void 0) continue;
1834
- const proven = NitroStaticConfig.prove(node, file);
1835
- if (proven.kind === "unproven") sources.push(proven);
1836
- else for (const [key, value] of proven.entries) overlay.set(key, value);
1989
+ /** The report of one group of entries. */
1990
+ static groupReport(group, reasonNames, reasons, asyncRegistries, code, startLoaded) {
1991
+ const places = [...group.places].sort((first, second) => StartupEntriesReport.compareText(first, second));
1992
+ const addedFiles = code === void 0 || startLoaded === void 0 ? void 0 : code.codeOf(group.packages, startLoaded);
1993
+ const bytesByPackage = code === void 0 || addedFiles === void 0 ? /* @__PURE__ */ new Map() : code.packageBytes(addedFiles);
1994
+ const identitiesByName = /* @__PURE__ */ new Map();
1995
+ for (const identity of group.packages) {
1996
+ const name = StartupBuiltCode.packageNameOf(identity);
1997
+ identitiesByName.set(name, [...identitiesByName.get(name) ?? [], identity]);
1837
1998
  }
1838
- if (overlay.size > 0) sources.push({
1839
- kind: "object",
1840
- file,
1841
- entries: overlay
1842
- });
1843
- sources.push(base);
1844
- return sources;
1999
+ const modules = [...bytesByPackage].filter(([, bytes]) => bytes > 0).map(([name, bytes]) => {
2000
+ const identities = identitiesByName.get(name);
2001
+ if (identities === void 0) return {
2002
+ module: name,
2003
+ bytes,
2004
+ reasons: [StartupEntryReasons.imported()]
2005
+ };
2006
+ const described = [...new Map(identities.flatMap((identity) => reasons.get(identity) ?? []).map((reason) => reasonNames.describe(reason)).map((named) => [named.text, named])).values()];
2007
+ return {
2008
+ module: identities.join(", "),
2009
+ bytes,
2010
+ reasons: described.length === 0 ? [StartupEntryReasons.notRecorded()] : described
2011
+ };
2012
+ }).sort((first, second) => second.bytes - first.bytes || StartupEntriesReport.compareText(first.module, second.module)).slice(0, StartupEntriesReport.namedModuleCount);
2013
+ const sealPackages = /* @__PURE__ */ new Map();
2014
+ for (const identity of group.packages) for (const reason of reasons.get(identity) ?? []) if (reason.kind === StartReasonKind.SealGroup && reason.source !== void 0) sealPackages.set(reason.source, [...sealPackages.get(reason.source) ?? [], identity]);
2015
+ const sealGroups = [...sealPackages].sort(([first], [second]) => StartupEntriesReport.compareText(first, second)).map(([registry, packages]) => ({
2016
+ registry,
2017
+ packages,
2018
+ ...addedFiles === void 0 ? {} : { bytes: [...new Set(packages.map((identity) => StartupBuiltCode.packageNameOf(identity)))].reduce((sum, name) => sum + (bytesByPackage.get(name) ?? 0), 0) }
2019
+ }));
2020
+ const loadedWithEntry = startLoaded === void 0 || addedFiles === void 0 ? void 0 : /* @__PURE__ */ new Set([...startLoaded, ...addedFiles]);
2021
+ return {
2022
+ packages: group.packages,
2023
+ entries: places,
2024
+ example: places[0],
2025
+ ...code === void 0 || addedFiles === void 0 ? {} : { added: code.sizeOf(addedFiles) },
2026
+ modules,
2027
+ sealGroups,
2028
+ onRead: asyncRegistries.filter((registry) => group.packages.includes(registry.owner)).map((registry) => ({
2029
+ registry: registry.registry,
2030
+ owner: registry.owner,
2031
+ ...code === void 0 || loadedWithEntry === void 0 ? {} : { added: code.sizeOf(code.codeOf(registry.packages.map((loaded) => loaded.package), loadedWithEntry)) }
2032
+ })),
2033
+ ...code === void 0 ? {} : StartupEntriesReport.byPackageNameOf(code, group.packages, "byPackageName")
2034
+ };
2035
+ }
2036
+ /** A field that names the packages whose files `code` finds by npm package name, or no field. */
2037
+ static byPackageNameOf(code, identities, field) {
2038
+ const byPackageName = code.byPackageName(identities);
2039
+ return byPackageName.length === 0 ? {} : { [field]: byPackageName };
1845
2040
  }
1846
2041
  /**
1847
- * What the Vite config says: whether it imports the Nitro plugin, and the option sources it gives. Once the
1848
- * plugin is imported, anything the reader cannot prove makes the sources unproven; the project is still a
1849
- * Nitro host.
2042
+ * The report of one async registry: the code of its first `load()` call beyond the start and the code that
2043
+ * loads with the owner.
1850
2044
  */
1851
- static readVite(file) {
1852
- const { program, imports } = NitroStaticConfig.parse(file);
1853
- const named = /* @__PURE__ */ new Set();
1854
- const namespaces = /* @__PURE__ */ new Set();
1855
- for (const entry of imports) {
1856
- if (entry.request !== NitroStaticConfig.nitroVitePackage || entry.isTypeOnly) continue;
1857
- if (entry.importKind === ImportKind.Namespace) namespaces.add(entry.localName);
1858
- else if (entry.importKind === ImportKind.Named && entry.importedName === "nitro") named.add(entry.localName);
2045
+ static asyncRegistryReport(registry, code, startLoaded) {
2046
+ const packages = registry.packages.map((loaded) => loaded.package);
2047
+ let added;
2048
+ if (code !== void 0 && startLoaded !== void 0) {
2049
+ const loaded = /* @__PURE__ */ new Set([...startLoaded, ...code.codeOf([registry.owner, ...registry.ownerPackages], startLoaded)]);
2050
+ added = code.sizeOf(code.codeOf(packages, loaded));
1859
2051
  }
1860
- if (named.size === 0 && namespaces.size === 0) return {
1861
- usesNitroPlugin: false,
1862
- sources: []
2052
+ return {
2053
+ registry: registry.registry,
2054
+ owner: registry.owner,
2055
+ inputKey: registry.inputKey,
2056
+ contributors: registry.contributors,
2057
+ packages,
2058
+ ...added === void 0 ? {} : { added },
2059
+ ...code === void 0 ? {} : StartupEntriesReport.byPackageNameOf(code, packages, "byPackageName")
1863
2060
  };
1864
- const unproven = (reason) => ({
1865
- usesNitroPlugin: true,
1866
- sources: [{
1867
- kind: "unproven",
1868
- file,
1869
- reason
1870
- }]
1871
- });
1872
- const importStarts = new Set(program.descendants("ImportDeclaration").flatMap((declaration) => declaration.descendants(AstNodeType.Identifier)).map((identifier) => identifier.start));
1873
- const calls = program.descendants(AstNodeType.CallExpression).flatMap((call) => {
1874
- const callee = call.child("callee");
1875
- if (callee.is(AstNodeType.Identifier) && named.has(callee.name ?? "")) return [{
1876
- call,
1877
- referenceStart: callee.start
1878
- }];
1879
- if (callee.is(AstNodeType.MemberExpression) && !callee.flagAt("computed") && callee.child("property").name === "nitro" && callee.child("object").is(AstNodeType.Identifier) && namespaces.has(callee.child("object").name ?? "")) return [{
1880
- call,
1881
- referenceStart: callee.child("object").start
2061
+ }
2062
+ /** The summary of the entries of one app, over every group. */
2063
+ static summaryOf(report, groups, code, startLoaded) {
2064
+ const kinds = /* @__PURE__ */ new Map();
2065
+ for (const entry of report.entries) kinds.set(entry.kind, [...kinds.get(entry.kind) ?? [], entry.packages]);
2066
+ const everyEntry = [...kinds].filter(([, sets]) => sets.length > 1).sort(([first], [second]) => StartupEntriesReport.compareText(first, second)).flatMap(([kind, sets]) => {
2067
+ const shared = sets[0].filter((identity) => sets.every((set) => set.includes(identity)));
2068
+ return shared.length === 0 ? [] : [{
2069
+ kind,
2070
+ entries: sets.length,
2071
+ packages: shared,
2072
+ ...code === void 0 || startLoaded === void 0 ? {} : { added: code.sizeOf(code.codeOf(shared, startLoaded)) }
1882
2073
  }];
1883
- return [];
1884
2074
  });
1885
- const callStarts = new Set(calls.map((entry) => entry.referenceStart));
1886
- const nameStarts = NitroStaticConfig.nameStarts(program);
1887
- if (program.descendants(AstNodeType.Identifier).filter((identifier) => (named.has(identifier.name ?? "") || namespaces.has(identifier.name ?? "")) && !importStarts.has(identifier.start) && !nameStarts.has(identifier.start) && !callStarts.has(identifier.start)).length > 0) return unproven("the Nitro Vite plugin is used other than by a direct call");
1888
- if (calls.length !== 1) return unproven(`the Nitro Vite plugin is called ${calls.length} times, not once`);
1889
- const resolved = NitroStaticConfig.exportedObject(program, imports, NitroStaticConfig.viteConfigHelper);
1890
- if (resolved.kind === "unproven") return unproven(resolved.reason);
1891
- const config = NitroStaticConfig.prove(resolved.node, file);
1892
- if (config.kind === "unproven") return {
1893
- usesNitroPlugin: true,
1894
- sources: [config]
1895
- };
1896
- const plugins = NitroStaticConfig.unwrap(config.entries.get("plugins"));
1897
- const call = calls[0].call;
1898
- if (!(plugins?.is(AstNodeType.ArrayExpression) === true && plugins.children("elements").some((element) => NitroStaticConfig.unwrap(element)?.start === call.start))) return unproven("the Nitro Vite plugin is not a direct element of the `plugins` array");
1899
- const sources = [];
1900
- const argument = NitroStaticConfig.unwrap(call.children("arguments")[0]);
1901
- if (argument !== void 0) {
1902
- const options = NitroStaticConfig.prove(argument, file);
1903
- sources.push(options);
1904
- const nested = options.kind === "object" ? options.entries.get("config") : void 0;
1905
- if (nested !== void 0) sources.push(NitroStaticConfig.prove(nested, file));
1906
- }
1907
- const nitroKey = config.entries.get("nitro");
1908
- if (nitroKey !== void 0) sources.push(NitroStaticConfig.prove(nitroKey, file));
2075
+ if (code === void 0 || report.entries.length === 0) return { everyEntry };
2076
+ const entryBytes = groups.flatMap((group) => group.entries.map(() => group.added?.bytes ?? 0)).sort((first, second) => first - second);
2077
+ const p75 = StartupEntriesReport.percentile(entryBytes, .75);
2078
+ const heavyGroups = groups.filter((group) => {
2079
+ const bytes = group.added?.bytes ?? 0;
2080
+ return bytes > 0 && bytes >= p75;
2081
+ });
2082
+ const heavyCounts = /* @__PURE__ */ new Map();
2083
+ for (const group of heavyGroups) for (const identity of group.packages) heavyCounts.set(identity, (heavyCounts.get(identity) ?? 0) + group.entries.length);
1909
2084
  return {
1910
- usesNitroPlugin: true,
1911
- sources
1912
- };
1913
- }
1914
- /**
1915
- * The object that `export default` gives: a literal, a call of the verified identity helper over one, or a
1916
- * single top-level `const` that holds either and is never assigned again.
1917
- */
1918
- static exportedObject(program, imports, helper) {
1919
- const helperNames = new Set(imports.filter((entry) => entry.importKind === ImportKind.Named && entry.importedName === helper.name && helper.packages.includes(entry.request) && !entry.isTypeOnly).map((entry) => entry.localName));
1920
- const declaration = program.children("body").find((statement) => statement.is(AstNodeType.ExportDefaultDeclaration))?.child("declaration");
1921
- const objectOf = (node, viaConstant) => {
1922
- const expression = NitroStaticConfig.unwrap(node);
1923
- if (expression === void 0) return {
1924
- kind: "unproven",
1925
- reason: "the config has no default export"
1926
- };
1927
- if (expression.is(AstNodeType.ObjectExpression)) return {
1928
- kind: "found",
1929
- node: expression
1930
- };
1931
- if (expression.is(AstNodeType.CallExpression)) {
1932
- const callee = expression.child("callee");
1933
- return callee.is(AstNodeType.Identifier) && helperNames.has(callee.name ?? "") && expression.children("arguments").length === 1 ? objectOf(expression.children("arguments")[0], viaConstant) : {
1934
- kind: "unproven",
1935
- reason: `the config is a call of something other than ${helper.name} from ${helper.packages.join(" or ")}`
1936
- };
1937
- }
1938
- if (expression.is(AstNodeType.Identifier) && !viaConstant) {
1939
- const initializer = NitroStaticConfig.constantOf(program, expression.name ?? "", expression.start);
1940
- return initializer === void 0 ? {
1941
- kind: "unproven",
1942
- reason: `\`${expression.name}\` is not a top-level const that nothing else uses`
1943
- } : objectOf(initializer, true);
2085
+ bytes: {
2086
+ median: StartupEntriesReport.percentile(entryBytes, .5),
2087
+ p75,
2088
+ max: entryBytes.at(-1) ?? 0
2089
+ },
2090
+ everyEntry,
2091
+ heavy: {
2092
+ entries: heavyGroups.reduce((sum, group) => sum + group.entries.length, 0),
2093
+ modules: [...heavyCounts].sort(([firstModule, firstCount], [secondModule, secondCount]) => secondCount - firstCount || StartupEntriesReport.compareText(firstModule, secondModule)).slice(0, StartupEntriesReport.namedHeavyModuleCount).map(([module, entries]) => ({
2094
+ module,
2095
+ entries
2096
+ }))
1944
2097
  }
1945
- return {
1946
- kind: "unproven",
1947
- reason: "the default export is not an object the reader can prove"
1948
- };
1949
2098
  };
1950
- return objectOf(declaration, false);
1951
2099
  }
1952
- /**
1953
- * The initializer of `const <name> = …` at the top level, when the name has no use except the one at
1954
- * `exportStart` (the default export, or the single wrapper call around it). A member assignment
1955
- * (`config.preset = …`), a call that gets the name (`Object.assign(config, …)`), or a spread of it is another
1956
- * use, and it makes the value unknown.
1957
- */
1958
- static constantOf(program, name, exportStart) {
1959
- const initializers = [];
1960
- for (const statement of program.children("body")) {
1961
- const declaration = statement.is(AstNodeType.ExportNamedDeclaration) ? statement.child("declaration") : statement;
1962
- if (declaration.stringAt("kind") !== "const") continue;
1963
- for (const declarator of declaration.children("declarations")) if (declarator.child("id").name === name) initializers.push({
1964
- init: declarator.child("init"),
1965
- idStart: declarator.child("id").start
1966
- });
2100
+ /** The text of the report of one app. */
2101
+ static appText(app, serverEntry) {
2102
+ if (app.entries === 0) return `App '${app.app}' has no entries: the first use of each entry loads no package beyond the start.` + StartupEntriesReport.asyncRegistriesText(app);
2103
+ const lines = [`Entries of app '${app.app}': ${StartupEntriesReport.count(app.entries, "entry", "entries")} in ${StartupEntriesReport.count(app.groupCount, "module set", "module sets")}.` + (app.start === void 0 || serverEntry === void 0 ? "" : ` Each row gives the code that the first use of an entry loads after the start (${StartupEntriesReport.sizeText(app.start)}), in the build of ${serverEntry}.`)];
2104
+ if (app.byPackageNameOnly === true) lines.push("The build record names no loader chunk of a package, so the report finds the code of each package by its npm package name. Two roots of one npm package then share their code.");
2105
+ if (app.groups.length < app.groupCount) lines.push(`The ${app.groups.length} largest of the ${app.groupCount} module sets (--top):`);
2106
+ for (const [index, group] of app.groups.entries()) {
2107
+ lines.push(`${index + 1}. ${StartupEntriesReport.count(group.entries.length, "entry", "entries")}, for example '${group.example}'` + (group.added === void 0 ? "." : `: ${StartupEntriesReport.sizeText(group.added)}.`), ` Module set: ${group.packages.length === 0 ? "no package beyond the start" : StartupEntriesReport.listText(group.packages)}.`);
2108
+ for (const module of group.modules) lines.push(` - ${module.module}: ${StartupSizeCheck.formatBytes(module.bytes)} (${module.reasons.map((reason) => reason.text).join("; ")})`);
2109
+ for (const sealGroup of group.sealGroups) lines.push(` - The seal group of ${sealGroup.registry} loads ${StartupEntriesReport.count(sealGroup.packages.length, "package", "packages")}` + (sealGroup.bytes === void 0 ? "" : ` (${StartupSizeCheck.formatBytes(sealGroup.bytes)})`) + " with these entries. Extend AsyncContributions<T> for the registry, so that its contributors load on its first load() call.");
2110
+ if (app.byPackageNameOnly !== true && group.byPackageName !== void 0) lines.push(` - Found by npm package name, as the build record names no loader chunk: ${StartupEntriesReport.listText(group.byPackageName)}.`);
2111
+ for (const onRead of group.onRead) lines.push(` - On read: a load() call of '${onRead.registry}' of ${onRead.owner} can add ` + (onRead.added === void 0 ? "the code of its contributors." : `${StartupEntriesReport.sizeText(onRead.added)}. The row above does not count it.`));
1967
2112
  }
1968
- if (initializers.length !== 1) return;
1969
- const names = NitroStaticConfig.nameStarts(program);
1970
- return program.descendants(AstNodeType.Identifier).filter((identifier) => identifier.name === name && identifier.start !== initializers[0].idStart && identifier.start !== exportStart && !names.has(identifier.start)).length === 0 ? initializers[0].init : void 0;
2113
+ const { summary } = app;
2114
+ if (summary.bytes !== void 0) lines.push(`Per entry: median ${StartupSizeCheck.formatBytes(summary.bytes.median)}, p75 ${StartupSizeCheck.formatBytes(summary.bytes.p75)}, max ${StartupSizeCheck.formatBytes(summary.bytes.max)}.`);
2115
+ for (const every of summary.everyEntry) lines.push(`Every '${every.kind}' entry (${every.entries}) loads ${StartupEntriesReport.count(every.packages.length, "package", "packages")}` + (every.added === void 0 ? "" : ` (${StartupSizeCheck.formatBytes(every.added.bytes)})`) + `: ${StartupEntriesReport.listText(every.packages)}.`);
2116
+ if (summary.heavy !== void 0 && summary.heavy.modules.length > 0) lines.push(`The ${StartupEntriesReport.count(summary.heavy.entries, "heavy entry", "heavy entries")} (p75 or more) load these packages most: ${summary.heavy.modules.map((module) => `${module.module} (${module.entries})`).join(", ")}.`);
2117
+ return lines.join("\n") + StartupEntriesReport.asyncRegistriesText(app);
1971
2118
  }
1972
- /** The starts of identifiers that are names, not references: a property key and a member name. */
1973
- static nameStarts(program) {
1974
- return /* @__PURE__ */ new Set([...program.descendants(AstNodeType.Property).filter((property) => !property.flagAt("computed") && !property.flagAt("shorthand")).map((property) => property.child("key").start), ...program.descendants(AstNodeType.MemberExpression).filter((member) => !member.flagAt("computed")).map((member) => member.child("property").start)]);
2119
+ /** The lines of the async registries of one app, with a newline before them, or nothing. */
2120
+ static asyncRegistriesText(app) {
2121
+ if (app.asyncRegistryCount === 0) return "";
2122
+ return `\n${[`Async registries: the first load() call of each one loads its contributors. No entry counts this code${app.asyncRegistries.length < app.asyncRegistryCount ? ` (the ${app.asyncRegistries.length} largest of ${app.asyncRegistryCount}, --top)` : ""}.`, ...app.asyncRegistries.map((registry) => `- '${registry.registry}' of ${registry.owner}: ${StartupEntriesReport.count(registry.contributors.length, "contributor", "contributors")} (${StartupEntriesReport.listText(registry.contributors, StartupEntriesReport.namedContributorCount)}), ${StartupEntriesReport.count(registry.packages.length, "package", "packages")} beyond the start` + (registry.added === void 0 ? "." : `, ${StartupEntriesReport.sizeText(registry.added)}.`))].join("\n")}`;
1975
2123
  }
1976
- /** The options of one object, or the reason that the reader cannot prove it. */
1977
- static prove(node, file) {
1978
- const object = NitroStaticConfig.unwrap(node);
1979
- if (object === void 0 || !object.is(AstNodeType.ObjectExpression)) return {
1980
- kind: "unproven",
1981
- file,
1982
- reason: "an options value is not an object literal"
1983
- };
1984
- const entries = /* @__PURE__ */ new Map();
1985
- for (const property of object.children("properties")) {
1986
- if (!property.is(AstNodeType.Property)) return {
1987
- kind: "unproven",
1988
- file,
1989
- reason: "an options object has a spread"
2124
+ /** Files and bytes for a person to read. */
2125
+ static sizeText(size) {
2126
+ return `${StartupEntriesReport.count(size.files, "file", "files")}, ${StartupSizeCheck.formatBytes(size.bytes)}`;
2127
+ }
2128
+ /** A list of names, with the count of the rest when it is long. */
2129
+ static listText(names, limit = StartupEntriesReport.namedPackageCount) {
2130
+ const named = names.slice(0, limit).join(", ");
2131
+ const rest = names.length - limit;
2132
+ return rest > 0 ? `${named} and ${rest} more` : named;
2133
+ }
2134
+ /** A count with the noun in the singular or the plural. */
2135
+ static count(value, singular, plural) {
2136
+ return `${value} ${value === 1 ? singular : plural}`;
2137
+ }
2138
+ /** An entry as `<kind> <key>`, as `heximon.startup.json` names it. */
2139
+ static placeOf(kind, key) {
2140
+ return `${kind} ${key}`;
2141
+ }
2142
+ /** The value at a fraction of sorted values, by the nearest rank. */
2143
+ static percentile(sorted, fraction) {
2144
+ return sorted[Math.max(0, Math.ceil(fraction * sorted.length) - 1)] ?? 0;
2145
+ }
2146
+ static compareText(first, second) {
2147
+ return first < second ? -1 : first > second ? 1 : 0;
2148
+ }
2149
+ };
2150
+ //#endregion
2151
+ //#region src/startup-hostless-report.ts
2152
+ /**
2153
+ * The hostless apps of `heximon check --startup`: the modules of each app, from the start reports, and the static
2154
+ * closure of the chunk that holds its boot file, from the build output. The size is a note: it fails nothing.
2155
+ */
2156
+ var StartupHostlessReport = class StartupHostlessReport {
2157
+ /**
2158
+ * The report of the hostless apps of a compile.
2159
+ *
2160
+ * @param reports - The start report of each app. Only the records of hostless apps count.
2161
+ * @param measuring - The measurement of the build output, when the run measured it.
2162
+ */
2163
+ static report(reports, measuring) {
2164
+ const measured = measuring?.kind === "measured" ? measuring : void 0;
2165
+ const serverEntry = measured?.entries.find((entry) => entry.name === ServerBuildRecord.mainEntryName) ?? measured?.entries[0];
2166
+ const apps = reports.filter((report) => report.role === StartReportRole.Hostless).map((report) => {
2167
+ const base = {
2168
+ app: report.app,
2169
+ subject: report.subject ?? report.app,
2170
+ modules: report.modules ?? []
1990
2171
  };
1991
- const key = property.child("key");
1992
- const name = key.name ?? key.stringAt("value");
1993
- if (property.flagAt("computed") || property.flagAt("method") || property.stringAt("kind") !== "init" || name === void 0) return {
1994
- kind: "unproven",
1995
- file,
1996
- reason: "an options object has a computed key, a getter or a method"
2172
+ if (serverEntry === void 0 || report.bootFile === void 0) return base;
2173
+ const size = StartupHostlessReport.sizeOf(report.bootFile, serverEntry, measured?.generated);
2174
+ return typeof size === "string" ? {
2175
+ ...base,
2176
+ sizeUnavailable: size
2177
+ } : {
2178
+ ...base,
2179
+ size
1997
2180
  };
1998
- entries.set(name, property.child("value"));
2181
+ });
2182
+ return {
2183
+ apps,
2184
+ lines: apps.map((app) => StartupHostlessReport.line(app, serverEntry?.measurement.entry))
2185
+ };
2186
+ }
2187
+ /** The static closure of the chunk that holds a boot file, or why there is none. */
2188
+ static sizeOf(bootFile, serverEntry, generated) {
2189
+ if (generated === void 0) return CheckHostlessSizeUnavailable.NoChunkRecord;
2190
+ const chunk = Object.keys(generated).sort().find((fileName) => generated[fileName].includes(bootFile));
2191
+ if (chunk === void 0) return CheckHostlessSizeUnavailable.NoChunk;
2192
+ const files = new Map(serverEntry.measurement.files.map((file) => [file.path, file]));
2193
+ const chunkFile = files.get(chunk);
2194
+ if (chunkFile === void 0) return CheckHostlessSizeUnavailable.NotReached;
2195
+ const reached = /* @__PURE__ */ new Set([chunk]);
2196
+ const pending = [chunk];
2197
+ for (let path = pending.pop(); path !== void 0; path = pending.pop()) for (const target of serverEntry.staticImports[path] ?? []) if (!reached.has(target)) {
2198
+ reached.add(target);
2199
+ pending.push(target);
1999
2200
  }
2000
2201
  return {
2001
- kind: "object",
2002
- file,
2003
- entries
2202
+ chunk,
2203
+ start: {
2204
+ files: reached.size,
2205
+ bytes: [...reached].reduce((sum, path) => sum + (files.get(path)?.bytes ?? 0), 0)
2206
+ },
2207
+ ...chunkFile.isStart ? { inStartClosure: true } : {}
2004
2208
  };
2005
2209
  }
2006
- /** A string option: the first source that sets it decides. */
2007
- static scalar(key, sources, emptyIsAbsent = false) {
2008
- for (const source of sources) {
2009
- if (source.kind === "unproven") return {
2010
- kind: "computed",
2011
- file: source.file,
2012
- reason: source.reason
2013
- };
2014
- const node = source.entries.get(key);
2015
- if (node === void 0) continue;
2016
- const value = NitroStaticConfig.stringOf(node);
2017
- if (emptyIsAbsent && value === "") continue;
2018
- return value === void 0 ? {
2019
- kind: "computed",
2020
- file: source.file,
2021
- reason: `\`${key}\` is not a string literal`
2022
- } : {
2023
- kind: "literal",
2024
- value
2025
- };
2210
+ /** The text line of one hostless app. */
2211
+ static line(app, entry) {
2212
+ const count = app.modules.length;
2213
+ const head = `Hostless app '${app.app}' (${app.subject}) has ${count} module${count === 1 ? "" : "s"}${count === 0 ? "" : `: ${app.modules.join(", ")}`}.`;
2214
+ if (app.size !== void 0) {
2215
+ const { files, bytes } = app.size.start;
2216
+ const closure = `${head} The static closure of its chunk ${app.size.chunk} has ${files} file${files === 1 ? "" : "s"}, ${StartupSizeCheck.formatBytes(bytes)}.`;
2217
+ return app.size.inStartClosure === true ? `${closure} The chunk is also in the static start closure of ${entry ?? "the server entry"}, so this code loads with the start and adds no startup cost of its own. The closure can also hold code of the main app's start.` : closure;
2218
+ }
2219
+ switch (app.sizeUnavailable) {
2220
+ case CheckHostlessSizeUnavailable.NoChunkRecord: return `${head} The build record ${ServerBuildRecord.relativePath} does not name the generated files of its chunks, so the app has no size. Build the app again with this version of Heximon.`;
2221
+ case CheckHostlessSizeUnavailable.NoChunk: return `${head} No chunk of the build holds its boot file, so the app has no size. Build the app again.`;
2222
+ case CheckHostlessSizeUnavailable.NotReached: return `${head} The size walk of ${entry ?? "the server entry"} does not reach the chunk of its boot file, so the app has no size.`;
2223
+ default: return head;
2026
2224
  }
2027
- return { kind: "none" };
2028
2225
  }
2226
+ };
2227
+ //#endregion
2228
+ //#region src/project-modules.ts
2229
+ /**
2230
+ * Imports packages the way the generated wiring imports them: through a small module written into the
2231
+ * compile output directory, which sits in the project. The specifiers inside it resolve from the project, so
2232
+ * the command gets the copy of a package that the wiring gets. A package the command imported from its own
2233
+ * install would be a second set of class objects, and `app.from(CoreModule)` would not know them.
2234
+ */
2235
+ var ProjectModules = class ProjectModules {
2029
2236
  /**
2030
- * The options of one nested section (such as `heximon`) of each source, in the same order. A section that is
2031
- * not an object literal the reader can prove is unproven; a source without the section adds nothing.
2237
+ * Import `specifiers` of the project.
2238
+ *
2239
+ * @param directory - A directory inside the project, with write access (the compile output directory).
2240
+ * @param fileName - The name of the module to write, unique among the calls for one directory.
2241
+ * @param source - The module source: `export … from "<specifier>"` lines.
2242
+ * @returns The namespace of the written module.
2032
2243
  */
2033
- static sectionSources(key, sources) {
2034
- return sources.flatMap((source) => {
2035
- if (source.kind === "unproven") return [source];
2036
- const section = source.entries.get(key);
2037
- return section === void 0 ? [] : [NitroStaticConfig.prove(section, source.file)];
2038
- });
2244
+ static async import(directory, fileName, source) {
2245
+ const file = join(directory, fileName);
2246
+ writeFileSync(file, source);
2247
+ return await import(pathToFileURL(file).href);
2039
2248
  }
2040
- /** A list option: every source adds to it, so one unproven source makes it unknown. */
2041
- static list(key, sources) {
2042
- const values = [];
2043
- let found = false;
2044
- for (const source of sources) {
2045
- if (source.kind === "unproven") return {
2046
- kind: "computed",
2047
- file: source.file,
2048
- reason: source.reason
2049
- };
2050
- const node = NitroStaticConfig.unwrap(source.entries.get(key));
2051
- if (node === void 0) continue;
2052
- const strings = (node.is(AstNodeType.ArrayExpression) ? node.children("elements") : []).map((element) => NitroStaticConfig.stringOf(element));
2053
- if (!node.is(AstNodeType.ArrayExpression) || strings.some((value) => value === void 0)) return {
2054
- kind: "computed",
2055
- file: source.file,
2056
- reason: `\`${key}\` is not an array of string literals`
2057
- };
2058
- found = true;
2059
- values.push(...strings);
2060
- }
2061
- return found ? {
2062
- kind: "literal",
2063
- value: values
2064
- } : { kind: "none" };
2249
+ /** The runtime of the project: everything the command asks of `@heximon/runtime`. */
2250
+ static runtime(directory) {
2251
+ return ProjectModules.import(directory, "project-runtime.js", "export * from \"@heximon/runtime\";\n");
2065
2252
  }
2066
- /** The text of a string literal or of a template literal with no placeholder; else `undefined`. */
2067
- static stringOf(node) {
2068
- const value = NitroStaticConfig.unwrap(node);
2069
- if (value === void 0) return;
2070
- if (typeof value.literalValue === "string") return value.literalValue;
2071
- if (value.is(AstNodeType.TemplateLiteral) && !value.hasChildren("expressions")) return value.children("quasis")[0]?.child("value").stringAt("cooked");
2253
+ };
2254
+ //#endregion
2255
+ //#region src/nitro-host.ts
2256
+ /**
2257
+ * The production inputs of a Nitro host project, for the preset that was read from its config files. The
2258
+ * preset picks the deploy platform, and the compile adds the Nitro host plugin, so a compile that reads the
2259
+ * sidecar alone would build another graph. `@heximon/nitro` of the project makes the inputs from the preset
2260
+ * name. Both packages load from the project, so the plugins, the strategy and the compiler are one copy. No
2261
+ * Nitro or Vite config runs.
2262
+ */
2263
+ var NitroHost = class NitroHost {
2264
+ context;
2265
+ aliases;
2266
+ constructor(context, aliases) {
2267
+ this.context = context;
2268
+ this.aliases = aliases;
2072
2269
  }
2073
- /** The node without its wrappers (`as`, `satisfies`, `!`, parentheses); `undefined` when absent. */
2074
- static unwrap(node) {
2075
- let current = node;
2076
- while (current !== void 0 && current.exists() && NitroStaticConfig.wrapperTypes.includes(current.type ?? "")) current = current.child("expression");
2077
- return current === void 0 || !current.exists() ? void 0 : current;
2270
+ /**
2271
+ * Resolve the inputs of the Nitro host.
2272
+ *
2273
+ * @param rootDir - The project root.
2274
+ * @param directory - A directory inside the project to write the import module into.
2275
+ * @param request - The preset (or the choice to take the platform from the sidecar), the literal source
2276
+ * directories of the Nitro config, and the module aliases of the project (the tsconfig `paths`).
2277
+ * @throws {Error} When `@heximon/nitro` is not installed in the project.
2278
+ */
2279
+ static async open(rootDir, directory, request) {
2280
+ const modules = await ProjectModules.import(directory, "project-nitro.js", "export { resolveNitroPresetInputs } from \"@heximon/nitro/module\";\n");
2281
+ return new NitroHost(await modules.resolveNitroPresetInputs({
2282
+ rootDirectory: rootDir,
2283
+ preset: request.preset,
2284
+ aliases: request.aliases.prefixes,
2285
+ ...request.serverDir === void 0 ? {} : { serverDir: request.serverDir },
2286
+ ...request.scanDirs === void 0 ? {} : { scanDirs: request.scanDirs },
2287
+ ...request.platformFromSidecar === true ? { platformFromSidecar: true } : {}
2288
+ }), request.aliases);
2078
2289
  }
2079
- static parse(file) {
2080
- const parsed = new SourceParser().parse(file, readFileSync(file, "utf8"));
2290
+ /** Whether the sidecar declares the deploy platform. */
2291
+ hasSidecarPlatform() {
2292
+ return this.context.config?.platform !== void 0;
2293
+ }
2294
+ /**
2295
+ * Why the preset is a custom preset (a path, a package, or a name that Nitro does not know), or `undefined` for
2296
+ * a built-in preset. The strategy of a custom preset comes from the sidecar `platform`, as for a computed one.
2297
+ */
2298
+ customPresetReason() {
2299
+ return this.context.customPreset;
2300
+ }
2301
+ /** The production compile inputs of the host: the strategy, the plugins, the sidecar, the source directories. */
2302
+ inputs() {
2303
+ return this.context;
2304
+ }
2305
+ /**
2306
+ * Run the compile the host's production build runs.
2307
+ *
2308
+ * @param rootDir - The project root.
2309
+ * @param outputDirectory - Where the generated files will be written.
2310
+ * @param sourceDirectories - The source directories to scan instead of the host's, when the caller has some.
2311
+ */
2312
+ compile(rootDir, outputDirectory, sourceDirectories) {
2313
+ const context = this.context;
2314
+ const config = context.config;
2315
+ const compiler = new ProjectCompiler();
2081
2316
  return {
2082
- program: parsed.program,
2083
- imports: parsed.imports
2317
+ output: compiler.compile({
2318
+ rootDir,
2319
+ outputDirectory,
2320
+ sourceDirectories: sourceDirectories ?? context.sourceDirectories,
2321
+ aliases: this.aliases.prefixes,
2322
+ exactAliases: this.aliases.exact,
2323
+ plugins: context.plugins,
2324
+ strategy: context.strategy,
2325
+ ...context.wiringMode === void 0 ? {} : { wiringMode: context.wiringMode },
2326
+ ...config === void 0 ? {} : { config },
2327
+ ...context.runtimeConfig === void 0 ? {} : { runtimeConfig: context.runtimeConfig },
2328
+ ...config?.root === void 0 ? {} : { apps: { main: config.root } },
2329
+ ...context.workspaceSubscribers === void 0 ? {} : { workspaceSubscribers: context.workspaceSubscribers }
2330
+ }),
2331
+ compiler,
2332
+ platformName: context.strategy.platformName
2084
2333
  };
2085
2334
  }
2086
2335
  };
@@ -2120,19 +2369,21 @@ var StartupTarget = class StartupTarget {
2120
2369
  const preset = hostTarget.preset;
2121
2370
  const aliases = TsconfigAliases.read(rootDir, hostTarget.generatedTsconfigFiles);
2122
2371
  const host = await StartupTarget.openHost(rootDir, preset, aliases, explicit === void 0 ? hostTarget.sourceOptions : { scanDirs: explicit });
2123
- if (preset.kind === "computed" && !host.hasSidecarPlatform()) throw CommandFailure.of(CheckDiagnosticCode.NitroConfigComputed, `The Nitro preset of this Nitro host is computed (${preset.reason}, in ${preset.file}), and the command does not run your config files, so it cannot tell the deploy target of the build. The start report depends on that target. Nothing was checked.`, "Declare `platform` in heximon.config.ts (for example `platform: new CloudflareWorkersStrategy()`), or set `preset` in the Nitro config to a string.");
2372
+ const customPreset = host.customPresetReason();
2373
+ const isPresetUnread = preset.kind === "computed" || customPreset !== void 0;
2374
+ if (isPresetUnread && !host.hasSidecarPlatform()) throw CommandFailure.of(CheckDiagnosticCode.NitroConfigComputed, preset.kind === "computed" ? `The Nitro preset of this Nitro host is computed (${preset.reason}, in ${preset.file}), and the command does not run your config files, so it cannot tell the deploy target of the build. The start report depends on that target. Nothing was checked.` : `The Nitro preset of this app is a custom preset (${customPreset}), and the command does not load a custom preset, so it cannot tell the deploy target of the build. The start report depends on that target. Nothing was checked.`, "Declare `platform` in heximon.config.ts (for example `platform: new CloudflareWorkersStrategy()`), " + (preset.kind === "computed" ? "or set `preset` in the Nitro config to a string." : "or set the Nitro preset to the name of a built-in preset."));
2124
2375
  const session = ProjectCompileSession.forNitroHost({
2125
2376
  rootDir,
2126
2377
  inputs: host.inputs(),
2127
2378
  aliases,
2128
2379
  ...explicit === void 0 ? {} : { sourceDirectories: explicit }
2129
2380
  });
2130
- const source = preset.kind === "computed" ? StartupTargetSource.Sidecar : hostTarget.source;
2381
+ const source = isPresetUnread ? StartupTargetSource.Sidecar : hostTarget.source;
2131
2382
  return {
2132
2383
  session,
2133
2384
  target: {
2134
2385
  ...StartupTarget.targetOf(session, source),
2135
- ...preset.kind === "literal" ? { preset: preset.value } : {}
2386
+ ...preset.kind === "literal" && !isPresetUnread ? { preset: preset.value } : {}
2136
2387
  }
2137
2388
  };
2138
2389
  }
@@ -2633,7 +2884,10 @@ const checkCommand = defineCommand({
2633
2884
  ...sessionOptions,
2634
2885
  isSourceExplicit: sourceOption !== void 0 && sourceOption.trim() !== ""
2635
2886
  }) : {
2636
- session: await ProjectCompileSession.open(sessionOptions),
2887
+ session: await ProjectCompileSession.open({
2888
+ ...sessionOptions,
2889
+ hostTarget: mode === CompileMode.App
2890
+ }),
2637
2891
  target: void 0
2638
2892
  };
2639
2893
  const session = opened.session;
@@ -2660,6 +2914,7 @@ const checkCommand = defineCommand({
2660
2914
  workspaceSubscribers: topology.topology
2661
2915
  };
2662
2916
  const output = session.compile(true, appCompileOptions);
2917
+ const targetNote = session.targetNote();
2663
2918
  const staleLibraries = await session.staleLibraryDiagnostics();
2664
2919
  if (staleLibraries.length > 0) checked = {
2665
2920
  diagnostics: staleLibraries,
@@ -2677,15 +2932,18 @@ const checkCommand = defineCommand({
2677
2932
  await session.compiler.formatOnDisk(rootDir, session.outputDirectory, output.files);
2678
2933
  }
2679
2934
  const dropped = verifyBaseline ? UpgradeBaseline.droppedSections(rootDir, output.files, output.diagnostics, session.config?.strictDiagnostics ?? []) : void 0;
2935
+ const cliCodes = new Map(dropped?.cliCodes ?? []);
2936
+ if (targetNote !== void 0) cliCodes.set(targetNote, CheckDiagnosticCode.HostTargetDefault);
2680
2937
  checked = {
2681
2938
  diagnostics: [
2939
+ ...targetNote === void 0 ? [] : [targetNote],
2682
2940
  ...topology.diagnostics,
2683
2941
  ...output.diagnostics,
2684
2942
  ...dropped?.diagnostics ?? []
2685
2943
  ],
2686
2944
  files: output.files,
2687
2945
  startReports: output.startReports ?? [],
2688
- ...dropped === void 0 ? {} : { cliCodes: dropped.cliCodes },
2946
+ ...cliCodes.size === 0 ? {} : { cliCodes },
2689
2947
  ...emitted ? { emittedTo: session.outputDirectory } : {}
2690
2948
  };
2691
2949
  }
@@ -2707,6 +2965,7 @@ const checkCommand = defineCommand({
2707
2965
  app: report.app,
2708
2966
  ...note
2709
2967
  }))) : void 0;
2968
+ const hostlessReport = startup && startupReports !== void 0 ? StartupHostlessReport.report(startupReports, sizeMeasuring) : void 0;
2710
2969
  const entriesReport = entries && startupReports !== void 0 && sizeMeasuring !== void 0 ? StartupEntriesReport.report(startupReports, sizeMeasuring, top) : void 0;
2711
2970
  const sizeResult = sizeMeasuring?.kind === "skipped" ? sizeMeasuring.result : sizeCompared?.result ?? sizeUpdated?.result;
2712
2971
  const diagnostics = [
@@ -2746,6 +3005,7 @@ const checkCommand = defineCommand({
2746
3005
  ...sizeResult === void 0 ? {} : { startupSize: sizeResult },
2747
3006
  ...entriesReport === void 0 ? {} : { startupEntries: entriesReport.result },
2748
3007
  ...startupNotes === void 0 ? {} : { startupNotes },
3008
+ ...hostlessReport === void 0 || hostlessReport.apps.length === 0 ? {} : { startupHostlessApps: hostlessReport.apps },
2749
3009
  ...startup && mode === CompileMode.App && checked.staleLibraries !== true ? { startupBaseline: startupChecked?.result ?? (startupUpdated === void 0 ? {
2750
3010
  action: "update",
2751
3011
  written: false,
@@ -2788,6 +3048,7 @@ const checkCommand = defineCommand({
2788
3048
  log.info(sizeNotes.join("\n"));
2789
3049
  if (sizeCompared?.result.action === "compare" && sizeCompared.result.committed && sizeCompared.result.growth.length === 0 && sizeCompared.result.notes.length === 0) log.success(`The server code is inside the size budget of ${StartupBaselineFile.fileName}.`);
2790
3050
  }
3051
+ for (const line of hostlessReport?.lines ?? []) log.info(line);
2791
3052
  for (const line of entriesReport?.lines ?? []) log.info(line);
2792
3053
  if (mode === CompileMode.Library && upgradeUpdate) log.warn(`${UpgradeBaselineFile.fileName} is an app-level artifact — a library's durable surface is baselined by each app that composes it, so there is nothing here to update.`);
2793
3054
  else if (previewed !== void 0) {
@@ -4968,7 +5229,8 @@ const graphCommand = defineCommand({
4968
5229
  const session = await ProjectCompileSession.open({
4969
5230
  rootDir,
4970
5231
  environment: args.env,
4971
- ...sourceDirectories === void 0 ? {} : { sourceDirectories }
5232
+ ...sourceDirectories === void 0 ? {} : { sourceDirectories },
5233
+ hostTarget: resolved.mode === CompileMode.App
4972
5234
  });
4973
5235
  output = resolved.mode === CompileMode.Library ? session.compileLibrary() : session.compile();
4974
5236
  } catch (error) {
@@ -6141,7 +6403,8 @@ var RoutesCommand = class RoutesCommand {
6141
6403
  const session = await ProjectCompileSession.open({
6142
6404
  rootDir,
6143
6405
  environment: args.env,
6144
- ...sourceDirectories === void 0 ? {} : { sourceDirectories }
6406
+ ...sourceDirectories === void 0 ? {} : { sourceDirectories },
6407
+ hostTarget: mode === CompileMode.App
6145
6408
  });
6146
6409
  compiled = mode === CompileMode.Library ? session.compileLibrary() : session.compile();
6147
6410
  } catch (error) {
@@ -6921,7 +7184,8 @@ var TaskRunner = class TaskRunner {
6921
7184
  aliases: this.aliases,
6922
7185
  ...sourceDirectories
6923
7186
  }));
6924
- if (preset.kind === "computed" && !host.hasSidecarPlatform()) throw new TaskRunFailure(TaskDiagnosticCode.NitroConfigComputed, `The Nitro preset is computed (${preset.reason}, in ${preset.file}), and the command does not run your config files, so it cannot read the platform: declare \`platform\` in heximon.config.ts (for example \`platform: new CloudflareWorkersStrategy()\`), or set NITRO_PRESET. Nothing was booted.`);
7187
+ const customPreset = host.customPresetReason();
7188
+ if ((preset.kind === "computed" || customPreset !== void 0) && !host.hasSidecarPlatform()) throw new TaskRunFailure(TaskDiagnosticCode.NitroConfigComputed, (preset.kind === "computed" ? `The Nitro preset is computed (${preset.reason}, in ${preset.file}), and the command does not run your config files, so it cannot read the platform: ` : `The Nitro preset is a custom preset (${customPreset}), and the command does not load a custom preset, so it cannot read the platform: `) + "declare `platform` in heximon.config.ts (for example `platform: new CloudflareWorkersStrategy()`), " + (preset.kind === "computed" ? "or set NITRO_PRESET." : "or set the Nitro preset to the name of a built-in preset.") + " Nothing was booted.");
6925
7189
  const compiled = host.compile(rootDir, outputDirectory, this.options.isSourceExplicit === true ? this.options.sourceDirectories : void 0);
6926
7190
  ({output, compiler} = compiled);
6927
7191
  this.platformName = compiled.platformName;
@@ -7025,7 +7289,7 @@ var TaskRunner = class TaskRunner {
7025
7289
  throw TaskRunner.failureOf(TaskDiagnosticCode.StartFailed, `The task ${this.options.taskName} did not start`, error);
7026
7290
  }
7027
7291
  try {
7028
- return await task.run(event);
7292
+ return await this.runThroughWorkHooks(runtime, target.task.className, () => task.run(event));
7029
7293
  } catch (error) {
7030
7294
  throw TaskRunner.failureOf(TaskDiagnosticCode.TaskFailed, `The task ${this.options.taskName} failed`, error, TaskRefusal);
7031
7295
  }
@@ -7040,6 +7304,18 @@ var TaskRunner = class TaskRunner {
7040
7304
  throw new TaskRunFailure(TaskDiagnosticCode.ResultNotJson, `The task ran, but its result is not JSON: ${error instanceof Error ? error.message : String(error)}`);
7041
7305
  }
7042
7306
  }
7307
+ /**
7308
+ * Run the task inside the app's work hooks, as `TaskManager` does, so tracing records a `task` span. A
7309
+ * project whose runtime has no work hooks runs the task as it is.
7310
+ */
7311
+ runThroughWorkHooks(runtime, taskName, run) {
7312
+ const workHooks = runtime.WorkHooks;
7313
+ const hooks = workHooks?.hooksFor(this.context);
7314
+ return workHooks === void 0 || hooks === void 0 ? run() : workHooks.runWith(hooks, {
7315
+ kind: runtime.WorkKind.Task,
7316
+ name: taskName
7317
+ }, run);
7318
+ }
7043
7319
  /** The seeds the app declares for every background frame, or none. */
7044
7320
  async seedsOf(runtime) {
7045
7321
  const resolvable = this.app;
@@ -7657,7 +7933,8 @@ const workflowsCommand = defineCommand({
7657
7933
  const session = await ProjectCompileSession.open({
7658
7934
  rootDir,
7659
7935
  environment: args.env,
7660
- ...sourceDirectories === void 0 ? {} : { sourceDirectories }
7936
+ ...sourceDirectories === void 0 ? {} : { sourceDirectories },
7937
+ hostTarget: true
7661
7938
  });
7662
7939
  const output = session.compile();
7663
7940
  const errors = output.diagnostics.filter((diagnostic) => diagnostic.severity === DiagnosticSeverity.Error);