@nifrajs/web 3.1.0 → 3.3.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.
Files changed (114) hide show
  1. package/dist/build-plan.d.ts +228 -0
  2. package/dist/build-plan.d.ts.map +1 -0
  3. package/dist/build-plan.js +514 -0
  4. package/dist/build-plan.js.map +1 -0
  5. package/dist/build-vite.d.ts +2 -1
  6. package/dist/build-vite.d.ts.map +1 -1
  7. package/dist/build-vite.js.map +1 -1
  8. package/dist/build.d.ts +2 -197
  9. package/dist/build.d.ts.map +1 -1
  10. package/dist/build.js +61 -502
  11. package/dist/build.js.map +1 -1
  12. package/dist/chunk-names.d.ts.map +1 -1
  13. package/dist/chunk-names.js +3 -2
  14. package/dist/chunk-names.js.map +1 -1
  15. package/dist/dev-ssr-graph.d.ts.map +1 -1
  16. package/dist/dev-ssr-graph.js +63 -28
  17. package/dist/dev-ssr-graph.js.map +1 -1
  18. package/dist/diagnostic.d.ts.map +1 -1
  19. package/dist/diagnostic.js +9 -2
  20. package/dist/diagnostic.js.map +1 -1
  21. package/dist/fonts-google.d.ts.map +1 -1
  22. package/dist/fonts-google.js +3 -1
  23. package/dist/fonts-google.js.map +1 -1
  24. package/dist/fs.d.ts.map +1 -1
  25. package/dist/fs.js +2 -1
  26. package/dist/fs.js.map +1 -1
  27. package/dist/index.d.ts +15 -609
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +22 -1935
  30. package/dist/index.js.map +1 -1
  31. package/dist/internal/codegen.d.ts +68 -0
  32. package/dist/internal/codegen.d.ts.map +1 -0
  33. package/dist/internal/codegen.js +317 -0
  34. package/dist/internal/codegen.js.map +1 -0
  35. package/dist/internal/head-merge.d.ts +2 -0
  36. package/dist/internal/head-merge.d.ts.map +1 -1
  37. package/dist/internal/head-merge.js +17 -1
  38. package/dist/internal/head-merge.js.map +1 -1
  39. package/dist/internal/parity.d.ts +7 -0
  40. package/dist/internal/parity.d.ts.map +1 -1
  41. package/dist/internal/parity.js +212 -30
  42. package/dist/internal/parity.js.map +1 -1
  43. package/dist/internal/render-document.d.ts +372 -0
  44. package/dist/internal/render-document.d.ts.map +1 -0
  45. package/dist/internal/render-document.js +744 -0
  46. package/dist/internal/render-document.js.map +1 -0
  47. package/dist/internal/runtime-contract.d.ts +48 -0
  48. package/dist/internal/runtime-contract.d.ts.map +1 -0
  49. package/dist/internal/runtime-contract.js +27 -0
  50. package/dist/internal/runtime-contract.js.map +1 -0
  51. package/dist/internal/web-app.d.ts +171 -0
  52. package/dist/internal/web-app.d.ts.map +1 -0
  53. package/dist/internal/web-app.js +844 -0
  54. package/dist/internal/web-app.js.map +1 -0
  55. package/dist/islands.d.ts +48 -0
  56. package/dist/islands.d.ts.map +1 -1
  57. package/dist/islands.js +79 -0
  58. package/dist/islands.js.map +1 -1
  59. package/dist/module-graph.d.ts.map +1 -1
  60. package/dist/module-graph.js +22 -9
  61. package/dist/module-graph.js.map +1 -1
  62. package/dist/nano.d.ts +125 -0
  63. package/dist/nano.d.ts.map +1 -0
  64. package/dist/nano.js +190 -0
  65. package/dist/nano.js.map +1 -0
  66. package/dist/plugins/css-modules.js +2 -2
  67. package/dist/plugins/css-modules.js.map +1 -1
  68. package/dist/plugins/kit.d.ts +12 -0
  69. package/dist/plugins/kit.d.ts.map +1 -1
  70. package/dist/plugins/kit.js +62 -12
  71. package/dist/plugins/kit.js.map +1 -1
  72. package/dist/plugins/postcss.js +2 -2
  73. package/dist/plugins/postcss.js.map +1 -1
  74. package/dist/plugins/scss.js +2 -2
  75. package/dist/plugins/scss.js.map +1 -1
  76. package/dist/plugins/stylex.d.ts +70 -0
  77. package/dist/plugins/stylex.d.ts.map +1 -0
  78. package/dist/plugins/stylex.js +166 -0
  79. package/dist/plugins/stylex.js.map +1 -0
  80. package/dist/plugins/svg.js +2 -2
  81. package/dist/plugins/svg.js.map +1 -1
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +23 -23
  84. package/dist/router.js.map +1 -1
  85. package/dist/vite.d.ts.map +1 -1
  86. package/dist/vite.js +26 -10
  87. package/dist/vite.js.map +1 -1
  88. package/package.json +39 -3
  89. package/src/build-plan.ts +741 -0
  90. package/src/build-vite.ts +1 -4
  91. package/src/build.ts +84 -716
  92. package/src/chunk-names.ts +3 -2
  93. package/src/dev-ssr-graph.ts +63 -28
  94. package/src/diagnostic.ts +14 -2
  95. package/src/fonts-google.ts +3 -1
  96. package/src/fs.ts +2 -1
  97. package/src/index.ts +73 -2705
  98. package/src/internal/codegen.ts +400 -0
  99. package/src/internal/head-merge.ts +19 -1
  100. package/src/internal/parity.ts +215 -35
  101. package/src/internal/render-document.ts +1116 -0
  102. package/src/internal/runtime-contract.ts +54 -0
  103. package/src/internal/web-app.ts +1114 -0
  104. package/src/islands.ts +85 -0
  105. package/src/module-graph.ts +23 -9
  106. package/src/nano.ts +246 -0
  107. package/src/plugins/css-modules.ts +2 -2
  108. package/src/plugins/kit.ts +65 -12
  109. package/src/plugins/postcss.ts +2 -2
  110. package/src/plugins/scss.ts +2 -2
  111. package/src/plugins/stylex.ts +298 -0
  112. package/src/plugins/svg.ts +2 -2
  113. package/src/router.ts +24 -24
  114. package/src/vite.ts +33 -9
package/src/build.ts CHANGED
@@ -7,12 +7,36 @@
7
7
  */
8
8
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
9
9
  import { cp, lstat, mkdir, realpath } from "node:fs/promises"
10
- import { dirname, join, relative, resolve as resolvePath, sep } from "node:path"
10
+ import {
11
+ dirname,
12
+ join,
13
+ basename as pathBasename,
14
+ relative,
15
+ resolve as resolvePath,
16
+ sep,
17
+ } from "node:path"
11
18
  import {
12
19
  singleCopyPlugin as declaredSingleCopyPlugin,
13
20
  readSingleCopyDeclaration,
14
21
  } from "@nifrajs/core/single-copy"
15
22
  import { type BunPlugin, Glob } from "bun"
23
+ import {
24
+ aggregateSizeReport,
25
+ type BuildManifest,
26
+ type BuildTarget,
27
+ type Bundler,
28
+ type ChunkSize,
29
+ detectNodeBuiltinsInClient,
30
+ detectServerOnlyInClient,
31
+ formatNodeBuiltinLeak,
32
+ formatServerOnlyLeak,
33
+ parseManifestClientEntry,
34
+ parseManifestRouteStyles,
35
+ parseManifestStyles,
36
+ planBuildTarget,
37
+ type ServerBuild,
38
+ type SizeReport,
39
+ } from "./build-plan.ts"
16
40
  import { sanitizeOutputNames } from "./chunk-names.ts"
17
41
  import { discoverRoutes } from "./fs.ts"
18
42
  import { generateClientEntry, generateServerManifest } from "./index.ts"
@@ -30,9 +54,32 @@ import {
30
54
  serverFnNamespace,
31
55
  } from "./internal/server-boundary.ts"
32
56
  // `buildTarget(static)` drives the SSG prerender engine directly (it's also re-exported below).
33
- import { type ClientModuleGraph, fromBunMetafile } from "./module-graph.ts"
57
+ import { fromBunMetafile } from "./module-graph.ts"
34
58
  import { prerenderRoutes } from "./prerender.ts"
35
59
 
60
+ export * from "./build-plan.ts"
61
+
62
+ const basename = (path: string): string => pathBasename(path)
63
+ // The lazy shape declares `const loaders`, the eager shape `const modules`. Anchored at a line start,
64
+ // NOT `.includes("const loaders =")`: the real emit is `const loaders: Record<...> = {`, whose `:` type
65
+ // annotation sits between the name and the `=`, so the ` =` substring never matched and every lazy
66
+ // manifest was re-synced as eager (silently converting `import()` splitting into a single eager bundle).
67
+ const MANIFEST_IS_LAZY = /^const loaders\b/m
68
+ const entryName = (file: string): string => {
69
+ const base = basename(file)
70
+ const dot = base.lastIndexOf(".")
71
+ return dot === -1 ? base : base.slice(0, dot)
72
+ }
73
+
74
+ /** The slice of Bun's build metafile this build path reads: per JS OUTPUT, its source `entryPoint` and
75
+ * the `cssBundle` Bun emitted for that entry. The guard-facing import graph is adapted separately by
76
+ * `fromBunMetafile`; this smaller view is only for the per-route stylesheet map. */
77
+ interface BunMetafile {
78
+ readonly outputs?: Readonly<
79
+ Record<string, { readonly entryPoint?: string; readonly cssBundle?: string }>
80
+ >
81
+ }
82
+
36
83
  // Build-time SSG: prerender opted-in static + dynamic routes to `index.html` (+ static `_data.json`),
37
84
  // run after `buildClient`.
38
85
  export {
@@ -290,596 +337,6 @@ export async function copyPublicDir(from: string, to: string): Promise<string[]>
290
337
  return copied.sort()
291
338
  }
292
339
 
293
- export interface BuildManifest {
294
- /** URL of the client entry module (content-hashed). */
295
- readonly entry: string
296
- /** URLs of every emitted asset (entry + chunks) - for serving + preloading. */
297
- readonly assets: readonly string[]
298
- /** `routeId → [layout chunk URLs…, own chunk URL]` - the chunks a route needs, for `createWebApp`'s
299
- * `routePreload` (`<link rel="modulepreload">` the matched route alongside the entry). Each route +
300
- * layout is also a build entrypoint, so it gets a named chunk the bootstrap's lazy import dedupes to. */
301
- readonly routes: Readonly<Record<string, readonly string[]>>
302
- /** URL paths copied from `publicDir`, sorted. Lets the server entry serve them without scanning a
303
- * directory per request, and lets an adapter that needs a file list (CDN upload, platform static
304
- * assets) consume one. Omitted when there is no `public/`. */
305
- readonly publicFiles?: readonly string[]
306
- /** The app's bundled, content-hashed stylesheet(s) - the bootstrap's **aggregate** CSS (every
307
- * `import './x.css'` reachable from the app). The complete stylesheet regardless of which file
308
- * imported the CSS; the always-safe fallback `createWebApp` links when a route has no per-route entry
309
- * in {@link routeStyles}. Omitted when the app imports no CSS. */
310
- readonly css?: readonly string[]
311
- /** `routeId → [chain CSS URLs]` - only the stylesheets the matched route's layout chain + own file
312
- * actually use (Bun emits a per-entrypoint CSS bundle per route/layout, with shared-component CSS
313
- * inlined into each consumer). `createWebApp` links these instead of the aggregate, so a page ships
314
- * only its own CSS. A route is omitted (→ aggregate fallback) when its `[name]` collides with another
315
- * route's basename (ambiguous CSS↔route) or the build emitted orphan shared-chunk CSS - correctness
316
- * over minimality. Absent entirely when the app imports no CSS. */
317
- readonly routeStyles?: Readonly<Record<string, readonly string[]>>
318
- }
319
-
320
- /** One edge in the metafile's import graph: the resolved `path` + the `original` specifier as written
321
- * (so `import "node:crypto"` records `original: "node:crypto"` even after Bun resolves it to a
322
- * polyfill path). Other Bun fields (`kind`, `external`) are ignored here. */
323
- interface BunMetafileImport {
324
- readonly path?: string
325
- readonly original?: string
326
- }
327
- /** The slice of Bun's build metafile nifra reads: per INPUT module, the specifiers it `imports`
328
- * (for the `node:` guard); per JS OUTPUT, its source `entryPoint`, the `cssBundle` Bun emitted for
329
- * that entry, and the `inputs` (graph keys) that landed in it (for the per-route CSS map + locating
330
- * which chunk a flagged builtin reached). Not yet in `@types/bun`; shape per the Bun bundler docs. */
331
- interface BunMetafileOutput {
332
- readonly entryPoint?: string
333
- readonly cssBundle?: string
334
- readonly inputs?: Readonly<Record<string, unknown>>
335
- }
336
- interface BunMetafile {
337
- readonly inputs?: Readonly<Record<string, { readonly imports?: readonly BunMetafileImport[] }>>
338
- readonly outputs: Readonly<Record<string, BunMetafileOutput>>
339
- }
340
-
341
- /** The `node:` specifier of an import edge, or undefined if it isn't a Node built-in. Reads the
342
- * `original` (as-written) specifier first, falling back to the resolved `path` (an `external` node:
343
- * import keeps `node:` in its path). */
344
- const nodeBuiltinOf = (im: BunMetafileImport): string | undefined => {
345
- if (im.original?.startsWith("node:")) return im.original
346
- if (im.path?.startsWith("node:")) return im.path
347
- return undefined
348
- }
349
-
350
- /** One `node:`-builtin-in-the-client finding: the offending builtin, the emitted chunk it landed in,
351
- * and the shortest USER-module import chain that pulled it there (entry → … → builtin). */
352
- export interface NodeBuiltinFinding {
353
- readonly builtin: string
354
- readonly chunk: string
355
- /** The shortest import path from a user entry to the builtin, as a list of display labels:
356
- * `[entryFile, ...as-written specifiers along the way, builtin]`, e.g.
357
- * `["routes/article/[slug].tsx", "../data.ts", "../db/client.ts", "postgres", "node:tls"]`. The
358
- * entry is its graph key (the route file); each hop is the import's *as-written* specifier; the tail
359
- * is the builtin. Empty only if the builtin module isn't reachable from any traced input (it always
360
- * is when flagged). */
361
- readonly chain: readonly string[]
362
- }
363
-
364
- /**
365
- * BFS the metafile import graph for the SHORTEST user-module path that pulls `builtin` into the
366
- * bundle, returning it as display labels `[entryFile, …as-written specifiers…, builtin]`. The frontier
367
- * starts at every `entryInput` (the route/user entrypoints) so the reported chain begins where the dev
368
- * actually wrote `import` - the actionable root, not an arbitrary internal module. Traversal crosses
369
- * only NON-`node:` edges (so Bun's polyfill chain never extends the path) and stops at the first edge
370
- * whose target is the builtin. Returns `[builtin]` if no entry reaches it (defensive; a flagged builtin
371
- * is reachable by construction). Pure - operates on the graph, never the emitted text.
372
- */
373
- function shortestBuiltinChain(
374
- inputs: Readonly<Record<string, { readonly imports?: readonly BunMetafileImport[] }>>,
375
- entryInputs: readonly string[],
376
- builtin: string,
377
- ): string[] {
378
- // Each queue item carries the resolved-path node + the display chain to reach it (entry + the
379
- // as-written specifier of every hop crossed so far). `seen` dedupes nodes so the BFS is linear and
380
- // the first time we touch the builtin's importer is via a shortest path.
381
- const seen = new Set<string>(entryInputs)
382
- let frontier: Array<{ node: string; chain: string[] }> = entryInputs.map((node) => ({
383
- node,
384
- chain: [node],
385
- }))
386
- while (frontier.length > 0) {
387
- const next: Array<{ node: string; chain: string[] }> = []
388
- for (const { node, chain } of frontier) {
389
- for (const im of inputs[node]?.imports ?? []) {
390
- // The builtin reached via THIS edge → the chain ends here (append the builtin label). Match on
391
- // the same `node:` detection the finding used (`original` first, then resolved `path`).
392
- if (nodeBuiltinOf(im) === builtin) return [...chain, builtin]
393
- const target = im.path
394
- // Only follow edges into user (non-`node:`) modules that exist in the input graph and haven't
395
- // been visited - so the polyfill subtree can't lengthen the path and there are no cycles.
396
- if (
397
- target === undefined ||
398
- target.startsWith("node:") ||
399
- inputs[target] === undefined ||
400
- seen.has(target)
401
- ) {
402
- continue
403
- }
404
- seen.add(target)
405
- // Display the hop by its as-written specifier (`../db/client.ts`, `postgres`), falling back to
406
- // the resolved path - that's what the dev recognizes in their source, not the resolved path.
407
- next.push({ node: target, chain: [...chain, im.original ?? target] })
408
- }
409
- }
410
- frontier = next
411
- }
412
- return [builtin] // unreachable from any entry - degrade to just the builtin (shouldn't happen)
413
- }
414
-
415
- /**
416
- * Scan a build's metafile for any `node:` builtin that a USER module pulled into a CLIENT output
417
- * chunk, returning a sorted, deduped list of {@link NodeBuiltinFinding}s. Three graph facts combine so
418
- * the report is precise AND actionable:
419
- * 1. **What the user wrote** - only builtins imported by a NON-`node:` input count, so Bun's own
420
- * polyfill chain (`node:crypto` → `node:buffer`/`node:stream`/…) doesn't bury the real cause.
421
- * 2. **Where it landed** - the chunk is read from the per-output `inputs`, so the error names the
422
- * emitted file to look at.
423
- * 3. **How it got there** - the shortest import chain from a user entry to the builtin
424
- * (`shortestBuiltinChain`), so the error points straight at the offending `import` line instead of
425
- * leaving the dev to grep the dependency tree (the DX gap this closes).
426
- * Graph-based (never the emitted text), so it survives minification and can't be fooled by a string
427
- * literal that merely contains `"node:crypto"`. Pure + exported for unit testing. Empty ⇒ clean.
428
- */
429
- export function detectNodeBuiltinsInClient(
430
- graph: ClientModuleGraph,
431
- ): ReadonlyArray<NodeBuiltinFinding> {
432
- const inputs = graph.modules
433
- // (1) The builtins a user (non-polyfill) module imports directly - the ones the author controls.
434
- const userImported = new Set<string>()
435
- for (const [inputKey, input] of Object.entries(inputs)) {
436
- if (inputKey.startsWith("node:")) continue // a polyfill importing another builtin - not the cause
437
- for (const im of input.imports ?? []) {
438
- const builtin = nodeBuiltinOf(im)
439
- if (builtin !== undefined) userImported.add(builtin)
440
- }
441
- }
442
- // The entry inputs (route/user entrypoints) - the chain BFS starts here so the reported path begins
443
- // at the file the dev wrote an `import` in. Each output's `entryPoint` is one such input.
444
- const entryInputs = [
445
- ...new Set(
446
- Object.values(graph.chunks)
447
- .map((o) => o.entryPoint)
448
- .filter((e): e is string => e !== undefined && !e.startsWith("node:")),
449
- ),
450
- ]
451
- // The chain per builtin is independent of the chunk, so compute it once per builtin (memoized).
452
- const chainCache = new Map<string, readonly string[]>()
453
- const chainFor = (builtin: string): readonly string[] => {
454
- const cached = chainCache.get(builtin)
455
- if (cached !== undefined) return cached
456
- const chain = shortestBuiltinChain(inputs, entryInputs, builtin)
457
- chainCache.set(builtin, chain)
458
- return chain
459
- }
460
- // (2) Locate which emitted chunk each user-imported builtin reached, via the per-output `inputs`.
461
- const findings = new Map<string, NodeBuiltinFinding>()
462
- for (const [outPath, out] of Object.entries(graph.chunks)) {
463
- for (const inputKey of out.modules) {
464
- if (userImported.has(inputKey)) {
465
- const chunk = basename(outPath)
466
- findings.set(`${inputKey}\0${chunk}`, {
467
- builtin: inputKey,
468
- chunk,
469
- chain: chainFor(inputKey),
470
- })
471
- }
472
- }
473
- }
474
- return [...findings.values()].sort((a, b) =>
475
- a.builtin === b.builtin ? a.chunk.localeCompare(b.chunk) : a.builtin.localeCompare(b.builtin),
476
- )
477
- }
478
-
479
- // ---------------------------------------------------------------------------------------------------
480
- // `server-only` poison-import guard (§3.3/§5.1). The complement to the `.server` convention + the
481
- // node-builtin guard: a module of PURE server logic with NO `node:` import (a secret-bearing constant,
482
- // a server-only API call) that an author wants to FAIL LOUD if it reaches the client opts in with a
483
- // side-effect `import "@nifrajs/web/server-only"` (Next's `import "server-only"`). On the SERVER build
484
- // the marker is an empty no-op; the CLIENT build detects - via the SAME Bun metafile graph the
485
- // node-builtin guard walks - any module that imports the marker AND lands in a client chunk, and fails
486
- // the build with the import chain. Graph-based (never the emitted text), so it survives minification.
487
- // ---------------------------------------------------------------------------------------------------
488
-
489
- /** The marker specifier an author imports to opt a module into the client-leak guard. Matched on the
490
- * import edge's *as-written* `original` first (the robust signal: it's exactly what the author typed,
491
- * before Bun resolves it to `src/server-only.ts` / `dist/server-only.js`). */
492
- export const SERVER_ONLY_MARKER = "@nifrajs/web/server-only"
493
-
494
- /** True when an import edge is the `server-only` marker import. Reads the as-written `original` (the
495
- * specifier the author typed); falls back to the resolved `path`'s basename so a pre-resolved edge
496
- * (no `original`) - or a workspace-relative resolution - is still recognised. */
497
- const isServerOnlyMarkerImport = (im: BunMetafileImport): boolean => {
498
- if (im.original === SERVER_ONLY_MARKER) return true
499
- // Defensive fallback: an edge that lost its `original` but resolved to the marker module file. The
500
- // marker is the only `server-only.{ts,js}` under `@nifrajs/web`, so the basename is unambiguous.
501
- const path = im.path
502
- return path !== undefined && /(^|\/)server-only\.[cm]?[jt]s$/.test(path)
503
- }
504
-
505
- /** One `server-only`-module-in-the-client finding: the offending module (the as-written marker-import
506
- * chain's tail before the marker), the emitted chunk it landed in, and the shortest USER-module import
507
- * chain that pulled it there (entry → … → the server-only module). */
508
- export interface ServerOnlyFinding {
509
- /** The emitted client chunk the server-only module landed in (basename). */
510
- readonly chunk: string
511
- /** The shortest import path from a user entry to the server-only module, as display labels:
512
- * `[entryFile, ...as-written specifiers…, "<module> (marked server-only)"]`. Mirrors
513
- * {@link NodeBuiltinFinding.chain}; the tail names the marked module so the message reads
514
- * `routes/x.tsx → ../secrets.ts (marked server-only)`. */
515
- readonly chain: readonly string[]
516
- }
517
-
518
- /**
519
- * BFS the metafile import graph for the SHORTEST user-module path that reaches a module which imports
520
- * the `server-only` marker, returning it as display labels `[entryFile, …as-written specifiers…,
521
- * "<module> (marked server-only)"]`. Mirrors {@link shortestBuiltinChain}: the frontier starts at
522
- * every `entryInput` so the chain begins at the file the dev wrote an `import` in; traversal crosses
523
- * only NON-`node:` user edges (no cycles via `seen`); it stops at the first node whose import set
524
- * contains the marker (the marked module - the actionable tail), labelling that node by the as-written
525
- * specifier the previous hop used to reach it. Pure - operates on the graph, never the emitted text.
526
- */
527
- function shortestServerOnlyChain(
528
- inputs: Readonly<Record<string, { readonly imports?: readonly BunMetafileImport[] }>>,
529
- entryInputs: readonly string[],
530
- markedModule: string,
531
- resolveTarget: (im: BunMetafileImport) => string | undefined,
532
- ): string[] {
533
- // The label for the marked module's tail: its as-written specifier (filled when we cross the edge
534
- // that reaches it) suffixed with `(marked server-only)`; the entry case uses the entry key itself.
535
- const tail = (label: string): string => `${label} (marked server-only)`
536
- // An entry that is ITSELF the marked module - the chain is just that one node.
537
- if (entryInputs.includes(markedModule)) return [tail(markedModule)]
538
- const seen = new Set<string>(entryInputs)
539
- let frontier: Array<{ node: string; chain: string[] }> = entryInputs.map((node) => ({
540
- node,
541
- chain: [node],
542
- }))
543
- while (frontier.length > 0) {
544
- const next: Array<{ node: string; chain: string[] }> = []
545
- for (const { node, chain } of frontier) {
546
- for (const im of inputs[node]?.imports ?? []) {
547
- // Resolve the edge's `path` to the matching INPUT-GRAPH KEY - in a real build the edge `path`
548
- // is absolute while the input keys are cwd-relative, so a raw equality/lookup would miss every
549
- // multi-hop user edge (and the chain would degrade to just the tail). The resolver maps both.
550
- const target = resolveTarget(im)
551
- if (target === undefined || target.startsWith("node:")) continue
552
- // The marked module reached via THIS edge → the chain ends here (label it as the marked tail
553
- // using the as-written specifier the author wrote, falling back to the resolved key).
554
- if (target === markedModule) return [...chain, tail(im.original ?? target)]
555
- if (seen.has(target)) continue
556
- seen.add(target)
557
- next.push({ node: target, chain: [...chain, im.original ?? target] })
558
- }
559
- }
560
- frontier = next
561
- }
562
- return [tail(markedModule)] // unreachable from any entry (defensive; a flagged module is reachable)
563
- }
564
-
565
- /**
566
- * Build a resolver from an import EDGE to its INPUT-GRAPH KEY. Bun's metafile records edge `path`s as
567
- * ABSOLUTE paths but keys `inputs` by CWD-RELATIVE paths, so a raw `inputs[im.path]` lookup misses
568
- * every user edge in a real build. The resolver: (1) an exact key match (the synthetic-metafile / unit
569
- * case); else (2) the input key the absolute path ends with (`…/secrets.ts` → `packages/web/.../secrets.ts`).
570
- * The longest-suffix match is taken so a shorter key can't shadow a more specific one. Pure.
571
- */
572
- function inputKeyResolver(
573
- inputs: Readonly<Record<string, unknown>>,
574
- ): (im: BunMetafileImport) => string | undefined {
575
- const keys = Object.keys(inputs)
576
- return (im) => {
577
- const path = im.path
578
- if (path === undefined) return undefined
579
- if (inputs[path] !== undefined) return path // exact (synthetic keys, or already-relative paths)
580
- let best: string | undefined
581
- for (const key of keys) {
582
- // `/<key>` so a suffix match aligns on a path boundary (never a partial segment), and the longest
583
- // such key wins (the most specific file).
584
- if (path.endsWith(`/${key}`) && (best === undefined || key.length > best.length)) best = key
585
- }
586
- return best
587
- }
588
- }
589
-
590
- /**
591
- * Scan a build's metafile for any module that opts into the `server-only` marker (a side-effect
592
- * `import "@nifrajs/web/server-only"`) yet landed in a CLIENT output chunk, returning a sorted, deduped
593
- * list of {@link ServerOnlyFinding}s. Mirrors {@link detectNodeBuiltinsInClient}: it reads the SAME
594
- * graph facts - which inputs import the marker (the "marked" modules), which chunk each landed in (the
595
- * per-output `inputs`), and the shortest import chain from a user entry to it. The marker module ITSELF
596
- * (which imports nothing) is excluded - only the modules that *opt in* are flagged. Pure + exported for
597
- * unit testing. Empty ⇒ clean.
598
- */
599
- export function detectServerOnlyInClient(
600
- graph: ClientModuleGraph,
601
- ): ReadonlyArray<ServerOnlyFinding> {
602
- const inputs = graph.modules
603
- // (1) The modules that import the marker - the ones the author opted into the guard. The marker
604
- // module itself is skipped: it's the import TARGET, not an opt-in (it imports nothing of its own).
605
- const marked = new Set<string>()
606
- for (const [inputKey, input] of Object.entries(inputs)) {
607
- if (isServerOnlyMarkerModule(inputKey)) continue
608
- if ((input.imports ?? []).some(isServerOnlyMarkerImport)) marked.add(inputKey)
609
- }
610
- if (marked.size === 0) return []
611
- // The entry inputs - the chain BFS starts here, so the reported path begins at the file the dev
612
- // wrote an `import` in. Same derivation as the node-builtin guard.
613
- const entryInputs = [
614
- ...new Set(
615
- Object.values(graph.chunks)
616
- .map((o) => o.entryPoint)
617
- .filter((e): e is string => e !== undefined && !e.startsWith("node:")),
618
- ),
619
- ]
620
- const resolveTarget = inputKeyResolver(inputs)
621
- const chainCache = new Map<string, readonly string[]>()
622
- const chainFor = (markedModule: string): readonly string[] => {
623
- const cached = chainCache.get(markedModule)
624
- if (cached !== undefined) return cached
625
- const chain = shortestServerOnlyChain(inputs, entryInputs, markedModule, resolveTarget)
626
- chainCache.set(markedModule, chain)
627
- return chain
628
- }
629
- // (2) Locate which emitted chunk each marked module reached, via the per-output `inputs`.
630
- const findings = new Map<string, ServerOnlyFinding>()
631
- for (const [outPath, out] of Object.entries(graph.chunks)) {
632
- for (const inputKey of out.modules) {
633
- if (marked.has(inputKey)) {
634
- const chunk = basename(outPath)
635
- findings.set(`${inputKey}\0${chunk}`, { chunk, chain: chainFor(inputKey) })
636
- }
637
- }
638
- }
639
- return [...findings.values()].sort((a, b) => {
640
- const am = a.chain[a.chain.length - 1] ?? ""
641
- const bm = b.chain[b.chain.length - 1] ?? ""
642
- return am === bm ? a.chunk.localeCompare(b.chunk) : am.localeCompare(bm)
643
- })
644
- }
645
-
646
- /** True when an INPUT graph key is the marker module file itself (`…/server-only.{ts,js}` under web).
647
- * Excluded from the "marked" set - the marker is the import target, not an opt-in module. */
648
- const isServerOnlyMarkerModule = (inputKey: string): boolean =>
649
- /(^|\/)server-only\.[cm]?[jt]s$/.test(inputKey)
650
-
651
- // ---------------------------------------------------------------------------------------------------
652
- // Guard MESSAGES - one owner for both production pipelines. The Bun build (below) and the Vite/Rollup
653
- // leak-guard plugin (plugins/vite-leak-guard.ts) both call these, so a leak reads IDENTICALLY whichever
654
- // bundler produced it. A second bundler must not grow a second, subtly-different wording of a security
655
- // error; that is exactly the "mostly ported" outcome the neutral graph seam exists to prevent.
656
- // ---------------------------------------------------------------------------------------------------
657
-
658
- /** The build-failing message for `node:` builtins that reached the client bundle. `undefined` ⇒ clean. */
659
- export function formatNodeBuiltinLeak(
660
- findings: ReadonlyArray<NodeBuiltinFinding>,
661
- ): string | undefined {
662
- if (findings.length === 0) return undefined
663
- const lines = findings.map((f) =>
664
- f.chain.length > 1
665
- ? ` - ${f.builtin} reached the client bundle via ${f.chain.join(" → ")} (chunk: ${f.chunk})`
666
- : ` - ${f.builtin} reached the client bundle via ${f.chunk}`,
667
- )
668
- return (
669
- `[nifra/web] Node built-in(s) in the client bundle - move them behind a server-only path ` +
670
- `(a loader/action runs on the server; import the \`node:\` module there, not at a route's ` +
671
- `top level):\n${lines.join("\n")}`
672
- )
673
- }
674
-
675
- /** The build-failing message for `server-only`-marked modules that reached the client. `undefined` ⇒ clean. */
676
- export function formatServerOnlyLeak(
677
- findings: ReadonlyArray<ServerOnlyFinding>,
678
- ): string | undefined {
679
- if (findings.length === 0) return undefined
680
- const lines = findings.map((f) =>
681
- f.chain.length > 1
682
- ? ` - server-only module reached the client bundle via ${f.chain.join(" → ")} (chunk: ${f.chunk})`
683
- : ` - server-only module reached the client bundle via ${f.chunk}`,
684
- )
685
- return (
686
- `[nifra/web] server-only module(s) in the client bundle - a module marked ` +
687
- `\`import "${SERVER_ONLY_MARKER}"\` reached the browser. Move it behind a server-only path ` +
688
- `(reach it via a loader/action, or rename it \`*.server.ts\`), so its server logic never ships ` +
689
- `to the client:\n${lines.join("\n")}`
690
- )
691
- }
692
-
693
- const basename = (path: string): string => path.slice(path.lastIndexOf("/") + 1)
694
- /** `[name]` Bun derives for an entrypoint: basename without extension (`users/[id].tsx` → `[id]`). */
695
- const entryName = (file: string): string => {
696
- const base = basename(file)
697
- const dot = base.lastIndexOf(".")
698
- return dot === -1 ? base : base.slice(0, dot)
699
- }
700
-
701
- // ---------------------------------------------------------------------------------------------------
702
- // Bundle-size report (`nifra build --report`). The raw byte + gzip size of each emitted chunk lets a
703
- // dev catch a bundle regression at build time. Pure aggregation/formatting helpers (no fs, no Bun
704
- // build) so they're unit-testable in isolation; the orchestrator below wires them to real outputs.
705
- // ---------------------------------------------------------------------------------------------------
706
-
707
- /** One emitted chunk's measured size, in raw bytes + gzipped bytes (over-the-wire weight). */
708
- export interface ChunkSize {
709
- /** The emitted file's basename (e.g. `index-abc123.js`). */
710
- readonly name: string
711
- /** Raw byte length of the file. */
712
- readonly bytes: number
713
- /** Gzipped byte length (what the client actually downloads, modulo brotli). */
714
- readonly gzip: number
715
- }
716
-
717
- /** A whole build's size report - every chunk (largest first) + the totals. */
718
- export interface SizeReport {
719
- /** Per-chunk sizes, sorted biggest gzip first (the regression you want to see at the top). */
720
- readonly chunks: readonly ChunkSize[]
721
- /** Sum of every chunk's raw bytes. */
722
- readonly totalBytes: number
723
- /** Sum of every chunk's gzip bytes. */
724
- readonly totalGzip: number
725
- }
726
-
727
- /**
728
- * Aggregate a list of measured chunks into a {@link SizeReport}: sort biggest-gzip-first (ties broken
729
- * by raw bytes, then name for stable output) and sum the totals. Pure - the measurement (reading the
730
- * file + `Bun.gzipSync`) happens in the orchestrator; this is the deterministic, unit-testable core.
731
- */
732
- export function aggregateSizeReport(chunks: readonly ChunkSize[]): SizeReport {
733
- const sorted = [...chunks].sort(
734
- (a, b) => b.gzip - a.gzip || b.bytes - a.bytes || a.name.localeCompare(b.name),
735
- )
736
- let totalBytes = 0
737
- let totalGzip = 0
738
- for (const c of sorted) {
739
- totalBytes += c.bytes
740
- totalGzip += c.gzip
741
- }
742
- return { chunks: sorted, totalBytes, totalGzip }
743
- }
744
-
745
- /** Human-readable byte count: `B`/`KB`/`MB` with one decimal above 1 KB (e.g. `12.3 KB`). Pure. */
746
- export function formatBytes(bytes: number): string {
747
- if (bytes < 1024) return `${bytes} B`
748
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
749
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
750
- }
751
-
752
- /**
753
- * Render a {@link SizeReport} as a terse aligned table (biggest first) with a totals row - the text
754
- * `nifra build --report` prints. Pure (string in, string out) so the formatting is unit-testable.
755
- */
756
- export function renderSizeReport(report: SizeReport): string {
757
- const rows = report.chunks.map((c) => ({
758
- name: c.name,
759
- raw: formatBytes(c.bytes),
760
- gz: formatBytes(c.gzip),
761
- }))
762
- // Column widths from the header + every row + the totals label, so the table never clips a value.
763
- const nameW = Math.max(5, ...rows.map((r) => r.name.length), "Total".length)
764
- const rawW = Math.max(3, ...rows.map((r) => r.raw.length), formatBytes(report.totalBytes).length)
765
- const gzW = Math.max(4, ...rows.map((r) => r.gz.length), formatBytes(report.totalGzip).length)
766
- const padEnd = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - s.length))
767
- const padStart = (s: string, w: number): string => " ".repeat(Math.max(0, w - s.length)) + s
768
- const line = (name: string, raw: string, gz: string): string =>
769
- ` ${padEnd(name, nameW)} ${padStart(raw, rawW)} ${padStart(gz, gzW)}`
770
- const out = [
771
- line("Chunk", "Raw", "Gzip"),
772
- line("-".repeat(nameW), "-".repeat(rawW), "-".repeat(gzW)),
773
- ...rows.map((r) => line(r.name, r.raw, r.gz)),
774
- line("Total", formatBytes(report.totalBytes), formatBytes(report.totalGzip)),
775
- ]
776
- return out.join("\n")
777
- }
778
-
779
- // ---------------------------------------------------------------------------------------------------
780
- // Server-manifest drift detection (#7). `server-manifest.ts` is a committed generated file: it bakes
781
- // the route list + the client-entry hash for a disk-less worker (`generateServerManifest`). If `routes/`
782
- // changes but the manifest isn't regenerated, the worker serves a stale route table - a silent edge
783
- // break. These pure helpers diff the COMMITTED manifest source against the freshly-discovered routes so
784
- // `nifra check` (and `buildServer`) can fail with a named, actionable error before the drift ships.
785
- // ---------------------------------------------------------------------------------------------------
786
-
787
- /** A drift finding between a committed server-manifest and the live `routes/` tree. */
788
- export interface ManifestDrift {
789
- /** Route files present in `routes/` but ABSENT from the committed manifest (the manifest is stale -
790
- * the new route won't be served by the worker). */
791
- readonly missing: readonly string[]
792
- /** Route files the committed manifest imports that no longer exist in `routes/` (a deleted/renamed
793
- * route still wired into the worker - a build/runtime break). */
794
- readonly extra: readonly string[]
795
- }
796
-
797
- // The route-relative file keys the generated manifest's route map declares. Both shapes are matched by
798
- // their VALUE: eager ` "routes/x.tsx": m0,` and lazy ` "routes/x.tsx": () => import("./routes/x"),`.
799
- // The KEY (not the import specifier) is the route identity `discoverRoutes` produces, extension and all;
800
- // the import specifier is emitted extensionless (so a bare `tsc` compiles the manifest) and could not be
801
- // mapped back to the exact `.tsx`/`.ts` key. The baked `routeStyles` JSON is a single line, so its keys
802
- // are never at an indented line start and never match. `[ \t]+` (not `\s+`) so the `m` anchor stays on
803
- // the same line and one route-map entry cannot span two lines of source.
804
- const MANIFEST_ROUTE_ENTRY = /^[ \t]+(["'])([^"'\n]+)\1\s*:\s*(?:m\d+\b|\(\s*\)\s*=>\s*import\b)/gm
805
- // The lazy shape declares `const loaders`, the eager shape `const modules`. Anchored at a line start,
806
- // NOT `.includes("const loaders =")`: the real emit is `const loaders: Record<...> = {`, whose `:` type
807
- // annotation sits between the name and the `=`, so the ` =` substring never matched and every lazy
808
- // manifest was re-synced as eager (silently converting `import()` splitting into a single eager bundle).
809
- const MANIFEST_IS_LAZY = /^const loaders\b/m
810
- // The baked client-entry line: `export const clientEntry = "…"`.
811
- const MANIFEST_CLIENT_ENTRY = /export\s+const\s+clientEntry\s*=\s*["']([^"']+)["']/
812
-
813
- /**
814
- * Extract the route-relative file list a committed server-manifest declares, as the same
815
- * `routes/`-relative keys `discoverRoutes` produces (e.g. `docs/index.tsx`). Reads the route map's KEYS,
816
- * which carry the file extension and no directory prefix - exactly discovery's shape - so the result is
817
- * independent of the specifier prefix the manifest happened to import with. The `@nifrajs/web` import and
818
- * the baked `clientEntry`/`styles`/`routeStyles` lines carry no route-map entry and are ignored.
819
- *
820
- * `_routesPrefix` is accepted for call-site compatibility but no longer needed: the keys are already
821
- * prefix-free. Pure - operates on source text.
822
- */
823
- export function parseManifestRouteFiles(source: string, _routesPrefix?: string): string[] {
824
- const files = new Set<string>()
825
- for (const match of source.matchAll(MANIFEST_ROUTE_ENTRY)) {
826
- if (match[2] !== undefined) files.add(match[2])
827
- }
828
- return [...files].sort()
829
- }
830
-
831
- /** The baked `clientEntry` URL in a committed server-manifest, or `undefined` if absent. Pure. */
832
- export function parseManifestClientEntry(source: string): string | undefined {
833
- return MANIFEST_CLIENT_ENTRY.exec(source)?.[1]
834
- }
835
-
836
- // The baked asset lines `generateServerManifest` emits: `export const styles = […]` then
837
- // `export const routeStyles = {…}`, each a JSON literal running to the next `export const`. Extracted
838
- // with `indexOf` slicing rather than a lazy `[\s\S]*?` regex: the slice is multi-line by nature (a
839
- // formatter can wrap a long `routeStyles` map, and missing it would silently DROP every baked
840
- // stylesheet on re-sync), and a lazy scan re-walks the file per unterminated opener - quadratic.
841
- function bakedManifestLiteral(source: string, name: string): string | undefined {
842
- const opener = `export const ${name} = `
843
- const start = source.indexOf(opener)
844
- if (start === -1) return undefined
845
- const from = start + opener.length
846
- const end = source.indexOf("\nexport const ", from)
847
- return end === -1 ? undefined : source.slice(from, end)
848
- }
849
-
850
- /** Parse a baked JSON literal captured from a committed manifest, tolerating a formatter's TRAILING COMMAS
851
- * (biome/prettier add one when wrapping a multi-line array/object; strict `JSON.parse` would reject it).
852
- * Only a comma immediately before a closing `]`/`}` is stripped, so commas inside string values are safe. */
853
- function parseManifestLiteral(raw: string): unknown {
854
- return JSON.parse(raw.replace(/,(\s*[\]}])/g, "$1"))
855
- }
856
-
857
- /** The baked top-level `styles` array in a committed server-manifest (empty if absent/unparseable). Pure. */
858
- export function parseManifestStyles(source: string): string[] {
859
- const raw = bakedManifestLiteral(source, "styles")
860
- if (raw === undefined) return []
861
- try {
862
- const value = parseManifestLiteral(raw)
863
- return Array.isArray(value) ? (value as string[]) : []
864
- } catch {
865
- return []
866
- }
867
- }
868
-
869
- /** The baked per-route `routeStyles` map in a committed server-manifest (empty if absent/unparseable). Pure. */
870
- export function parseManifestRouteStyles(source: string): Record<string, string[]> {
871
- const raw = bakedManifestLiteral(source, "routeStyles")
872
- if (raw === undefined) return {}
873
- try {
874
- const value = parseManifestLiteral(raw)
875
- return value !== null && typeof value === "object" && !Array.isArray(value)
876
- ? (value as Record<string, string[]>)
877
- : {}
878
- } catch {
879
- return {}
880
- }
881
- }
882
-
883
340
  /**
884
341
  * Re-emit a committed server-manifest from a freshly-discovered route tree, PRESERVING its baked
885
342
  * client-asset references (`clientEntry` / `styles` / `routeStyles`) and its eager-vs-lazy shape. This is
@@ -909,49 +366,6 @@ export function resyncServerManifestSource(
909
366
  * supplies both file lists (the committed source is parsed via {@link parseManifestRouteFiles}; the
910
367
  * fresh list comes from `discoverRoutes`). Lists need not be pre-sorted; the result is sorted.
911
368
  */
912
- export function diffManifestRoutes(
913
- manifestFiles: readonly string[],
914
- discoveredFiles: readonly string[],
915
- ): ManifestDrift {
916
- const inManifest = new Set(manifestFiles)
917
- const inRoutes = new Set(discoveredFiles)
918
- const missing = discoveredFiles.filter((f) => !inManifest.has(f)).sort()
919
- const extra = manifestFiles.filter((f) => !inRoutes.has(f)).sort()
920
- return { missing, extra }
921
- }
922
-
923
- /** True when a drift report is clean (no missing + no extra routes). */
924
- export function isManifestInSync(drift: ManifestDrift): boolean {
925
- return drift.missing.length === 0 && drift.extra.length === 0
926
- }
927
-
928
- /**
929
- * Format a {@link ManifestDrift} as a named, actionable error message, or `undefined` when in sync.
930
- * Names the exact missing/extra routes + the one fix (regenerate the manifest by re-running the build).
931
- * `manifestPath` is shown for the dev to locate the stale file. Pure.
932
- */
933
- export function formatManifestDrift(
934
- drift: ManifestDrift,
935
- manifestPath = "server-manifest.ts",
936
- ): string | undefined {
937
- if (isManifestInSync(drift)) return undefined
938
- const lines: string[] = [
939
- `[nifra/web] server-manifest drift - \`${manifestPath}\` is out of sync with routes/.`,
940
- ]
941
- if (drift.missing.length > 0) {
942
- lines.push(
943
- ` Missing (in routes/, not in the manifest - these routes won't be served): ${drift.missing.join(", ")}`,
944
- )
945
- }
946
- if (drift.extra.length > 0) {
947
- lines.push(
948
- ` Extra (imported by the manifest, gone from routes/ - a dangling import): ${drift.extra.join(", ")}`,
949
- )
950
- }
951
- lines.push(" Fix: re-run the build to regenerate the server manifest, then commit it.")
952
- return lines.join("\n")
953
- }
954
-
955
369
  /**
956
370
  * Build the client bundle for a file-routed app. Writes the hashed assets + `manifest.json` to
957
371
  * `outDir` and returns the manifest. Throws (with the bundler logs) on build failure - never
@@ -963,6 +377,24 @@ export async function buildClient(options: BuildClientOptions): Promise<BuildMan
963
377
  await assertIdentityParity(root)
964
378
  const resolve = options.resolve ?? ((file: string) => `${routesDir}/${file}`)
965
379
  const publicPath = options.publicPath ?? "/assets/"
380
+
381
+ // outDir inside publicDir folds the build output back into the public copy on the next run (the
382
+ // bundle lands at public/assets/assets/*), and the dev/prod parity assert then throws on paths no
383
+ // one authored. Reject the overlap up front - no copy behavior is correct for this layout, and the
384
+ // parity symptom names neither option so the cause is unrecoverable from the message.
385
+ const publicRoot = options.publicDir === false ? undefined : (options.publicDir ?? "public")
386
+ if (publicRoot !== undefined) {
387
+ const publicResolved = resolvePath(publicRoot)
388
+ const outResolved = resolvePath(outDir)
389
+ if (outResolved === publicResolved || outResolved.startsWith(publicResolved + sep)) {
390
+ throw new Error(
391
+ `[nifra/web] outDir (${outResolved}) is inside publicDir (${publicResolved}). The public ` +
392
+ `copy would fold the build output back into itself. Move outDir outside publicDir, or ` +
393
+ `pass publicDir: false if the app has no hand-authored static files.`,
394
+ )
395
+ }
396
+ }
397
+
966
398
  mkdirSync(outDir, { recursive: true })
967
399
 
968
400
  const routeManifest = discoverRoutes(routesDir)
@@ -1143,7 +575,12 @@ export async function buildClient(options: BuildClientOptions): Promise<BuildMan
1143
575
  return [...new Set(urls)]
1144
576
  }
1145
577
  const routeStyles: Record<string, readonly string[]> = {}
1146
- if (css.length > 0 && cssByEntry.size > 0) {
578
+ // A compiler plugin may attach a global stylesheet to the generated bootstrap rather than to a
579
+ // route entry (StyleX's atomic CSS is one example). In that shape there is no useful per-route map:
580
+ // emitting `routeId: []` would suppress the aggregate `styles` fallback in `createWebApp` and render
581
+ // SSR pages unstyled. Keep routeStyles absent until at least one authored route entry owns CSS.
582
+ const routeCssEntries = [...cssByEntry.keys()].filter((entry) => entry !== resolvePath(entryFile))
583
+ if (css.length > 0 && routeCssEntries.length > 0) {
1147
584
  for (const route of routeManifest.routes) {
1148
585
  routeStyles[route.id] = stylesFor([
1149
586
  ...route.layoutIds.map((id) => routeManifest.layouts[id]?.file ?? ""),
@@ -1221,13 +658,6 @@ export interface BuildServerOptions {
1221
658
  }
1222
659
 
1223
660
  /** The built worker bundle - point your `wrangler.toml`'s `main` at `worker`. */
1224
- export interface ServerBuild {
1225
- /** Path to the bundled, self-contained worker entry. */
1226
- readonly worker: string
1227
- /** Paths of every emitted output (entry + any code-split chunks) - what to ship to the platform. */
1228
- readonly outputs: readonly string[]
1229
- }
1230
-
1231
661
  /**
1232
662
  * react-dom's `exports["./server"]` maps the `bun` condition to a Bun-API server build that crashes
1233
663
  * on workerd, and `Bun.build` always applies the `bun` condition (it wins over `workerd`/`edge-light`),
@@ -1488,15 +918,6 @@ export async function buildServer(options: BuildServerOptions): Promise<ServerBu
1488
918
  // …) - so we GENERATE it here (per target) instead of asking each app to ship five near-identical files.
1489
919
  // ===================================================================================================
1490
920
 
1491
- /** A deploy target `nifra build --target <t>` can emit. `static` is pure SSG (no server). */
1492
- export const BUILD_TARGETS = ["bun", "node", "deno", "cf-pages", "vercel", "static"] as const
1493
- export type BuildTarget = (typeof BUILD_TARGETS)[number]
1494
-
1495
- /** A type guard narrowing an arbitrary string to a {@link BuildTarget}. */
1496
- export function isBuildTarget(value: string): value is BuildTarget {
1497
- return (BUILD_TARGETS as readonly string[]).includes(value)
1498
- }
1499
-
1500
921
  /**
1501
922
  * Codegen the per-target **server entry** module (source text) for `buildServer` to bundle. It imports
1502
923
  * the app's `adapter` (from `framework.ts`), the optional `backend` (from `backend.ts`), and the
@@ -1684,15 +1105,6 @@ export function generateServerEntry(options: {
1684
1105
  return `${lines.join("\n")}\n`
1685
1106
  }
1686
1107
 
1687
- /** The Bun.build `target` each deploy target compiles its server with (mirrors `buildServer`'s docs). */
1688
- const SERVER_BUILD_TARGET: Record<Exclude<BuildTarget, "static">, "browser" | "node" | "bun"> = {
1689
- "cf-pages": "browser", // edge conditions (workerd/edge-light)
1690
- vercel: "browser", // Vercel Edge runtime
1691
- deno: "browser", // Deno's Web-standard runtime runs the edge bundle
1692
- node: "node", // node:* external; react-dom → its Node SSR build
1693
- bun: "bun", // Bun's flagship runtime
1694
- }
1695
-
1696
1108
  /** Measure each emitted output file's raw + gzip size. Reads the file off disk and gzips it with
1697
1109
  * `Bun.gzipSync` (the over-the-wire weight). Async only because it reads files; the aggregation is the
1698
1110
  * pure {@link aggregateSizeReport}. */
@@ -1784,41 +1196,6 @@ export interface BuildTargetResult {
1784
1196
  * Note: the heavier platform wrappers (`.vercel/output` v3 layout, wrangler ISR `find_additional_modules`)
1785
1197
  * remain app-owned scripts; this command targets the common single-bundle deploys. See the CLI docs.
1786
1198
  */
1787
- /**
1788
- * A build-tool STRATEGY for {@link buildTargetWith} - the two bundling steps, and nothing else. Everything
1789
- * around them (server-entry codegen, deploy assembly, prerender, size report) is bundler-agnostic and
1790
- * lives in `buildTargetWith`, so a second bundler (Vite) is this interface, not a second orchestrator.
1791
- *
1792
- * Plugin lists are `readonly unknown[]` because a Bun plugin and a Vite plugin are different types; each
1793
- * strategy casts to its own. `buildTargetWith` only forwards them.
1794
- */
1795
- export interface Bundler {
1796
- /** Build the client bundle → the shared {@link BuildManifest}. */
1797
- buildClient(input: {
1798
- readonly routesDir: string
1799
- readonly outDir: string
1800
- readonly clientModule: string
1801
- readonly plugins?: readonly unknown[]
1802
- readonly conditions?: readonly string[]
1803
- readonly define?: Readonly<Record<string, string>>
1804
- readonly publicDir?: string | false
1805
- readonly publicEnvPrefix?: string
1806
- /** Project root (Vite needs it; the Bun strategy ignores it). */
1807
- readonly root?: string
1808
- }): Promise<BuildManifest>
1809
- /** Build the server worker → the shared {@link ServerBuild}. */
1810
- buildServer(input: {
1811
- readonly routesDir: string
1812
- readonly serverEntry: string
1813
- readonly outDir: string
1814
- readonly clientEntry: string
1815
- readonly target: "browser" | "node" | "bun"
1816
- readonly plugins?: readonly unknown[]
1817
- readonly define?: Readonly<Record<string, string>>
1818
- readonly root?: string
1819
- }): Promise<ServerBuild>
1820
- }
1821
-
1822
1199
  /** The default (Bun) strategy - `buildClient`/`buildServer` from this module. */
1823
1200
  export const bunBundler: Bundler = {
1824
1201
  buildClient: (input) =>
@@ -1864,6 +1241,7 @@ export async function buildTargetWith(
1864
1241
  bundler: Bundler,
1865
1242
  ): Promise<BuildTargetResult> {
1866
1243
  const { routesDir, outDir, workDir } = options
1244
+ const targetPlan = planBuildTarget(target, outDir)
1867
1245
  const { rmSync } = await import("node:fs")
1868
1246
  rmSync(outDir, { recursive: true, force: true })
1869
1247
  rmSync(workDir, { recursive: true, force: true })
@@ -1894,7 +1272,7 @@ export async function buildTargetWith(
1894
1272
  writeFileSync(`${assetsDir}/manifest.json`, JSON.stringify(client, null, 2))
1895
1273
  }
1896
1274
 
1897
- if (target === "static") {
1275
+ if (targetPlan.kind === "static") {
1898
1276
  if (options.prerenderApp === undefined) {
1899
1277
  throw new Error(
1900
1278
  "[nifra/web] buildTarget(static) requires `prerenderApp` (a factory `(client) => createWebApp`)",
@@ -1926,7 +1304,7 @@ export async function buildTargetWith(
1926
1304
  target,
1927
1305
  outDir,
1928
1306
  client,
1929
- run: `static site → ${outDir} (serve the directory with any static host)`,
1307
+ run: targetPlan.run,
1930
1308
  size,
1931
1309
  }
1932
1310
  }
@@ -1946,13 +1324,12 @@ export async function buildTargetWith(
1946
1324
  ...(publicFiles.length > 0 ? { publicFiles } : {}),
1947
1325
  }),
1948
1326
  )
1949
- const serverTarget = SERVER_BUILD_TARGET[target]
1950
1327
  const { worker } = await bundler.buildServer({
1951
1328
  routesDir,
1952
1329
  serverEntry: serverEntryPath,
1953
1330
  outDir: `${workDir}/server`,
1954
1331
  clientEntry: client.entry,
1955
- target: serverTarget,
1332
+ target: targetPlan.serverTarget,
1956
1333
  ...(options.serverPlugins ? { plugins: options.serverPlugins } : {}),
1957
1334
  define: { "process.env.NODE_ENV": '"production"', ...(options.define ?? {}) },
1958
1335
  root: resolvePath(dirname(routesDir)),
@@ -1960,9 +1337,8 @@ export async function buildTargetWith(
1960
1337
 
1961
1338
  // (3) Assemble the deploy dir for the target.
1962
1339
  const { cpSync } = await import("node:fs")
1963
- let run: string
1964
- if (target === "cf-pages") {
1965
- cpSync(worker, `${outDir}/_worker.js`)
1340
+ if (targetPlan.target === "cf-pages") {
1341
+ cpSync(worker, `${outDir}/${targetPlan.outputFile}`)
1966
1342
  // The app's real patterns, so a directory is only collapsed into a glob once the route table
1967
1343
  // proves nothing can be served beneath it.
1968
1344
  const rules = cloudflareRouteRules(
@@ -1982,26 +1358,18 @@ export async function buildTargetWith(
1982
1358
  "worker via ASSETS instead of the CDN directly - correct, just one invocation each.",
1983
1359
  )
1984
1360
  }
1985
- run = `Cloudflare Pages → ${outDir} (deploy: wrangler pages deploy ${basename(outDir)})`
1986
- } else if (target === "vercel") {
1987
- cpSync(worker, `${outDir}/index.js`)
1988
- run = `Vercel edge function → ${outDir}/index.js (wrap with your vercel.json or Build Output API)`
1361
+ } else if (targetPlan.target === "vercel") {
1362
+ cpSync(worker, `${outDir}/${targetPlan.outputFile}`)
1989
1363
  } else {
1990
- // bun / node / deno: the runnable server bundle next to its /assets.
1991
- cpSync(worker, `${outDir}/server.js`)
1992
- const cmd =
1993
- target === "node"
1994
- ? `node ${basename(outDir)}/server.js`
1995
- : `${target} ${basename(outDir)}/server.js`
1996
- run = `${target} server → ${outDir} (run: ${cmd})`
1364
+ cpSync(worker, `${outDir}/${targetPlan.outputFile}`)
1997
1365
  }
1998
1366
  rmSync(workDir, { recursive: true, force: true })
1999
1367
 
2000
1368
  // Size report over the client assets + the server bundle (its parse cost matters on the edge).
2001
1369
  const clientPaths = client.assets.map((u) => assetUrlToPath(u, assetsDir))
2002
- const serverPath = `${outDir}/${target === "cf-pages" ? "_worker.js" : target === "vercel" ? "index.js" : "server.js"}`
1370
+ const serverPath = `${outDir}/${targetPlan.outputFile}`
2003
1371
  const size = aggregateSizeReport(await measureOutputs([...clientPaths, serverPath]))
2004
- return { target, outDir, client, run, size }
1372
+ return { target, outDir, client, run: targetPlan.run, size }
2005
1373
  }
2006
1374
 
2007
1375
  /** Map a client asset URL (`/assets/x-hash.js`) back to its on-disk path under `assetsDir`. The