@xessa/cli 0.0.0-stage → 0.1.1

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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/dist/args.d.ts +43 -0
  4. package/dist/args.d.ts.map +1 -0
  5. package/dist/args.js +202 -0
  6. package/dist/args.js.map +1 -0
  7. package/dist/commands/build.d.ts +44 -0
  8. package/dist/commands/build.d.ts.map +1 -0
  9. package/dist/commands/build.js +533 -0
  10. package/dist/commands/build.js.map +1 -0
  11. package/dist/commands/check.d.ts +11 -0
  12. package/dist/commands/check.d.ts.map +1 -0
  13. package/dist/commands/check.js +35 -0
  14. package/dist/commands/check.js.map +1 -0
  15. package/dist/commands/clean.d.ts +12 -0
  16. package/dist/commands/clean.d.ts.map +1 -0
  17. package/dist/commands/clean.js +140 -0
  18. package/dist/commands/clean.js.map +1 -0
  19. package/dist/commands/format.d.ts +41 -0
  20. package/dist/commands/format.d.ts.map +1 -0
  21. package/dist/commands/format.js +127 -0
  22. package/dist/commands/format.js.map +1 -0
  23. package/dist/commands/watch.d.ts +38 -0
  24. package/dist/commands/watch.d.ts.map +1 -0
  25. package/dist/commands/watch.js +338 -0
  26. package/dist/commands/watch.js.map +1 -0
  27. package/dist/compiler.d.ts +20 -0
  28. package/dist/compiler.d.ts.map +1 -0
  29. package/dist/compiler.js +57 -0
  30. package/dist/compiler.js.map +1 -0
  31. package/dist/config.d.ts +93 -0
  32. package/dist/config.d.ts.map +1 -0
  33. package/dist/config.js +331 -0
  34. package/dist/config.js.map +1 -0
  35. package/dist/formatter.d.ts +21 -0
  36. package/dist/formatter.d.ts.map +1 -0
  37. package/dist/formatter.js +38 -0
  38. package/dist/formatter.js.map +1 -0
  39. package/dist/glob.d.ts +52 -0
  40. package/dist/glob.d.ts.map +1 -0
  41. package/dist/glob.js +214 -0
  42. package/dist/glob.js.map +1 -0
  43. package/dist/index.d.ts +34 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +114 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/manifest.d.ts +56 -0
  48. package/dist/manifest.d.ts.map +1 -0
  49. package/dist/manifest.js +138 -0
  50. package/dist/manifest.js.map +1 -0
  51. package/dist/paths.d.ts +24 -0
  52. package/dist/paths.d.ts.map +1 -0
  53. package/dist/paths.js +42 -0
  54. package/dist/paths.js.map +1 -0
  55. package/dist/project.d.ts +44 -0
  56. package/dist/project.d.ts.map +1 -0
  57. package/dist/project.js +92 -0
  58. package/dist/project.js.map +1 -0
  59. package/dist/report.d.ts +128 -0
  60. package/dist/report.d.ts.map +1 -0
  61. package/dist/report.js +128 -0
  62. package/dist/report.js.map +1 -0
  63. package/dist/setup.d.ts +58 -0
  64. package/dist/setup.d.ts.map +1 -0
  65. package/dist/setup.js +181 -0
  66. package/dist/setup.js.map +1 -0
  67. package/dist/writer.d.ts +32 -0
  68. package/dist/writer.d.ts.map +1 -0
  69. package/dist/writer.js +93 -0
  70. package/dist/writer.js.map +1 -0
  71. package/package.json +40 -4
  72. package/src/args.ts +246 -0
  73. package/src/commands/build.ts +682 -0
  74. package/src/commands/check.ts +45 -0
  75. package/src/commands/clean.ts +168 -0
  76. package/src/commands/format.ts +169 -0
  77. package/src/commands/watch.ts +366 -0
  78. package/src/compiler-api.d.ts +261 -0
  79. package/src/compiler.ts +65 -0
  80. package/src/config.ts +443 -0
  81. package/src/formatter.ts +56 -0
  82. package/src/glob.ts +230 -0
  83. package/src/index.ts +137 -0
  84. package/src/manifest.ts +176 -0
  85. package/src/paths.ts +50 -0
  86. package/src/project.ts +122 -0
  87. package/src/report.ts +230 -0
  88. package/src/setup.ts +218 -0
  89. package/src/writer.ts +102 -0
@@ -0,0 +1,682 @@
1
+ /**
2
+ * Build engine shared by `xessa build` and `xessa check`.
3
+ *
4
+ * Entries are planned with the public `planOutputs` API (mirroring the plan the
5
+ * compiler builds internally), compiled together with `compileProject`, and
6
+ * written per-file atomically. Errors keep the last successful outputs and skip
7
+ * every write for the affected entry.
8
+ */
9
+
10
+ import { readFile } from "node:fs/promises";
11
+ import type {
12
+ CompileOptions,
13
+ CompileProjectOptions,
14
+ CompileResult,
15
+ Diagnostic,
16
+ OutputKind,
17
+ PlanOutputsResult,
18
+ ProjectConfig,
19
+ ResolvedSetup,
20
+ } from "@xessa/compiler";
21
+ import type { CliInvocation } from "../args.js";
22
+ import { loadCompiler } from "../compiler.js";
23
+ import type { CliConfig } from "../config.js";
24
+ import { type ManifestRecord, isArtifactRecord, readManifest, writeManifest } from "../manifest.js";
25
+ import { dirnamePosix, joinPosix } from "../paths.js";
26
+ import { type ProjectContext, prepareProject } from "../project.js";
27
+ import {
28
+ type BuildReport,
29
+ type CliDiagnostic,
30
+ DiagnosticPositions,
31
+ type EntryReport,
32
+ type JsonBuildReport,
33
+ type OutputRecord,
34
+ dedupeDiagnostics,
35
+ formatDiagnostic,
36
+ hasErrors,
37
+ invocationFailure,
38
+ toJson,
39
+ writeErrorLine,
40
+ writeLine,
41
+ } from "../report.js";
42
+ import { type FileSetupValues, decodeFileSetup, resolveEffectiveSetup } from "../setup.js";
43
+ import { atomicWrite, hashFile, removeFile, sweepTemporaries } from "../writer.js";
44
+
45
+ /** Options for one build/check run. */
46
+ export interface ExecuteBuildOptions {
47
+ /** Resolved project inputs. */
48
+ readonly context: ProjectContext;
49
+ /** Write artifacts; `false` makes the run a check. */
50
+ readonly write: boolean;
51
+ /** Plan and compile but do not touch the disk. */
52
+ readonly dryRun: boolean;
53
+ /** Remove obsolete owned outputs after a fully successful project build. */
54
+ readonly prune: boolean;
55
+ /** `--minify` / `--no-minify` override. */
56
+ readonly minify?: boolean;
57
+ /** Returns `false` when a newer build generation superseded this one. */
58
+ readonly isCurrent?: () => boolean;
59
+ }
60
+
61
+ /** Result of {@link executeBuild}. */
62
+ export interface ExecuteBuildResult {
63
+ /** Structured report for text or JSON output. */
64
+ readonly report: BuildReport;
65
+ /** Whether the run was discarded because a newer generation started. */
66
+ readonly stale: boolean;
67
+ }
68
+
69
+ interface MutableOutput {
70
+ kind: OutputKind;
71
+ path: string;
72
+ absolutePath: string;
73
+ written: boolean;
74
+ reason?: string;
75
+ }
76
+
77
+ /** Compiler diagnostic code used for CLI-level source read failures. */
78
+ const CLI_SOURCE_ERROR = "XESSACLI002";
79
+ /** Compiler diagnostic code used for CLI-level write failures. */
80
+ const CLI_WRITE_ERROR = "XESSACLI001";
81
+
82
+ /** Run one build or check and return the structured report. */
83
+ export async function executeBuild(options: ExecuteBuildOptions): Promise<ExecuteBuildResult> {
84
+ const { context } = options;
85
+ const command = options.write ? "build" : "check";
86
+ const warnings = [...context.configWarnings];
87
+ const errors: string[] = [];
88
+ const rawByEntry = new Map<string, Diagnostic[]>();
89
+ const positionedByEntry = new Map<string, CliDiagnostic[]>();
90
+
91
+ let compiler: Awaited<ReturnType<typeof loadCompiler>>;
92
+ try {
93
+ compiler = await loadCompiler();
94
+ } catch (error) {
95
+ errors.push(describeError(error));
96
+ return {
97
+ report: emptyReport(command, context, options.dryRun, errors, warnings),
98
+ stale: false,
99
+ };
100
+ }
101
+
102
+ const host = compiler.createNodeHost(context.root);
103
+ const positions = new DiagnosticPositions(context.root);
104
+ const entries = [...context.entries];
105
+ if (entries.length === 0) {
106
+ warnings.push("No .cssx sources matched the project include globs.");
107
+ }
108
+ const setups = new Map<string, FileSetupValues>();
109
+ const sources = new Map<string, string>();
110
+ const resolvedSetups = new Map<string, ResolvedSetup>();
111
+ const minifyOverrides = new Set<string>();
112
+
113
+ for (const entry of entries) {
114
+ let source: string | undefined;
115
+ try {
116
+ source = await readFile(joinPosix(context.root, entry), "utf8");
117
+ sources.set(entry, source);
118
+ } catch (error) {
119
+ const diagnostic: CliDiagnostic = {
120
+ code: CLI_SOURCE_ERROR,
121
+ severity: "error",
122
+ message: `Could not read source: ${describeError(error)}`,
123
+ file: entry,
124
+ line: 1,
125
+ column: 1,
126
+ };
127
+ positionedByEntry.set(entry, [diagnostic]);
128
+ setups.set(entry, {});
129
+ continue;
130
+ }
131
+
132
+ let fileSetup: FileSetupValues = {};
133
+ try {
134
+ fileSetup = decodeFileSetup(compiler.parse(source, { file: entry }).ast);
135
+ } catch {
136
+ fileSetup = {};
137
+ }
138
+ setups.set(entry, fileSetup);
139
+ if (
140
+ options.minify !== undefined &&
141
+ fileSetup.minify !== undefined &&
142
+ fileSetup.minify !== options.minify
143
+ ) {
144
+ minifyOverrides.add(entry);
145
+ warnings.push(
146
+ `${entry}: setup minify ${fileSetup.minify ? "true" : "false"} overridden by CLI flag (${options.minify ? "--minify" : "--no-minify"}).`,
147
+ );
148
+ }
149
+ }
150
+
151
+ // Plan every entry first so cross-entry target collisions are detectable.
152
+ const plans = new Map<string, PlanOutputsResult>();
153
+ const occupied: string[] = [];
154
+ const projectConfig = planProjectConfig(context.config?.output);
155
+ for (const entry of entries) {
156
+ const setup = resolveEffectiveSetup(
157
+ entry,
158
+ context.config,
159
+ setups.get(entry) ?? {},
160
+ options.minify,
161
+ );
162
+ resolvedSetups.set(entry, setup);
163
+ let plan: PlanOutputsResult;
164
+ try {
165
+ plan = compiler.planOutputs(
166
+ {
167
+ sourceFile: entry,
168
+ setup,
169
+ ...(projectConfig === undefined ? {} : { projectConfig }),
170
+ workspaceRoot: context.root,
171
+ },
172
+ {
173
+ host: { canonicalize: (path) => host.canonicalize(path) },
174
+ occupiedTargets: [...occupied],
175
+ },
176
+ );
177
+ } catch (error) {
178
+ errors.push(`Could not plan outputs for ${entry}: ${describeError(error)}`);
179
+ continue;
180
+ }
181
+ plans.set(entry, plan);
182
+ for (const output of plan.plan.outputs) occupied.push(output.absolutePath);
183
+ }
184
+
185
+ // Sweep `.cssx-tmp` files left by a process that died between the temporary
186
+ // write and its rename, before this run writes anything. Only the writer's own
187
+ // dot-prefixed pattern is matched, never user files.
188
+ if (options.write && !options.dryRun) {
189
+ const directories = new Set<string>([context.root]);
190
+ for (const plan of plans.values()) {
191
+ for (const output of plan.plan.outputs) directories.add(dirnamePosix(output.absolutePath));
192
+ }
193
+ await sweepTemporaries([...directories]);
194
+ }
195
+
196
+ // Compile all entries through one shared module graph.
197
+ let results: Record<string, CompileResult> = {};
198
+ try {
199
+ results = await compiler.compileProject(
200
+ entries,
201
+ host,
202
+ compileOptions(context.config, options.minify),
203
+ );
204
+ } catch (error) {
205
+ errors.push(`Compilation failed: ${describeError(error)}`);
206
+ }
207
+
208
+ // A file `@setup minify` beats the compiler's project layer, but explicit CLI
209
+ // flags are the highest precedence (SPECIFICATION.md §9.1). Recompile only
210
+ // the conflicting entries with `compile`, whose API options override file
211
+ // setup, and take its CSS text; class maps, types, plans and dependencies stay
212
+ // with the shared project compilation.
213
+ if (options.minify !== undefined && minifyOverrides.size > 0) {
214
+ for (const entry of minifyOverrides) {
215
+ const result = results[entry];
216
+ const setup = resolvedSetups.get(entry);
217
+ const source = sources.get(entry);
218
+ const cssPlanned = plans.get(entry)?.plan.outputs.some((output) => output.kind === "css");
219
+ if (result === undefined || setup === undefined || source === undefined || !cssPlanned) {
220
+ continue;
221
+ }
222
+ const css = await compileWithMinifyOverride(
223
+ compiler,
224
+ context,
225
+ entry,
226
+ source,
227
+ setup,
228
+ options.minify,
229
+ );
230
+ if (css === undefined) {
231
+ warnings.push(
232
+ `${entry}: could not apply the CLI minify override; keeping the setup value.`,
233
+ );
234
+ continue;
235
+ }
236
+ results[entry] = { ...result, css };
237
+ }
238
+ }
239
+
240
+ const mutableOutputs = new Map<string, MutableOutput[]>();
241
+ const dependencies = new Map<string, readonly string[]>();
242
+ const successfulSources = new Set<string>();
243
+ let stale = false;
244
+
245
+ for (const entry of entries) {
246
+ const result = results[entry];
247
+ const plan = plans.get(entry);
248
+ const raw: Diagnostic[] = [];
249
+ if (result !== undefined) raw.push(...result.diagnostics);
250
+ if (plan !== undefined) raw.push(...plan.diagnostics);
251
+ rawByEntry.set(entry, dedupeRaw(raw));
252
+ dependencies.set(entry, result?.dependencies ?? []);
253
+
254
+ const outputs: MutableOutput[] = [];
255
+ for (const planned of plan?.plan.outputs ?? []) {
256
+ outputs.push({
257
+ kind: planned.kind,
258
+ path: planned.workspacePath,
259
+ absolutePath: planned.absolutePath,
260
+ written: false,
261
+ });
262
+ }
263
+ mutableOutputs.set(entry, outputs);
264
+ }
265
+
266
+ // Position all diagnostics before writing so text and JSON agree.
267
+ for (const entry of entries) {
268
+ const positioned = await positions.convert(rawByEntry.get(entry) ?? []);
269
+ const extra = positionedByEntry.get(entry) ?? [];
270
+ positionedByEntry.set(entry, dedupeDiagnostics([...positioned, ...extra]));
271
+ }
272
+
273
+ const writesEnabled = options.write && !options.dryRun;
274
+ // Checked immediately before the first artifact rename (no await intervenes),
275
+ // so a generation discarded here writes nothing at all.
276
+ if (writesEnabled && options.isCurrent !== undefined && !options.isCurrent()) stale = true;
277
+
278
+ const writtenRecords: ManifestRecord[] = [];
279
+
280
+ for (const entry of entries) {
281
+ const entryDiagnostics = positionedByEntry.get(entry) ?? [];
282
+ const entryHasErrors = hasErrors(entryDiagnostics);
283
+ const outputs = mutableOutputs.get(entry) ?? [];
284
+ const result = results[entry];
285
+
286
+ if (!options.write) {
287
+ for (const output of outputs) output.reason = "check";
288
+ continue;
289
+ }
290
+ if (options.dryRun) {
291
+ for (const output of outputs) output.reason = "dry-run";
292
+ continue;
293
+ }
294
+ if (stale) {
295
+ for (const output of outputs) output.reason = "stale";
296
+ continue;
297
+ }
298
+ if (entryHasErrors || result === undefined) {
299
+ for (const output of outputs) output.reason = "error";
300
+ continue;
301
+ }
302
+
303
+ let entryFailed = false;
304
+ for (const output of outputs) {
305
+ const content = artifactContent(result, output.kind);
306
+ if (content === undefined) {
307
+ output.reason = output.kind === "cssSourceMap" ? "not-implemented" : "missing-artifact";
308
+ warnings.push(
309
+ output.kind === "cssSourceMap"
310
+ ? `${output.path}: CSS source maps land in P7; artifact not written.`
311
+ : `${output.path}: the compiler did not return ${output.kind} content; artifact not written.`,
312
+ );
313
+ continue;
314
+ }
315
+ try {
316
+ const hash = await atomicWrite(output.absolutePath, content);
317
+ output.written = true;
318
+ writtenRecords.push({ kind: output.kind, path: output.path, source: entry, hash });
319
+ } catch (error) {
320
+ output.reason = "write-failed";
321
+ entryFailed = true;
322
+ const writeDiagnostic: CliDiagnostic = {
323
+ code: CLI_WRITE_ERROR,
324
+ severity: "error",
325
+ message: `Failed to write ${output.path}: ${describeError(error)}`,
326
+ file: entry,
327
+ line: 1,
328
+ column: 1,
329
+ };
330
+ positionedByEntry.set(
331
+ entry,
332
+ dedupeDiagnostics([...(positionedByEntry.get(entry) ?? []), writeDiagnostic]),
333
+ );
334
+ break;
335
+ }
336
+ }
337
+ if (!entryFailed) successfulSources.add(entry);
338
+ }
339
+
340
+ if (writesEnabled && !stale) {
341
+ const pruneAll =
342
+ options.prune && entries.length > 0 && successfulSources.size === entries.length;
343
+ try {
344
+ const previous = await readManifest(context.root);
345
+ warnings.push(...previous.warnings);
346
+ const replaceSources = pruneAll ? new Set<string>() : new Set(successfulSources);
347
+ const rewritten = new Set(writtenRecords.map((record) => record.path));
348
+ const kept = previous.manifest.files.filter((record) =>
349
+ rewritten.has(record.path) ? false : !(pruneAll || replaceSources.has(record.source)),
350
+ );
351
+ const obsolete = previous.manifest.files.filter(
352
+ (record) => !rewritten.has(record.path) && (pruneAll || replaceSources.has(record.source)),
353
+ );
354
+ const cleanup = await pruneRecords(context.root, obsolete);
355
+ warnings.push(...cleanup.warnings);
356
+ errors.push(...cleanup.errors);
357
+ const nextRecords = mergeRecords(kept, writtenRecords);
358
+ // Always persist the manifest once any artifact was renamed into place. A
359
+ // filesystem event can arrive after the check above and during the write
360
+ // loop; skipping the manifest then left the tree newer than the records
361
+ // (the CSSX-T06 desync). The next generation rebuilds from this consistent
362
+ // state, so nothing is lost and nothing is reported as owned twice.
363
+ await writeManifest(context.root, { version: 1, files: nextRecords });
364
+ } catch (error) {
365
+ errors.push(`Could not update .cssx-manifest.json: ${describeError(error)}`);
366
+ }
367
+ }
368
+
369
+ const entryReports: EntryReport[] = entries.map((entry) => ({
370
+ file: entry,
371
+ dependencies: dependencies.get(entry) ?? [],
372
+ outputs: (mutableOutputs.get(entry) ?? []).map(toOutputRecord),
373
+ diagnostics: positionedByEntry.get(entry) ?? [],
374
+ }));
375
+
376
+ const report: BuildReport = {
377
+ command,
378
+ workspaceRoot: context.root,
379
+ configFile: context.config?.file ?? null,
380
+ dryRun: options.dryRun,
381
+ entries: entryReports,
382
+ diagnostics: dedupeDiagnostics(entryReports.flatMap((entry) => entry.diagnostics)),
383
+ warnings,
384
+ errors,
385
+ };
386
+
387
+ return { report, stale };
388
+ }
389
+
390
+ /** `xessa build` command entry point. */
391
+ export async function runBuild(invocation: CliInvocation, cwd: string): Promise<number> {
392
+ const prepared = await prepareProject(invocation, cwd);
393
+ if (!prepared.ok) return invocationFailure(invocation.command, prepared.message, invocation.json);
394
+ if (!prepared.context.singleEntry && prepared.context.entries.length === 0) {
395
+ return invocationFailure(
396
+ invocation.command,
397
+ "No .cssx sources matched the project include globs.",
398
+ invocation.json,
399
+ );
400
+ }
401
+
402
+ let outcome: ExecuteBuildResult;
403
+ try {
404
+ outcome = await executeBuild({
405
+ context: prepared.context,
406
+ write: true,
407
+ dryRun: invocation.dryRun,
408
+ prune: !prepared.context.singleEntry,
409
+ ...(invocation.minify === undefined ? {} : { minify: invocation.minify }),
410
+ });
411
+ } catch (error) {
412
+ return invocationFailure(invocation.command, describeError(error), invocation.json);
413
+ }
414
+
415
+ emitReport(outcome.report, invocation.json);
416
+ return reportExitCode(outcome.report);
417
+ }
418
+
419
+ /** Convert a report into its machine-readable shape. */
420
+ export function toJsonReport(report: BuildReport): JsonBuildReport {
421
+ const failed = hasErrors(report.diagnostics) || report.errors.length > 0;
422
+ return {
423
+ command: report.command,
424
+ success: !failed,
425
+ exitCode: failed ? 1 : 0,
426
+ dryRun: report.dryRun,
427
+ workspaceRoot: report.workspaceRoot,
428
+ configFile: report.configFile,
429
+ entries: report.entries.map((entry) => ({
430
+ file: entry.file,
431
+ dependencies: entry.dependencies,
432
+ outputs: entry.outputs.map((output) => ({
433
+ kind: output.kind,
434
+ path: output.path,
435
+ written: output.written,
436
+ ...(output.reason === undefined ? {} : { reason: output.reason }),
437
+ })),
438
+ diagnostics: entry.diagnostics,
439
+ })),
440
+ diagnostics: report.diagnostics,
441
+ warnings: report.warnings,
442
+ errors: report.errors,
443
+ };
444
+ }
445
+
446
+ /** Print a report as text or JSON. */
447
+ export function emitReport(report: BuildReport, json: boolean): void {
448
+ if (json) {
449
+ writeLine(toJson(toJsonReport(report)).trimEnd());
450
+ return;
451
+ }
452
+
453
+ for (const diagnostic of report.diagnostics) writeErrorLine(formatDiagnostic(diagnostic));
454
+ for (const warning of report.warnings) writeErrorLine(`xessa: warning: ${warning}`);
455
+ for (const error of report.errors) writeErrorLine(`xessa: error: ${error}`);
456
+
457
+ const written = report.entries.flatMap((entry) =>
458
+ entry.outputs.filter((output) => output.written),
459
+ );
460
+ for (const output of written) writeLine(`wrote ${output.path}`);
461
+
462
+ const errorCount = report.diagnostics.filter((entry) => entry.severity === "error").length;
463
+ const warningCount =
464
+ report.diagnostics.filter((entry) => entry.severity === "warning").length +
465
+ report.warnings.length;
466
+ if (report.command === "check") {
467
+ writeLine(
468
+ `xessa check: ${report.entries.length} entr${report.entries.length === 1 ? "y" : "ies"} checked, ` +
469
+ `${errorCount} error${plural(errorCount)}, ${warningCount} warning${plural(warningCount)}`,
470
+ );
471
+ return;
472
+ }
473
+ if (report.dryRun) {
474
+ writeLine(`xessa build: dry run, ${plannedCount(report)} file(s) planned`);
475
+ return;
476
+ }
477
+ if (errorCount > 0 || report.errors.length > 0) {
478
+ writeLine(`xessa build: failed (${errorCount} error${plural(errorCount)})`);
479
+ return;
480
+ }
481
+ writeLine(
482
+ `xessa build: ${report.entries.length} entr${report.entries.length === 1 ? "y" : "ies"}, ` +
483
+ `${written.length} file${plural(written.length)} written, ` +
484
+ `${warningCount} warning${plural(warningCount)}`,
485
+ );
486
+ }
487
+
488
+ /** Exit code for a completed report: 1 when any error exists. */
489
+ export function reportExitCode(report: BuildReport): number {
490
+ return hasErrors(report.diagnostics) || report.errors.length > 0 ? 1 : 0;
491
+ }
492
+
493
+ function plannedCount(report: BuildReport): number {
494
+ return report.entries.reduce((count, entry) => count + entry.outputs.length, 0);
495
+ }
496
+
497
+ function compileOptions(
498
+ config: CliConfig | null,
499
+ minify: boolean | undefined,
500
+ ): CompileProjectOptions {
501
+ const output = config?.output;
502
+ const mergedOutput =
503
+ output === undefined && minify === undefined
504
+ ? undefined
505
+ : {
506
+ ...(output ?? {}),
507
+ ...(minify === undefined ? {} : { minify }),
508
+ };
509
+ return {
510
+ ...(mergedOutput === undefined ? {} : { output: mergedOutput }),
511
+ ...(config?.classes === undefined ? {} : { naming: config.classes }),
512
+ ...(config?.media === undefined ? {} : { media: config.media }),
513
+ ...(config?.compiler?.strict === undefined ? {} : { strict: config.compiler.strict }),
514
+ ...(config?.compiler?.mediaGrouping === undefined
515
+ ? {}
516
+ : { mediaGrouping: config.compiler.mediaGrouping }),
517
+ };
518
+ }
519
+
520
+ /** Planner project layer exactly as `compileProject` passes it (directories only). */
521
+ function planProjectConfig(output: CliConfig["output"]): ProjectConfig | undefined {
522
+ if (output === undefined) return undefined;
523
+ const directories = {
524
+ ...(output.cssDir === undefined ? {} : { cssDir: output.cssDir }),
525
+ ...(output.mapDir === undefined ? {} : { mapDir: output.mapDir }),
526
+ };
527
+ if (directories.cssDir === undefined && directories.mapDir === undefined) return undefined;
528
+ return { output: directories };
529
+ }
530
+
531
+ /**
532
+ * Recompile one entry so an explicit `--minify`/`--no-minify` flag wins over a
533
+ * file `@setup minify`. Only the CSS text is taken: destinations, class maps,
534
+ * types and dependency records remain those of the shared project compile.
535
+ */
536
+ async function compileWithMinifyOverride(
537
+ compiler: Awaited<ReturnType<typeof loadCompiler>>,
538
+ context: ProjectContext,
539
+ entry: string,
540
+ source: string,
541
+ setup: ResolvedSetup,
542
+ minify: boolean,
543
+ ): Promise<string | undefined> {
544
+ const options: CompileOptions = {
545
+ file: entry,
546
+ workspaceRoot: context.root,
547
+ prefix: setup.prefix,
548
+ minify,
549
+ emitCss: true,
550
+ emitMap: false,
551
+ emitTypes: false,
552
+ ...(context.config?.media === undefined ? {} : { media: context.config.media }),
553
+ ...(context.config?.compiler?.mediaGrouping === undefined
554
+ ? {}
555
+ : { mediaGrouping: context.config.compiler.mediaGrouping }),
556
+ };
557
+ try {
558
+ const result = await compiler.compile(source, options);
559
+ return result.css;
560
+ } catch {
561
+ return undefined;
562
+ }
563
+ }
564
+
565
+ function artifactContent(result: CompileResult, kind: OutputKind): string | undefined {
566
+ switch (kind) {
567
+ case "css":
568
+ return result.css;
569
+ case "js":
570
+ return result.js;
571
+ case "types":
572
+ return result.types;
573
+ case "cssSourceMap":
574
+ return result.sourceMap;
575
+ }
576
+ }
577
+
578
+ function dedupeRaw(diagnostics: readonly Diagnostic[]): Diagnostic[] {
579
+ const seen = new Set<string>();
580
+ const result: Diagnostic[] = [];
581
+ for (const diagnostic of diagnostics) {
582
+ const key = [
583
+ diagnostic.code,
584
+ diagnostic.severity,
585
+ diagnostic.span.file,
586
+ diagnostic.span.start,
587
+ diagnostic.span.end,
588
+ diagnostic.message,
589
+ ].join("\u0000");
590
+ if (seen.has(key)) continue;
591
+ seen.add(key);
592
+ result.push(diagnostic);
593
+ }
594
+ return result;
595
+ }
596
+
597
+ function toOutputRecord(output: MutableOutput): OutputRecord {
598
+ return {
599
+ kind: output.kind,
600
+ path: output.path,
601
+ absolutePath: output.absolutePath,
602
+ written: output.written,
603
+ ...(output.reason === undefined ? {} : { reason: output.reason }),
604
+ };
605
+ }
606
+
607
+ function mergeRecords(
608
+ previous: readonly ManifestRecord[],
609
+ written: readonly ManifestRecord[],
610
+ ): ManifestRecord[] {
611
+ const byPath = new Map<string, ManifestRecord>();
612
+ for (const record of previous) byPath.set(record.path, record);
613
+ for (const record of written) byPath.set(record.path, record);
614
+ return [...byPath.values()].sort((left, right) => (left.path < right.path ? -1 : 1));
615
+ }
616
+
617
+ interface CleanupOutcome {
618
+ readonly warnings: readonly string[];
619
+ readonly errors: readonly string[];
620
+ }
621
+
622
+ /**
623
+ * Delete obsolete owned outputs that are still byte-identical to their recorded
624
+ * hash. Files modified since generation are kept and reported.
625
+ */
626
+ async function pruneRecords(
627
+ root: string,
628
+ obsolete: readonly ManifestRecord[],
629
+ ): Promise<CleanupOutcome> {
630
+ const warnings: string[] = [];
631
+ const errors: string[] = [];
632
+
633
+ for (const record of obsolete) {
634
+ if (!isArtifactRecord(record)) {
635
+ warnings.push(
636
+ `Not removing ${record.path}: the record does not describe a compiler artifact; ownership released.`,
637
+ );
638
+ continue;
639
+ }
640
+ const absolute = joinPosix(root, record.path);
641
+ const currentHash = await hashFile(absolute);
642
+ if (currentHash === null) continue;
643
+ if (currentHash !== record.hash) {
644
+ warnings.push(`Not removing ${record.path}: modified since generation; ownership released.`);
645
+ continue;
646
+ }
647
+ try {
648
+ await removeFile(absolute);
649
+ } catch (error) {
650
+ errors.push(`Could not remove obsolete output ${record.path}: ${describeError(error)}`);
651
+ }
652
+ }
653
+
654
+ return { warnings, errors };
655
+ }
656
+
657
+ function emptyReport(
658
+ command: "build" | "check",
659
+ context: ProjectContext,
660
+ dryRun: boolean,
661
+ errors: readonly string[],
662
+ warnings: readonly string[],
663
+ ): BuildReport {
664
+ return {
665
+ command,
666
+ workspaceRoot: context.root,
667
+ configFile: context.config?.file ?? null,
668
+ dryRun,
669
+ entries: [],
670
+ diagnostics: [],
671
+ warnings,
672
+ errors,
673
+ };
674
+ }
675
+
676
+ function describeError(error: unknown): string {
677
+ return error instanceof Error ? error.message : String(error);
678
+ }
679
+
680
+ function plural(count: number): string {
681
+ return count === 1 ? "" : "s";
682
+ }