@pithyjs/ssr 0.0.0-stage → 0.1.2-beta.9

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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/bin/pithy-ssg.mjs +23 -0
  4. package/dist/browser.d.ts +38 -0
  5. package/dist/browser.d.ts.map +1 -0
  6. package/dist/browser.js +40 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/build/cli-args.d.ts +104 -0
  9. package/dist/build/cli-args.d.ts.map +1 -0
  10. package/dist/build/cli-args.js +88 -0
  11. package/dist/build/cli-args.js.map +1 -0
  12. package/dist/build/cli-exit.d.ts +95 -0
  13. package/dist/build/cli-exit.d.ts.map +1 -0
  14. package/dist/build/cli-exit.js +237 -0
  15. package/dist/build/cli-exit.js.map +1 -0
  16. package/dist/build/cli.d.ts +11 -0
  17. package/dist/build/cli.d.ts.map +1 -0
  18. package/dist/build/cli.js +93 -0
  19. package/dist/build/cli.js.map +1 -0
  20. package/dist/build/collect-css.d.ts +168 -0
  21. package/dist/build/collect-css.d.ts.map +1 -0
  22. package/dist/build/collect-css.js +479 -0
  23. package/dist/build/collect-css.js.map +1 -0
  24. package/dist/build/css-live-props.d.ts +89 -0
  25. package/dist/build/css-live-props.d.ts.map +1 -0
  26. package/dist/build/css-live-props.js +704 -0
  27. package/dist/build/css-live-props.js.map +1 -0
  28. package/dist/build/css-purge.d.ts +153 -0
  29. package/dist/build/css-purge.d.ts.map +1 -0
  30. package/dist/build/css-purge.js +463 -0
  31. package/dist/build/css-purge.js.map +1 -0
  32. package/dist/build/index.d.ts +24 -0
  33. package/dist/build/index.d.ts.map +1 -0
  34. package/dist/build/index.js +31 -0
  35. package/dist/build/index.js.map +1 -0
  36. package/dist/build/not-found.d.ts +94 -0
  37. package/dist/build/not-found.d.ts.map +1 -0
  38. package/dist/build/not-found.js +99 -0
  39. package/dist/build/not-found.js.map +1 -0
  40. package/dist/build/relative-links.d.ts +31 -0
  41. package/dist/build/relative-links.d.ts.map +1 -0
  42. package/dist/build/relative-links.js +79 -0
  43. package/dist/build/relative-links.js.map +1 -0
  44. package/dist/build/shell-head.d.ts +68 -0
  45. package/dist/build/shell-head.d.ts.map +1 -0
  46. package/dist/build/shell-head.js +236 -0
  47. package/dist/build/shell-head.js.map +1 -0
  48. package/dist/build/sprite-ssg.d.ts +61 -0
  49. package/dist/build/sprite-ssg.d.ts.map +1 -0
  50. package/dist/build/sprite-ssg.js +114 -0
  51. package/dist/build/sprite-ssg.js.map +1 -0
  52. package/dist/build/ssg.d.ts +117 -0
  53. package/dist/build/ssg.d.ts.map +1 -0
  54. package/dist/build/ssg.js +404 -0
  55. package/dist/build/ssg.js.map +1 -0
  56. package/dist/build/vite-ssg.d.ts +396 -0
  57. package/dist/build/vite-ssg.d.ts.map +1 -0
  58. package/dist/build/vite-ssg.js +1130 -0
  59. package/dist/build/vite-ssg.js.map +1 -0
  60. package/dist/client/bootstrap.d.ts +51 -0
  61. package/dist/client/bootstrap.d.ts.map +1 -0
  62. package/dist/client/bootstrap.js +121 -0
  63. package/dist/client/bootstrap.js.map +1 -0
  64. package/dist/client/hydrate.d.ts +60 -0
  65. package/dist/client/hydrate.d.ts.map +1 -0
  66. package/dist/client/hydrate.js +168 -0
  67. package/dist/client/hydrate.js.map +1 -0
  68. package/dist/client/index.d.ts +21 -0
  69. package/dist/client/index.d.ts.map +1 -0
  70. package/dist/client/index.js +16 -0
  71. package/dist/client/index.js.map +1 -0
  72. package/dist/index.d.ts +32 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +31 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/server/app.d.ts +166 -0
  77. package/dist/server/app.d.ts.map +1 -0
  78. package/dist/server/app.js +200 -0
  79. package/dist/server/app.js.map +1 -0
  80. package/dist/server/context.d.ts +238 -0
  81. package/dist/server/context.d.ts.map +1 -0
  82. package/dist/server/context.js +371 -0
  83. package/dist/server/context.js.map +1 -0
  84. package/dist/server/environment.d.ts +88 -0
  85. package/dist/server/environment.d.ts.map +1 -0
  86. package/dist/server/environment.js +261 -0
  87. package/dist/server/environment.js.map +1 -0
  88. package/dist/server/html-shell.d.ts +41 -0
  89. package/dist/server/html-shell.d.ts.map +1 -0
  90. package/dist/server/html-shell.js +208 -0
  91. package/dist/server/html-shell.js.map +1 -0
  92. package/dist/server/index.d.ts +26 -0
  93. package/dist/server/index.d.ts.map +1 -0
  94. package/dist/server/index.js +37 -0
  95. package/dist/server/index.js.map +1 -0
  96. package/dist/server/layout-taint.d.ts +62 -0
  97. package/dist/server/layout-taint.d.ts.map +1 -0
  98. package/dist/server/layout-taint.js +313 -0
  99. package/dist/server/layout-taint.js.map +1 -0
  100. package/dist/server/loaders.d.ts +194 -0
  101. package/dist/server/loaders.d.ts.map +1 -0
  102. package/dist/server/loaders.js +479 -0
  103. package/dist/server/loaders.js.map +1 -0
  104. package/dist/server/render-route.d.ts +102 -0
  105. package/dist/server/render-route.d.ts.map +1 -0
  106. package/dist/server/render-route.js +182 -0
  107. package/dist/server/render-route.js.map +1 -0
  108. package/dist/server/render.d.ts +80 -0
  109. package/dist/server/render.d.ts.map +1 -0
  110. package/dist/server/render.js +256 -0
  111. package/dist/server/render.js.map +1 -0
  112. package/dist/server/router-adapter.d.ts +134 -0
  113. package/dist/server/router-adapter.d.ts.map +1 -0
  114. package/dist/server/router-adapter.js +225 -0
  115. package/dist/server/router-adapter.js.map +1 -0
  116. package/dist/server/serialization.d.ts +54 -0
  117. package/dist/server/serialization.d.ts.map +1 -0
  118. package/dist/server/serialization.js +287 -0
  119. package/dist/server/serialization.js.map +1 -0
  120. package/dist/server/ssr-worker.d.ts +18 -0
  121. package/dist/server/ssr-worker.d.ts.map +1 -0
  122. package/dist/server/ssr-worker.js +118 -0
  123. package/dist/server/ssr-worker.js.map +1 -0
  124. package/dist/server/utils.d.ts +11 -0
  125. package/dist/server/utils.d.ts.map +1 -0
  126. package/dist/server/utils.js +14 -0
  127. package/dist/server/utils.js.map +1 -0
  128. package/dist/server/worker-pool.d.ts +153 -0
  129. package/dist/server/worker-pool.d.ts.map +1 -0
  130. package/dist/server/worker-pool.js +451 -0
  131. package/dist/server/worker-pool.js.map +1 -0
  132. package/dist/server/worker-protocol.d.ts +61 -0
  133. package/dist/server/worker-protocol.d.ts.map +1 -0
  134. package/dist/server/worker-protocol.js +9 -0
  135. package/dist/server/worker-protocol.js.map +1 -0
  136. package/dist/shared/css-purge.d.ts +71 -0
  137. package/dist/shared/css-purge.d.ts.map +1 -0
  138. package/dist/shared/css-purge.js +177 -0
  139. package/dist/shared/css-purge.js.map +1 -0
  140. package/dist/shared/entry-path.d.ts +41 -0
  141. package/dist/shared/entry-path.d.ts.map +1 -0
  142. package/dist/shared/entry-path.js +87 -0
  143. package/dist/shared/entry-path.js.map +1 -0
  144. package/dist/shared/head.d.ts +87 -0
  145. package/dist/shared/head.d.ts.map +1 -0
  146. package/dist/shared/head.js +412 -0
  147. package/dist/shared/head.js.map +1 -0
  148. package/dist/shared/shell-helpers.d.ts +69 -0
  149. package/dist/shared/shell-helpers.d.ts.map +1 -0
  150. package/dist/shared/shell-helpers.js +160 -0
  151. package/dist/shared/shell-helpers.js.map +1 -0
  152. package/dist/shared/types.d.ts +332 -0
  153. package/dist/shared/types.d.ts.map +1 -0
  154. package/dist/shared/types.js +27 -0
  155. package/dist/shared/types.js.map +1 -0
  156. package/package.json +84 -3
@@ -0,0 +1,1130 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.build.vite-ssg",
4
+ "title": "Vite-integrated SSG Build Orchestrator",
5
+ "category": "feature",
6
+ "risk": "critical"
7
+ }
8
+ */
9
+ /**
10
+ * Vite-integrated SSG Build Orchestrator
11
+ *
12
+ * Provides `buildSSG()` — a single function that apps call to produce
13
+ * a fully portable static site with optional client-side hydration.
14
+ *
15
+ * The framework handles everything internally:
16
+ * - Loads pithy.config.ts for app configuration
17
+ * - Auto-discovers routes from the virtual route manifest
18
+ * - Renders the App shell and injects page content
19
+ * - Collects CSS from the Vite module graph, and in static mode purges the
20
+ * rules no rendered page uses (see `css-purge.ts`)
21
+ * - Registers the app's icon sprite and inlines the symbols each page uses
22
+ * (both modes — a prerendered document must stand on its own before any
23
+ * client JS runs)
24
+ * - Builds the client JS bundle for hydration mode
25
+ *
26
+ * Apps need zero entry files — just `pithy.config.ts` at the root.
27
+ *
28
+ * Usage:
29
+ * pithy-ssg — static HTML only (no JS)
30
+ * pithy-ssg --hydrate — static HTML + client JS
31
+ */
32
+ import * as fs from 'node:fs';
33
+ import * as path from 'node:path';
34
+ import { execFileSync } from 'node:child_process';
35
+ import { createRequire } from 'node:module';
36
+ import { inlineSpriteIntoHtml, } from '@pithyjs/shared/sprite';
37
+ import { collectCss } from './collect-css.js';
38
+ import { purgeCssForPages } from './css-purge.js';
39
+ import { purgeDeadCustomProps, collectHtmlSources, asSafelistArray, } from './css-live-props.js';
40
+ import { makeLinksRelative } from './relative-links.js';
41
+ import { NOT_FOUND_OUTPUT, hasRenderedText } from './not-found.js';
42
+ import { loadSpriteForSsg, clearSpriteForSsg } from './sprite-ssg.js';
43
+ import { readShellHead, resolvePageHead } from './shell-head.js';
44
+ import { injectIntoOutlet, pathToFilePath } from '../shared/shell-helpers.js';
45
+ import { entryCollisionKey } from '../shared/entry-path.js';
46
+ // Re-export pathToFilePath for test access (canonical definition in shell-helpers)
47
+ export { pathToFilePath } from '../shared/shell-helpers.js';
48
+ // Canonical in `./not-found.js`, so `generateStaticSite()` and `buildSSG()`
49
+ // cannot drift apart. Re-exported here because this is the module the build
50
+ // entry point and the tests address.
51
+ export { NOT_FOUND_OUTPUT, hasRenderedText };
52
+ /**
53
+ * Build the list of pages {@link buildSSG} renders and writes, in emission order.
54
+ *
55
+ * Extracted as a pure, side-effect-free seam because this is the exact wiring
56
+ * BUG-015 got wrong three times before it shipped: the `linkBase` a job carries,
57
+ * the `entry` filename it writes to, and whether a 404 job is appended at all
58
+ * are three independent decisions that nothing but a real `pithy-ssg --hydrate`
59
+ * run used to exercise. `findRouteByPattern` is injected rather than looked up
60
+ * here so a fake tree can stand in for the real route module in a unit test —
61
+ * no `ssrLoadModule`, no Vite server.
62
+ *
63
+ * The not-found job, when `notFoundRoute` is present, is always appended LAST.
64
+ * Its `entry` lands at the output root rather than nested like every ordinary
65
+ * page, so it must not shift collision-detection order for the paths ahead of
66
+ * it. No `notFoundRoute` (the app has no top-level catch-all) is a complete
67
+ * no-op — no job appended, nothing written, build still exits 0.
68
+ *
69
+ * @param staticPaths - Every literal path `collectStaticPaths()` found.
70
+ * @param notFoundRoute - The app's top-level catch-all, or null/undefined if
71
+ * it has none. See {@link findRootCatchAllRoute} in `ssg.ts`.
72
+ * @param findRouteByPattern - Resolves a route path to its `RouteNode`.
73
+ */
74
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"planRenderJobs","stability":"experimental","signature":"(staticPaths: string[], notFoundRoute: RouteNode | null | undefined, findRouteByPattern: (routePath: string) => RouteNode | null | undefined) => RenderJob[]"} */
75
+ export function planRenderJobs(staticPaths, notFoundRoute, findRouteByPattern) {
76
+ const renderJobs = staticPaths.map(routePath => ({
77
+ routePath,
78
+ routeNode: findRouteByPattern(routePath),
79
+ entry: pathToFilePath(routePath),
80
+ linkBase: routePath,
81
+ }));
82
+ if (notFoundRoute) {
83
+ renderJobs.push({
84
+ routePath: NOT_FOUND_OUTPUT.renderPath,
85
+ routeNode: notFoundRoute,
86
+ entry: NOT_FOUND_OUTPUT.entry,
87
+ linkBase: NOT_FOUND_OUTPUT.linkBase,
88
+ });
89
+ }
90
+ return renderJobs;
91
+ }
92
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"copyPublicAssets","stability":"experimental","signature":"(publicDir: string | false | undefined, outDir: string) => string[]"} */
93
+ /**
94
+ * Copy the app's public directory into the output.
95
+ *
96
+ * Hydrate output gets this for free — the client `vite build` writes into the
97
+ * same `outDir` and copies `publicDir` itself. Static mode runs no client
98
+ * build, so it emitted a document referencing a favicon it never shipped.
99
+ *
100
+ * Call before the pages are written: a page and a public file that resolve to
101
+ * the same path should end with the rendered page, not the raw asset.
102
+ *
103
+ * Walks with `statSync`, which follows symlinks as Vite's own `copyDir` does:
104
+ * a `Dirent` reports a symlink as neither file nor directory, so a linked
105
+ * asset would be dropped and its document reference would 404.
106
+ *
107
+ * Following them is what makes the two guards necessary. Directories are
108
+ * compared by real path, so an `outDir` inside `publicDir` is skipped whether
109
+ * it is reached directly or through a link, and the chain of real paths
110
+ * already open is carried down so a cycle — `public/loop -> public` — ends the
111
+ * branch instead of recursing until the filesystem refuses. The chain is per
112
+ * branch, not global: the same directory linked from two places is legitimate
113
+ * content and is copied to both.
114
+ *
115
+ * @param publicDir - Vite's resolved `publicDir` (`false` when disabled).
116
+ * @param outDir - Directory the build writes into.
117
+ * @returns Paths copied, relative to `publicDir`.
118
+ */
119
+ export function copyPublicAssets(publicDir, outDir) {
120
+ if (!publicDir || !fs.existsSync(publicDir))
121
+ return [];
122
+ const outReal = fs.existsSync(outDir)
123
+ ? fs.realpathSync(outDir)
124
+ : path.resolve(outDir);
125
+ const copied = [];
126
+ const walk = (dir, rel, open) => {
127
+ for (const name of fs.readdirSync(dir)) {
128
+ const from = path.resolve(dir, name);
129
+ const relPath = rel ? `${rel}/${name}` : name;
130
+ if (fs.statSync(from).isDirectory()) {
131
+ const real = fs.realpathSync(from);
132
+ if (real === outReal || open.has(real))
133
+ continue;
134
+ fs.mkdirSync(path.resolve(outDir, relPath), { recursive: true });
135
+ walk(from, relPath, new Set(open).add(real));
136
+ }
137
+ else {
138
+ const to = path.resolve(outDir, relPath);
139
+ fs.mkdirSync(path.dirname(to), { recursive: true });
140
+ fs.copyFileSync(from, to);
141
+ copied.push(relPath);
142
+ }
143
+ }
144
+ };
145
+ walk(publicDir, '', new Set([fs.realpathSync(publicDir)]));
146
+ return copied;
147
+ }
148
+ /**
149
+ * Keep the generated not-found document out of search indexes.
150
+ *
151
+ * `404.html` is a real, crawlable URL — a host that serves it for unmatched
152
+ * paths also serves it at `/404.html` — and it inherits the shell's `<title>`,
153
+ * so left alone it gets indexed as a duplicate of the home page.
154
+ *
155
+ * Only the generated 404 is touched (`linkBase === null` identifies it), and
156
+ * only when the page has said nothing about robots itself: an app that sets its
157
+ * own directive has made a decision, and this is not the place to overrule it.
158
+ *
159
+ * The title is deliberately left alone. `noindex` removes the search-result
160
+ * problem, and the tab title belongs to the catch-all page, which can set it.
161
+ */
162
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"withNotFoundRobots","stability":"internal","signature":"(head: HeadState, job: Pick<RenderJob, 'linkBase'>) => HeadState"} */
163
+ export function withNotFoundRobots(head, job) {
164
+ if (job.linkBase !== null)
165
+ return head;
166
+ if (head.meta.some(m => m.name?.toLowerCase() === 'robots'))
167
+ return head;
168
+ return {
169
+ ...head,
170
+ meta: [...head.meta, { name: 'robots', content: 'noindex' }],
171
+ };
172
+ }
173
+ /**
174
+ * Finalize a rendered page for the URL(s) it will be SERVED at.
175
+ *
176
+ * Takes the JOB, not a path, and reads `linkBase` from it. That is deliberate:
177
+ * an earlier shape took `{ path, linkPath }`, where `path` was never read and
178
+ * existed only to be swapped in — so the mutation this seam was added to close
179
+ * survived it, one token to the right, with 951 tests still green. Passing the
180
+ * already-tested `planRenderJobs` output leaves nothing to swap.
181
+ *
182
+ * `linkBase: null` means the document has no fixed depth — the 404, served at
183
+ * every unmatched URL — so relativisation is DISABLED for it regardless of the
184
+ * caller's `relativeLinks`. Relative URLs resolve against the request, not the
185
+ * file, so `assets/x.css` works for `/nope` and breaks for `/docs/whatever`.
186
+ */
187
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"finalizeForOutput","stability":"experimental","signature":"(html: string, job: Pick<RenderJob, 'linkBase'>, options: FinalizePageOptions) => FinalizePageResult"} */
188
+ export function finalizeForOutput(html, job, options) {
189
+ if (job.linkBase === null) {
190
+ return finalizePageHtml(html, '/', { ...options, relativeLinks: false });
191
+ }
192
+ return finalizePageHtml(html, job.linkBase, options);
193
+ }
194
+ /**
195
+ * Apply the last two transforms before a page is written to disk.
196
+ *
197
+ * Extracted from {@link buildSSG} as a pure seam, because the two properties
198
+ * that matter here are exactly the ones an end-to-end build cannot pin in CI:
199
+ *
200
+ * 1. **Ordering.** Sprite inlining must run *after* `makeLinksRelative`, since
201
+ * that is what the emitted file actually contains — `assets/icons-HASH.svg`,
202
+ * not `/assets/…`. Asserting against the pre-rebase URL is the false negative
203
+ * that once made this bug read as fixed.
204
+ * 2. **Hydrate output is inlined too.** It used to be gated off, on the theory
205
+ * that the client build emits the hashed sprite and `virtual:pithy-icons`
206
+ * re-registers it at runtime. Both halves are true of the *client bundle*
207
+ * and neither is true of the *prerendered document*. The app registers its
208
+ * sprite from module scope (`registerIconSprite(SPRITE_URL, …)`), and during
209
+ * SSG that module is loaded through the Vite **dev** server — so `SPRITE_URL`
210
+ * is the dev virtual path `/@pithy-icons-sprite.svg`, a route that exists
211
+ * only under `vite dev` and is never emitted by a build. Hydrate pages
212
+ * therefore shipped `<use href="@pithy-icons-sprite.svg#name">`: a 404 per
213
+ * icon, a blank brand mark until `hydrate()` discards the DOM and re-renders,
214
+ * and permanently blank with JS off.
215
+ *
216
+ * Inlining is the fix rather than rewriting the href at the hashed asset,
217
+ * because the icon has to paint *before* any request resolves — a prerendered
218
+ * document that needs a second round trip to show its logo has given up the
219
+ * thing prerendering is for. It is safe on the hydrate path: the symbol block
220
+ * is inserted at `<body>` level, outside the container `hydrate()` clears, and
221
+ * the client re-registers the real hashed `SPRITE_URL` on boot, so
222
+ * post-hydration `<use>` references resolve against the emitted asset.
223
+ *
224
+ * @param html - The assembled `htmlShell()` output for one route.
225
+ * @param routePath - Route the page was rendered for (e.g. `/about`).
226
+ * @param options - See {@link FinalizePageOptions}.
227
+ * @returns The final document plus any unresolved icon names.
228
+ */
229
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"finalizePageHtml","stability":"experimental","signature":"(html: string, routePath: string, options: FinalizePageOptions) => FinalizePageResult"} */
230
+ export function finalizePageHtml(html, routePath, options) {
231
+ const relativized = options.relativeLinks
232
+ ? makeLinksRelative(html, routePath, { assetsOnly: options.hydrate })
233
+ : html;
234
+ // Run the inliner even when the bundle carries no symbols for this page.
235
+ // Returning early on an empty bundle would suppress the *reporting* too, and
236
+ // a page whose `<use href>` references cannot be resolved is exactly the case
237
+ // worth hearing about: bailing silently is how a dangling reference reaches a
238
+ // published page looking like a successful build. `urlKeys` still gates it,
239
+ // so an app with no sprite at all does no work.
240
+ if (options.sprite.urlKeys.size === 0) {
241
+ return { html: relativized, missingIcons: [] };
242
+ }
243
+ const inlined = inlineSpriteIntoHtml(relativized, options.sprite);
244
+ return { html: inlined.html, missingIcons: inlined.missing };
245
+ }
246
+ // =============================================================================
247
+ // Client Bundle Build
248
+ // =============================================================================
249
+ /** Where the generated client config lives, relative to the app root. */
250
+ const CLIENT_CONFIG_DIRNAME = path.join('node_modules', '.pithy-ssg');
251
+ /**
252
+ * Create the throwaway directory the generated client config is written into.
253
+ *
254
+ * It has to live **inside the app**, not in `os.tmpdir()`. The config file
255
+ * `import`s from `'vite'`, and Node resolves a module's specifiers from that
256
+ * file's own directory, walking up for `node_modules` — the cwd of the process
257
+ * that spawned it is irrelevant. From the OS temp dir there is no
258
+ * `node_modules/vite` anywhere up the chain, so `--hydrate` died with
259
+ * `ERR_MODULE_NOT_FOUND` for every app (BUG-014). Vite compounds it by
260
+ * rewriting the config into a `.timestamp-*.mjs` sidecar in the same directory.
261
+ *
262
+ * `<root>/node_modules/.pithy-ssg/` reaches `<root>/node_modules` on the second
263
+ * hop of that walk, is already ignored by every VCS, and matches the `.vite` /
264
+ * `.cache` convention.
265
+ *
266
+ * @throws If the directory cannot be created — a silent fallback to a location
267
+ * outside the project would just resurrect the original failure.
268
+ */
269
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"createClientConfigDir","stability":"internal","signature":"(root: string) => string"} */
270
+ export function createClientConfigDir(root) {
271
+ const base = path.resolve(root, CLIENT_CONFIG_DIRNAME);
272
+ try {
273
+ fs.mkdirSync(base, { recursive: true });
274
+ return fs.mkdtempSync(path.join(base, 'build-'));
275
+ }
276
+ catch (error) {
277
+ throw new Error(`Could not create the pithy-ssg client config directory at ${base}.\n` +
278
+ ` The generated Vite config must live inside the project so Node can\n` +
279
+ ` resolve 'vite' from it, so this cannot fall back elsewhere.\n` +
280
+ ` Check that ${root}/node_modules/ exists and is writable — a\n` +
281
+ ` read-only checkout, a permission-denied mount, or a plain file\n` +
282
+ ` named node_modules all land here. If it is simply missing, run\n` +
283
+ ` your package manager's install in the app workspace.\n` +
284
+ ` Cause: ${error instanceof Error ? error.message : String(error)}`);
285
+ }
286
+ }
287
+ /**
288
+ * Remove a directory made by {@link createClientConfigDir}.
289
+ *
290
+ * Recursive so Vite's `client.config.mjs.timestamp-*.mjs` sidecars — written
291
+ * next to the config — go with it. Never throws: this runs in a `finally` and
292
+ * must not mask a build error.
293
+ *
294
+ * The shared `.pithy-ssg` PARENT is deliberately left in place. Removing it when
295
+ * it looked empty raced with a concurrently starting build: that build can be
296
+ * between its own `mkdirSync(base)` and `mkdtempSync(base/build-*)`, at which
297
+ * point the parent really is empty, and deleting it makes the other build fail
298
+ * with `ENOENT` — a cleanup step breaking an unrelated build. Retrying creation
299
+ * would narrow that window rather than close it, so the parent simply stays.
300
+ *
301
+ * What it costs is one empty directory under `node_modules/`, which is neither
302
+ * user-facing nor version-controlled. That is a better trade than a build that
303
+ * fails once in a while for a reason nobody can reproduce.
304
+ */
305
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"removeClientConfigDir","stability":"internal","signature":"(dir: string) => void"} */
306
+ export function removeClientConfigDir(dir) {
307
+ try {
308
+ fs.rmSync(dir, { recursive: true, force: true });
309
+ }
310
+ catch {
311
+ /* ignore — cleanup must never mask the build result */
312
+ }
313
+ }
314
+ /**
315
+ * Build client JS/CSS bundle using Vite.
316
+ *
317
+ * Loads the app's vite.config.ts and overrides build options.
318
+ * Uses subprocess to avoid sass resolution issues with programmatic API.
319
+ *
320
+ * Exported as a test seam. {@link createClientConfigDir} being correct is worth
321
+ * nothing if this function stops calling it — a suite that only exercises the
322
+ * helpers stays green through a revert to `mkdtemp(os.tmpdir())` right here,
323
+ * which is the exact regression this file's header exists to prevent. The one
324
+ * test that matters therefore drives `buildClientBundle` itself and inspects the
325
+ * `--config` path handed to the vite binary.
326
+ */
327
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"buildClientBundle","stability":"internal","signature":"(root: string, outDir: string, entryClient: string) => Promise<ClientBuildResult>"} */
328
+ export async function buildClientBundle(root, outDir, entryClient) {
329
+ console.log('Building client bundle...\n');
330
+ // Vite's JavaScript ENTRY, run with this same Node — not the `.bin` shim.
331
+ //
332
+ // The shim looked simpler and is a cross-platform trap: on Windows it is
333
+ // `vite.cmd`, and a batch file cannot be executed by `execFileSync` without
334
+ // `shell: true` — Node refuses outright since the CVE-2024-27980 fix. So the
335
+ // shim meant hydrate builds failed on Windows, while the alternative, turning
336
+ // `shell: true` back on, reintroduces exactly the path-with-spaces quoting
337
+ // problem that avoiding the shell was meant to solve.
338
+ //
339
+ // Running the entry with `process.execPath` needs neither: one code path, no
340
+ // shell, no quoting, identical on every platform. It also pins the Node
341
+ // already running this build rather than whatever a shim happens to resolve.
342
+ //
343
+ // Checked *before* the config directory is created, not after: this throw is
344
+ // between the write and the `try`/`finally` that cleans it up, so a missing
345
+ // install used to leave `node_modules/.pithy-ssg/build-XXXX/client.config.mjs`
346
+ // sitting in the user's project. Failing first costs one `existsSync`.
347
+ // Resolved through Node's OWN algorithm, not a hardcoded path.
348
+ //
349
+ // `<root>/node_modules/vite/bin/vite.js` only exists under a nested layout.
350
+ // With pnpm's `node-linker=hoisted`, `shamefully-hoist`, or any hoisting
351
+ // package manager, Vite is installed and importable while that exact directory
352
+ // is absent — so probing it with `existsSync` aborts the build telling the
353
+ // user to install something they already have. `createRequire` finds it
354
+ // wherever the layout put it, and reading `bin.vite` from the manifest also
355
+ // survives Vite renaming its own entry file.
356
+ let viteEntry;
357
+ try {
358
+ const requireFromApp = createRequire(path.join(root, 'noop.js'));
359
+ const pkgPath = requireFromApp.resolve('vite/package.json');
360
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
361
+ const binField = typeof pkg.bin === 'string' ? pkg.bin : (pkg.bin?.vite ?? 'bin/vite.js');
362
+ viteEntry = path.resolve(path.dirname(pkgPath), binField);
363
+ }
364
+ catch (cause) {
365
+ throw new Error(`Vite could not be resolved from ${root}.\n` +
366
+ ` Install it in the app workspace: pnpm add -D vite\n` +
367
+ ` Cause: ${cause instanceof Error ? cause.message : String(cause)}`);
368
+ }
369
+ if (!fs.existsSync(viteEntry)) {
370
+ throw new Error(`Vite resolved to ${viteEntry}, which does not exist.\n` +
371
+ ` This usually means a partial install — reinstall dependencies.`);
372
+ }
373
+ // Generate a temp config that extends the app's config with build overrides.
374
+ // It must sit inside the project — see createClientConfigDir().
375
+ const tempConfigDir = createClientConfigDir(root);
376
+ const tempConfigPath = path.resolve(tempConfigDir, 'client.config.mjs');
377
+ const entryClientAbs = path.resolve(root, entryClient).replace(/\\/g, '/');
378
+ const outDirAbs = outDir.replace(/\\/g, '/');
379
+ // Opened immediately after the directory exists, not just around the build:
380
+ // anything that throws in between would otherwise strand the generated
381
+ // config inside the user's project.
382
+ try {
383
+ // Write temp config that loads the app's config and overrides build section
384
+ fs.writeFileSync(tempConfigPath, `
385
+ import { loadConfigFromFile, mergeConfig } from 'vite';
386
+
387
+ const root = ${JSON.stringify(root.replace(/\\/g, '/'))};
388
+ const loaded = await loadConfigFromFile(
389
+ { command: 'build', mode: 'production' },
390
+ undefined,
391
+ root
392
+ );
393
+
394
+ const appConfig = loaded?.config ?? {};
395
+
396
+ // Take everything from app config, override build
397
+ export default mergeConfig(appConfig, {
398
+ build: {
399
+ outDir: ${JSON.stringify(outDirAbs)},
400
+ emptyOutDir: true,
401
+ manifest: true,
402
+ rollupOptions: {
403
+ input: ${JSON.stringify(entryClientAbs)},
404
+ },
405
+ },
406
+ });
407
+ `, 'utf-8');
408
+ execFileSync(process.execPath, [viteEntry, 'build', '--config', tempConfigPath.replace(/\\/g, '/')], {
409
+ cwd: root,
410
+ stdio: 'inherit',
411
+ });
412
+ }
413
+ finally {
414
+ // Clean up the generated config and Vite's .timestamp-*.mjs sidecars
415
+ removeClientConfigDir(tempConfigDir);
416
+ }
417
+ // Read Vite build manifest to locate entry chunk + CSS reliably,
418
+ // regardless of custom rollup output naming in the app's vite.config.
419
+ const manifestPath = path.resolve(outDir, '.vite', 'manifest.json');
420
+ if (!fs.existsSync(manifestPath)) {
421
+ throw new Error('Client build did not produce .vite/manifest.json.\n' +
422
+ ' Ensure build.manifest is not explicitly disabled in vite.config.');
423
+ }
424
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
425
+ // Vite manifest keys are typically root-relative posix paths.
426
+ // Try absolute path first, then relative, then fall back to isEntry lookup.
427
+ const relativeKey = entryClient.replace(/\\/g, '/');
428
+ const entry = manifest[entryClientAbs] ??
429
+ manifest[relativeKey] ??
430
+ Object.values(manifest).find(e => e.isEntry);
431
+ if (!entry) {
432
+ throw new Error(`Client build succeeded but entry not found in manifest.\n` +
433
+ ` Tried keys: "${entryClientAbs}", "${relativeKey}", isEntry fallback\n` +
434
+ ` Available keys: ${Object.keys(manifest).join(', ')}`);
435
+ }
436
+ const result = {};
437
+ result.script = entry.file;
438
+ const jsSize = (fs.statSync(path.resolve(outDir, entry.file)).size / 1024).toFixed(1);
439
+ console.log(`\n Client JS: ${result.script} (${jsSize} KB)`);
440
+ // EVERY stylesheet the client build emitted, not only the entry's.
441
+ //
442
+ // `cssCodeSplit` is Vite's default, so a route's CSS lands in its own chunk
443
+ // that `__vitePreload` fetches only AFTER the JS boots. A prerendered document
444
+ // linking just the entry's CSS therefore paints unstyled until hydration — and
445
+ // stays unstyled permanently with JS off, which is the exact reader the
446
+ // prerender exists for. Static mode never had this gap because `collectCss()`
447
+ // walked the whole module graph; switching an app to `--hydrate` silently lost
448
+ // it, with browser checks hiding it because the chunk lands in milliseconds
449
+ // when JS is on.
450
+ //
451
+ // Linking them all up front also matches what hydrate output does next: it is
452
+ // a client-routed app after first paint, so the router would fetch these on
453
+ // the first navigation regardless.
454
+ //
455
+ // Entry CSS first, so the base layer (design system, ui-kit, global styles)
456
+ // precedes route rules in the cascade rather than depending on chunk order.
457
+ const entryCss = entry.css ?? [];
458
+ const routeCss = Object.values(manifest)
459
+ .filter(chunk => chunk !== entry)
460
+ .flatMap(chunk => chunk.css ?? []);
461
+ const allCss = [...new Set([...entryCss, ...routeCss])];
462
+ if (allCss.length > 0) {
463
+ result.css = allCss;
464
+ for (const cssFile of allCss) {
465
+ const cssSize = (fs.statSync(path.resolve(outDir, cssFile)).size / 1024).toFixed(1);
466
+ console.log(` Client CSS: ${cssFile} (${cssSize} KB)`);
467
+ }
468
+ console.log('');
469
+ }
470
+ else {
471
+ console.log(' No extracted CSS file found\n');
472
+ }
473
+ return result;
474
+ }
475
+ const layoutDiagnostics = {
476
+ dropped: new Map(),
477
+ suspicious: new Map(),
478
+ };
479
+ function recordLayoutDiagnostics(routePath, diagnostics) {
480
+ if (!diagnostics)
481
+ return;
482
+ for (const declaration of diagnostics.droppedStyles) {
483
+ layoutDiagnostics.dropped.set(declaration, (layoutDiagnostics.dropped.get(declaration) ?? 0) + 1);
484
+ }
485
+ for (const declaration of diagnostics.suspiciousGeometry) {
486
+ const routes = layoutDiagnostics.suspicious.get(declaration) ?? [];
487
+ routes.push(routePath);
488
+ layoutDiagnostics.suspicious.set(declaration, routes);
489
+ }
490
+ }
491
+ /** Print the aggregated findings once, after every page has rendered. */
492
+ function reportLayoutDiagnostics() {
493
+ if (layoutDiagnostics.dropped.size > 0) {
494
+ const total = [...layoutDiagnostics.dropped.values()].reduce((a, b) => a + b, 0);
495
+ const names = [...layoutDiagnostics.dropped.keys()]
496
+ .map(d => d.split(':')[0]?.trim())
497
+ .filter((v, i, all) => v && all.indexOf(v) === i);
498
+ console.log(` Layout: dropped ${total} measurement-derived style declaration(s) ` +
499
+ `(${names.join(', ')}) — no layout engine during static render.`);
500
+ }
501
+ for (const [declaration, routes] of layoutDiagnostics.suspicious) {
502
+ console.warn(` WARN zero-valued geometry "${declaration}" on ${routes.length} page(s), ` +
503
+ `e.g. ${routes[0]}. Usually a measurement taken where there is no layout ` +
504
+ `engine; a genuine zero is possible.`);
505
+ }
506
+ layoutDiagnostics.dropped.clear();
507
+ layoutDiagnostics.suspicious.clear();
508
+ }
509
+ /**
510
+ * Run `body` with `globalThis.__PITHY_SSR__` set, restoring it exactly.
511
+ *
512
+ * ## Why the flag spans the whole export
513
+ *
514
+ * `setupEnvironment()` sets this flag around a single `renderToString()` call,
515
+ * which is the right scope for a live SSR server handling one request. It is
516
+ * the wrong scope here: every app module is **evaluated** outside that window —
517
+ * `ssrLoadModule(appPath)`, and each route's `imports.page()` in the render
518
+ * loop — and module evaluation is exactly where a module-level reference to a
519
+ * DOM global lives.
520
+ *
521
+ * `apps/playground` proved it. `class PithyDemoElement extends HTMLElement`
522
+ * evaluates its `extends` clause the instant the module loads, so an
523
+ * `isSSRMode()` guard on it was answering `false` during a static export and
524
+ * the route died with `ReferenceError: HTMLElement is not defined` (BUG-027).
525
+ * A guard that cannot be trusted at module scope is not a guard.
526
+ *
527
+ * ## Why the restore is exact, and why it is a `finally`
528
+ *
529
+ * `buildSSG()` is a library export a caller may invoke mid-process and carry on
530
+ * afterwards, so leaving the flag set would silently put the rest of that
531
+ * process into SSR mode. A flag that was **absent** is deleted rather than set
532
+ * to `false`, because `'__PITHY_SSR__' in globalThis` is observable and the two
533
+ * are not the same state. The `finally` means a throwing export restores it
534
+ * too — the case a `--allow-partial`-less build hits routinely.
535
+ *
536
+ * This nests correctly with `setupEnvironment()`: the inner one saves `true`
537
+ * and restores `true`.
538
+ *
539
+ * Safe for `--hydrate` even though the client bundle is built inside this
540
+ * window: `buildClientBundle()` runs Vite in a **separate process**
541
+ * (`execFileSync`), so a global in this one cannot reach it.
542
+ *
543
+ * @param body - The export to run. Its resolution or rejection is passed through.
544
+ * @returns Whatever `body` resolves to.
545
+ * @internal Exported for testing
546
+ */
547
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"withSsrExportFlag","stability":"experimental","signature":"<T>(body: () => Promise<T>) => Promise<T>"} */
548
+ export async function withSsrExportFlag(body) {
549
+ const host = globalThis;
550
+ // Depth-counted, and the snapshot is taken ONCE at depth 0 — on the host, not
551
+ // per call. Capturing `had`/`previous` per call looked equivalent and was not:
552
+ // for two INTERLEAVED exports, the second captures `true` (the first already
553
+ // set it), and whichever finishes last restores that mid-export snapshot, so
554
+ // the flag stays set forever. Strict nesting happened to work either way,
555
+ // which is exactly why the per-call version read as correct.
556
+ const depth = host.__PITHY_SSR_DEPTH__ ?? 0;
557
+ if (depth === 0) {
558
+ host.__PITHY_SSR_SAVED__ = {
559
+ had: '__PITHY_SSR__' in host,
560
+ previous: host.__PITHY_SSR__,
561
+ };
562
+ }
563
+ host.__PITHY_SSR_DEPTH__ = depth + 1;
564
+ host.__PITHY_SSR__ = true;
565
+ try {
566
+ return await body();
567
+ }
568
+ finally {
569
+ const remaining = host.__PITHY_SSR_DEPTH__ - 1;
570
+ if (remaining > 0) {
571
+ host.__PITHY_SSR_DEPTH__ = remaining;
572
+ }
573
+ else {
574
+ const saved = host.__PITHY_SSR_SAVED__;
575
+ delete host.__PITHY_SSR_DEPTH__;
576
+ delete host.__PITHY_SSR_SAVED__;
577
+ if (saved?.had)
578
+ host.__PITHY_SSR__ = saved.previous;
579
+ else
580
+ delete host.__PITHY_SSR__;
581
+ }
582
+ }
583
+ }
584
+ /**
585
+ * Build a static site with optional client-side hydration.
586
+ *
587
+ * Loads the app's configuration, routes, and App component directly via Vite.
588
+ * No entry-server.ts or entry-client.ts needed — the framework handles everything.
589
+ *
590
+ * A thin wrapper whose own job is to own the SSR-mode window: see
591
+ * {@link withSsrExportFlag} for why the flag has to span the whole export
592
+ * rather than each render, and why the restore is a `finally`.
593
+ *
594
+ * @param options - See {@link BuildSSGOptions}.
595
+ * @returns Rendered route paths, the not-found entry, per-route failures and
596
+ * export-wide {@link SSGBuildResult.buildFailures}.
597
+ *
598
+ * @example Static mode (no JS)
599
+ * ```ts
600
+ * await buildSSG();
601
+ * ```
602
+ *
603
+ * @example Hydrate mode (with JS)
604
+ * ```ts
605
+ * await buildSSG({ hydrate: true });
606
+ * ```
607
+ */
608
+ export async function buildSSG(options) {
609
+ return withSsrExportFlag(() => runBuildSSG(options));
610
+ }
611
+ /**
612
+ * What a bad option VALUE is, for a warning: `typeof` alone reports `object`
613
+ * for a `Set`, for `null` and for an array alike, which names none of them.
614
+ */
615
+ function describe(value) {
616
+ if (value === null)
617
+ return 'null';
618
+ if (Array.isArray(value))
619
+ return 'array';
620
+ if (typeof value !== 'object')
621
+ return typeof value;
622
+ return value.constructor?.name ?? 'object';
623
+ }
624
+ /**
625
+ * Every name the dead-declaration purge must keep regardless of liveness: the
626
+ * app's own `keepCustomProperties`, plus the design-system plugin's
627
+ * `channelVarSafelist` read off its published `api`.
628
+ *
629
+ * The plugin's entries are the ones its gate could not prove used — composed at
630
+ * runtime — so this pass cannot see a reference to them either, and without the
631
+ * forward it drops precisely what the author asked the gate to keep.
632
+ *
633
+ * Read rather than imported: `@pithyjs/ssr` does not depend on
634
+ * `@pithyjs/vite-plugin`. Shape-checked because the plugin may be absent, an
635
+ * older version, or a user's own plugin of the same name.
636
+ *
637
+ * Assembled here, not at the call site: `runBuildSSG` needs a live Vite server,
638
+ * so nothing reaches its body from a unit test and logic written inline there
639
+ * can be gutted without reddening anything.
640
+ */
641
+ /** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"livePropSafelist","stability":"experimental","signature":"(config: { keepCustomProperties?: unknown }, plugins?: readonly { name?: string; api?: unknown }[]) => readonly (string | RegExp)[]"} */
642
+ export function livePropSafelist(config, plugins = []) {
643
+ // Coerced before anything spreads it. The option is typed, but a JS config
644
+ // written without `defineConfig` is not: a bare string spread into single
645
+ // characters, and a number or object threw `is not iterable` here — outside
646
+ // the purge's own try/catch, so the whole build failed.
647
+ const own = asSafelistArray(config.keepCustomProperties);
648
+ const api = plugins.find(p => p?.name === 'pithy-design-system')?.api;
649
+ const channel = api?.channelVarSafelist;
650
+ if (channel !== undefined && !Array.isArray(channel)) {
651
+ console.warn(`[pithy:ssg] channelVarSafelist must be an ARRAY; got ` +
652
+ `${describe(channel)}. Its names are NOT protected from the ` +
653
+ `dead-declaration purge — list them in keepCustomProperties.`);
654
+ return own;
655
+ }
656
+ const usable = (channel ?? []).filter((e) => typeof e === 'string' || e instanceof RegExp);
657
+ if (usable.length !== (channel ?? []).length) {
658
+ const unusable = (channel ?? [])
659
+ .filter((e) => !(typeof e === 'string' || e instanceof RegExp))
660
+ .map(describe);
661
+ // The plugin treats the same input as fatal and keeps every channel
662
+ // variable, so staying silent here left the two passes disagreeing about
663
+ // one option with nothing said. This pass cannot mirror `keepAll` — it
664
+ // would have to guess which names are channel variables — so it says
665
+ // plainly which entries it could not use.
666
+ console.warn(`[pithy:ssg] channelVarSafelist: ignoring ` +
667
+ `${(channel ?? []).length - usable.length} entry/entries that are ` +
668
+ `neither a string nor a RegExp (${unusable.join(', ')}). The ` +
669
+ `design-system plugin keeps ALL ` +
670
+ `channel variables for this input; this pass keeps only the entries ` +
671
+ `it can read, so the two disagree until the option is fixed.`);
672
+ }
673
+ return [...own, ...usable];
674
+ }
675
+ async function runBuildSSG(options) {
676
+ const root = path.resolve(options?.root ?? process.cwd());
677
+ const outDir = path.resolve(root, options?.outDir ?? 'out');
678
+ // Prevent path traversal — outDir must resolve within root to avoid
679
+ // accidental deletion of directories outside the project
680
+ const relativeOutDir = path.relative(root, outDir);
681
+ if (!relativeOutDir ||
682
+ relativeOutDir === '.' ||
683
+ relativeOutDir.startsWith('..') ||
684
+ path.isAbsolute(relativeOutDir)) {
685
+ throw new Error(`outDir "${options?.outDir ?? ''}" resolves to the project root or outside it.\n` +
686
+ ` Resolved: ${outDir}\n` +
687
+ ` Root: ${root}\n` +
688
+ ` Use a subdirectory path (e.g. "out" or "dist/static").`);
689
+ }
690
+ const hydrate = options?.hydrate ?? false;
691
+ const configPath = options?.configPath ?? '/pithy.config';
692
+ const entryClient = options?.entryClient ?? 'src/main.ts';
693
+ const relativeLinks = options?.relativeLinks ?? true;
694
+ const mode = hydrate ? 'interactive (with hydration)' : 'static (no JS)';
695
+ console.log(`\n--- SSG Build: ${mode} ---\n`);
696
+ const startTime = performance.now();
697
+ // Phase 1: Build client bundle (only in hydrate mode)
698
+ let clientBuild = {};
699
+ if (hydrate) {
700
+ clientBuild = await buildClientBundle(root, outDir, entryClient);
701
+ }
702
+ else {
703
+ if (fs.existsSync(outDir)) {
704
+ fs.rmSync(outDir, { recursive: true, force: true });
705
+ }
706
+ fs.mkdirSync(outDir, { recursive: true });
707
+ }
708
+ // Phase 2: SSG render via Vite dev server
709
+ let createServer;
710
+ try {
711
+ ({ createServer } = await import('vite'));
712
+ }
713
+ catch {
714
+ throw new Error('Vite is required for SSG builds but could not be found.\n' +
715
+ 'Install it with: pnpm add -D vite');
716
+ }
717
+ const vite = await createServer({
718
+ root,
719
+ server: { middlewareMode: true },
720
+ appType: 'custom',
721
+ // Evaluate every @pithyjs module in Vite's runner. Externalized, a module
722
+ // loaded here and the same file imported by the app are two instances, so
723
+ // loadJITCompiler() below would load parse5 into the wrong one.
724
+ ssr: { noExternal: [/^@pithyjs\//] },
725
+ // Force legacy sass API to avoid sass-embedded's initAsyncCompiler issue
726
+ // in programmatic SSR context (same class of issue that buildClientBundle
727
+ // works around by using a subprocess).
728
+ css: {
729
+ preprocessorOptions: {
730
+ scss: { api: 'legacy' },
731
+ },
732
+ },
733
+ });
734
+ const rendered = [];
735
+ const failed = [];
736
+ const buildFailures = [];
737
+ try {
738
+ // Read the shell THROUGH Vite, not off disk: `%VITE_*%` placeholders and
739
+ // `transformIndexHtml` plugin hooks are what dev and `vite build` render,
740
+ // so parsing the raw file would carry a literal `%VITE_APP_TITLE%` into the
741
+ // artifact and diverge from every other way the app is built.
742
+ const shellHead = await readShellHead(root, {
743
+ transform: html => vite.transformIndexHtml('/', html),
744
+ });
745
+ if (options?.title)
746
+ shellHead.title = options.title;
747
+ // ── Load modules through Vite (resolves virtual modules, aliases, workspace deps) ──
748
+ console.log('Loading app configuration...');
749
+ const configMod = await vite.ssrLoadModule(configPath);
750
+ const config = configMod.default ?? {};
751
+ console.log('Loading route manifest...');
752
+ const routesMod = await vite.ssrLoadModule('virtual:pithy/routes.gen');
753
+ const routes = routesMod.routes;
754
+ // Normalize app path to root-absolute Vite module ID (e.g. /src/App)
755
+ const rawAppPath = config.app ?? '/src/App';
756
+ const appPath = rawAppPath.replace(/^\.\//, '/').replace(/^(?!\/)/, '/');
757
+ console.log(`Loading App component from ${appPath}...`);
758
+ const appMod = await vite.ssrLoadModule(appPath);
759
+ const App = appMod.default;
760
+ // Load framework modules through Vite too (avoids tsx resolution issues)
761
+ const ssrServerMod = await vite.ssrLoadModule('@pithyjs/ssr/server');
762
+ const renderToString = ssrServerMod.renderToString;
763
+ const htmlShellFn = ssrServerMod.htmlShell;
764
+ const ssrBuildMod = await vite.ssrLoadModule('@pithyjs/ssr/build');
765
+ const collectStaticPaths = ssrBuildMod.collectStaticPaths;
766
+ const findRootCatchAllRoute = ssrBuildMod.findRootCatchAllRoute;
767
+ const routerMod = await vite.ssrLoadModule('@pithyjs/router');
768
+ const findRouteByPattern = routerMod.findRouteByPattern;
769
+ // Load JIT compiler (parse5) for runtime html`` templates.
770
+ // Must run before any renderToString() call.
771
+ // Imported from compile/parseHtml directly (not the barrel) to avoid
772
+ // pulling parse5 into client bundles via the barrel re-export chain.
773
+ // Wrapped in try/catch: parse5 is an optional peer dep — AOT-only apps may not have it.
774
+ try {
775
+ const parseHtmlMod = await vite.ssrLoadModule('@pithyjs/core/compile/parseHtml');
776
+ await parseHtmlMod.loadJITCompiler();
777
+ }
778
+ catch (err) {
779
+ // parse5 not installed — fine for AOT-only apps where all templates are pre-compiled.
780
+ // Log so genuine load errors (corrupt install, version mismatch) aren't invisible.
781
+ console.warn('[pithy:ssg] Could not load JIT compiler (parse5). AOT-only apps can ignore this.', err);
782
+ }
783
+ // Initialize design system if configured — creates the ThemeManager
784
+ // singleton so components calling getThemeManager() don't crash.
785
+ if (config.designSystem) {
786
+ const dsMod = await vite.ssrLoadModule('@pithyjs/design-system');
787
+ dsMod.initDesignSystem(config.designSystem);
788
+ }
789
+ // Icon sprite. Both modes: the sprite URL these pages reference comes from
790
+ // the *dev* `virtual:pithy-icons` module this Vite server serves, so it is
791
+ // `/@pithy-icons-sprite.svg` — a dev-only route no build ever emits. Left
792
+ // alone it is a 404 per icon in the prerendered document, whichever mode
793
+ // produced it. See finalizePageHtml().
794
+ //
795
+ // Must run before the render loop — registration is what makes
796
+ // `resolveIconSvg()` emit a `<use>` instead of the missing-icon placeholder.
797
+ const sprite = await loadSpriteForSsg(vite);
798
+ if (sprite.symbols.size > 0) {
799
+ console.log(`Registered icon sprite (${sprite.symbols.size} symbols).`);
800
+ }
801
+ // ── Discover static routes ──
802
+ const staticPaths = await collectStaticPaths(routes);
803
+ console.log(`Found ${staticPaths.length} static paths to render.\n`);
804
+ // `collectStaticPaths()` excludes catch-all routes by design, and that stays
805
+ // — a catch-all has no literal path of its own to be written at. The
806
+ // site-wide not-found document is a separate emission: one extra render of
807
+ // the TOP-LEVEL catch-all, written to the output root as `404.html`.
808
+ // No top-level catch-all (or a nested-only one) is a complete no-op.
809
+ // See NOT_FOUND_OUTPUT and findRootCatchAllRoute().
810
+ const notFoundRoute = findRootCatchAllRoute(routes);
811
+ if (notFoundRoute) {
812
+ console.log(`Found a top-level catch-all (${notFoundRoute.pattern}); ` +
813
+ `it will also be written to ${NOT_FOUND_OUTPUT.entry}.\n`);
814
+ }
815
+ // Scripts and styles to inject (only in hydrate mode)
816
+ const scripts = clientBuild.script ? [`/${clientBuild.script}`] : [];
817
+ const styles = clientBuild.css ? clientBuild.css.map(f => `/${f}`) : [];
818
+ const outletId = config.outletId ?? 'outlet';
819
+ // ── Render all routes ──
820
+ console.log('Rendering routes...\n');
821
+ // The JOB itself, not fields copied out of it. Copying re-opened the exact
822
+ // seam `finalizeForOutput` was reshaped to close: with `entry` and
823
+ // `linkBase` restated here, `linkBase: linkBase ?? '/'` was a one-token
824
+ // edit that passed 977 tests, reverted the absolute-links fix AND the
825
+ // noindex fix, and printed an impossible `Rendered: 3/2`. There is nothing
826
+ // to restate now, so there is nothing to quietly restate wrongly.
827
+ const pageResults = [];
828
+ // The not-found job renders the catch-all's page at a synthetic URL and
829
+ // lands at the output root, so its entry and link depth differ from the
830
+ // usual `pathToFilePath(routePath)` / `routePath` pair. See planRenderJobs().
831
+ const renderJobs = planRenderJobs(staticPaths, notFoundRoute, routePath => findRouteByPattern(routes, routePath));
832
+ for (const job of renderJobs) {
833
+ const { routePath, routeNode, entry, linkBase } = job;
834
+ try {
835
+ if (!routeNode || !routeNode.imports.page) {
836
+ console.log(` SKIP ${routePath} -- no page component`);
837
+ continue;
838
+ }
839
+ const pageMod = await routeNode.imports.page();
840
+ const PageComponent = pageMod.default;
841
+ if (!PageComponent) {
842
+ console.log(` SKIP ${routePath} -- no default export`);
843
+ continue;
844
+ }
845
+ // Render the page component
846
+ const pageResult = await renderToString({
847
+ url: routePath,
848
+ App: PageComponent,
849
+ });
850
+ if (pageResult.redirectTo) {
851
+ console.log(` REDIRECT ${routePath} -> ${pageResult.redirectTo}`);
852
+ continue;
853
+ }
854
+ // Layout-taint findings are returned, not logged, because
855
+ // `renderToString()` also serves live SSR requests. The static export is
856
+ // the caller that wants them, and it aggregates rather than repeating
857
+ // the same declaration once per page.
858
+ recordLayoutDiagnostics(routePath, pageResult.layoutDiagnostics);
859
+ // Render App shell per route so layouts reading SSR context
860
+ // (active nav, canonical URL, route-based head) get correct values
861
+ const shellResult = await renderToString({ url: routePath, App });
862
+ const shellHtml = shellResult.html;
863
+ // Inject page HTML into the App shell's outlet
864
+ const finalHtml = injectIntoOutlet(shellHtml, pageResult.html, outletId, '[SSG]');
865
+ // A 404 whose page contributed NOTHING is worse than no 404 at all.
866
+ //
867
+ // `buildSSG` renders the catch-all's page standalone and injects the
868
+ // result into the shell's outlet, so a page that portals its content to
869
+ // `document.body` and returns an empty `el` loses that content here —
870
+ // apps/studio's not-found page does exactly this. What survives is the
871
+ // shell alone: measured, a 554 KB copy of the editor home screen with
872
+ // no "Page not found" anywhere in it, shipped as the site-wide 404 and
873
+ // fully dead without client JS.
874
+ //
875
+ // The test is TEXT, not an empty string: the page returns an inert
876
+ // `<div>` placeholder, so the injected html is `<div></div>` — not
877
+ // blank, and carrying nothing a reader could see. Refusing to write it
878
+ // leaves the host's own 404, which is honest.
879
+ if (linkBase === null && !hasRenderedText(pageResult.html)) {
880
+ console.warn(` SKIP ${routePath} -- catch-all page rendered no outlet content, ` +
881
+ `so ${entry} would ship the app shell alone. Not written. ` +
882
+ `A page that portals its content out of the outlet cannot be prerendered.`);
883
+ continue;
884
+ }
885
+ console.log(` OK(${pageResult.status}) ${routePath}`);
886
+ pageResults.push({
887
+ job,
888
+ html: finalHtml,
889
+ head: resolvePageHead(shellHead, shellResult.head, pageResult.head),
890
+ state: pageResult.state,
891
+ });
892
+ }
893
+ catch (err) {
894
+ const error = err instanceof Error ? err : new Error(String(err));
895
+ console.log(` FAIL ${routePath} -- ${error.message}`);
896
+ failed.push({ path: routePath, error });
897
+ }
898
+ }
899
+ // ── Collect CSS from module graph (static mode only) ──
900
+ let extraCss;
901
+ if (!hydrate) {
902
+ console.log('\nCollecting CSS from Vite module graph...');
903
+ // `entryClient` is passed even though SSR never executes it: its
904
+ // side-effect stylesheet imports are most of the app's CSS, and without
905
+ // warming it the module graph contains almost none of them.
906
+ const collectedCss = await collectCss(vite, entryClient, {
907
+ // The app's DECLARATION, not a probe for a registered plugin. Declared-
908
+ // but-unserved is exactly what BUG-028 was, and a registration probe
909
+ // answered "false" for it — the one case the gate exists to catch.
910
+ designSystemDeclared: Boolean(config.designSystem),
911
+ // Recorded, not thrown. Page writing has not started yet, so throwing
912
+ // would trade "a site with no design tokens" for "no site at all".
913
+ onDesignSystemFailure: error => {
914
+ buildFailures.push({ stage: 'design-system-css', error });
915
+ },
916
+ });
917
+ if (collectedCss.length > 0) {
918
+ console.log(` Collected ${collectedCss.length} chars of additional CSS`);
919
+ extraCss = collectedCss;
920
+ }
921
+ else {
922
+ console.log(' No additional CSS collected');
923
+ }
924
+ // ── Purge CSS the rendered pages never use ──
925
+ //
926
+ // Runs HERE, after the render loop, because the pages are what proves a
927
+ // rule unused. `pageResults` already carries the 404 — `planRenderJobs`
928
+ // appends its job to the same list every other page comes from — so the
929
+ // union covers it without a second parameter. It must: a rule only the
930
+ // 404 uses would otherwise be proven unused, dropped, and the 404 would
931
+ // fall back to the user agent's own defaults.
932
+ //
933
+ // Static mode only. Hydrate mode links `clientBuild.css` files and runs
934
+ // JS, so the rendered DOM is not the DOM the stylesheet has to cover.
935
+ if (extraCss) {
936
+ const before = Buffer.byteLength(extraCss, 'utf-8');
937
+ // `p.html` is the body FRAGMENT; `htmlShellFn` wraps it in
938
+ // `<html>`/`<body>`/`<div id="{appId}">` further down, carrying these
939
+ // attributes. An app that themes with
940
+ // `head({ bodyAttrs: { class: 'dark' } })` has a `.dark .x` rule that
941
+ // the fragment alone proves unused, and the same goes for any rule
942
+ // anchored on the app root.
943
+ extraCss = await purgeCssForPages(extraCss, pageResults.map(p => ({
944
+ html: p.html,
945
+ // The same `appId` handed to `htmlShellFn` below. It wraps the
946
+ // fragment in `<div id="{appId}">`, so without this every
947
+ // `#app ...` rule is proven unused and dropped.
948
+ appId: config.appId,
949
+ htmlAttrs: p.head.htmlAttrs,
950
+ bodyAttrs: p.head.bodyAttrs,
951
+ })));
952
+ // Second pass, over what the first one left. Ordering is load-bearing:
953
+ // a channel variable is dead only once the unused utility rule that
954
+ // referenced it has gone, so running this first would keep the whole
955
+ // family.
956
+ //
957
+ // The attribute values join the page HTML, and the asymmetry with the
958
+ // rule purge above is the reason: a RULE in `extraCss` that no element
959
+ // matches really is unused, but a DECLARATION can be consumed from
960
+ // anywhere in the document — `bodyAttrs: { style: 'color:var(--x)' }`
961
+ // included. Anything consuming it from OUTSIDE the document, such as an
962
+ // author-supplied `<link rel="stylesheet">`, needs
963
+ // `keepCustomProperties` in `pithy.config.ts`.
964
+ extraCss = purgeDeadCustomProps(extraCss, {
965
+ safelist: livePropSafelist(config, vite.config.plugins),
966
+ htmlSources: collectHtmlSources(pageResults.map(p => ({
967
+ html: p.html,
968
+ head: p.head,
969
+ })), sprite),
970
+ });
971
+ const after = Buffer.byteLength(extraCss, 'utf-8');
972
+ if (after < before) {
973
+ console.log(` Purged unused CSS: ${(before / 1024).toFixed(1)} KB -> ` +
974
+ `${(after / 1024).toFixed(1)} KB`);
975
+ }
976
+ }
977
+ }
978
+ // ── Write output files ──
979
+ if (!hydrate) {
980
+ // `build.copyPublicDir: false` is an explicit opt-out that `vite build`
981
+ // honours, so hydrate output omits these. Copying anyway would ship
982
+ // assets the caller excluded, in the one mode they cannot check.
983
+ const copied = vite.config.build.copyPublicDir
984
+ ? copyPublicAssets(vite.config.publicDir, outDir)
985
+ : [];
986
+ if (copied.length > 0) {
987
+ console.log(`\n Copied ${copied.length} public asset(s) to the output.`);
988
+ }
989
+ }
990
+ // Asked of `publicDir` itself, not of the copied output: in hydrate mode
991
+ // Vite's own client build does the copying, so nothing here would see it.
992
+ const hasAuthoredNotFound = vite.config.build.copyPublicDir &&
993
+ typeof vite.config.publicDir === 'string' &&
994
+ fs.existsSync(path.join(vite.config.publicDir, NOT_FOUND_OUTPUT.entry));
995
+ let notFoundEntry = null;
996
+ console.log('\nWriting portable static files...');
997
+ const entryOwners = new Map();
998
+ for (const page of pageResults) {
999
+ const { html, head, state } = page;
1000
+ const { routePath, entry } = page.job;
1001
+ const fullHtml = htmlShellFn({
1002
+ html,
1003
+ head: withNotFoundRobots(head, page.job),
1004
+ state: hydrate ? state : undefined,
1005
+ scripts,
1006
+ styles,
1007
+ criticalCss: extraCss,
1008
+ appId: config.appId,
1009
+ });
1010
+ // Reject traversal segments — consistent with ssg.ts renderPage()
1011
+ const segments = routePath.replace(/^\//, '').split('/');
1012
+ if (segments.some(s => s === '..' || s === '.')) {
1013
+ failed.push({
1014
+ path: routePath,
1015
+ error: new Error(`Path traversal detected: "${routePath}" contains ".." or "." segments`),
1016
+ });
1017
+ continue;
1018
+ }
1019
+ const { html: finalOutput, missingIcons } = finalizeForOutput(fullHtml, page.job, { relativeLinks, hydrate, sprite });
1020
+ if (missingIcons.length > 0) {
1021
+ console.warn(` WARN ${routePath} -- ${missingIcons.length} icon(s) referenced but absent ` +
1022
+ `from the sprite (${missingIcons.join(', ')}); they will render empty.`);
1023
+ }
1024
+ // `/About` and `/about` are two names on ext4 and one file on APFS and
1025
+ // NTFS — writing both silently ships whichever rendered last.
1026
+ // A hand-authored `public/404.html` is an explicit not-found document;
1027
+ // the generated one is inferred from the presence of a catch-all route.
1028
+ // Explicit wins, and this is the only way to opt out of generation.
1029
+ //
1030
+ // Scoped to the 404 on purpose: every other entry comes from a route the
1031
+ // author actually created, and page-wins is the long-standing behaviour
1032
+ // there. Only the 404 is emitted without anyone asking for it, so only
1033
+ // the 404 needs a way to say no.
1034
+ if (entry === NOT_FOUND_OUTPUT.entry && hasAuthoredNotFound) {
1035
+ console.warn(` SKIP ${routePath} -- public/${NOT_FOUND_OUTPUT.entry} exists, so the ` +
1036
+ `hand-authored document is kept and the generated one discarded.`);
1037
+ continue;
1038
+ }
1039
+ const owner = entryOwners.get(entryCollisionKey(entry));
1040
+ if (owner !== undefined) {
1041
+ const detail = owner.entry === entry
1042
+ ? `both write to "${entry}"`
1043
+ : `write to "${owner.entry}" and "${entry}", which are one file on a filesystem that ignores case or Unicode normalization`;
1044
+ const error = new Error(`Output collision: paths "${owner.path}" and "${routePath}" ${detail}`);
1045
+ console.log(` FAIL ${routePath} -- ${error.message}`);
1046
+ failed.push({ path: routePath, error });
1047
+ continue;
1048
+ }
1049
+ entryOwners.set(entryCollisionKey(entry), { path: routePath, entry });
1050
+ const absFile = path.resolve(outDir, entry);
1051
+ fs.mkdirSync(path.dirname(absFile), { recursive: true });
1052
+ fs.writeFileSync(absFile, finalOutput, 'utf-8');
1053
+ const sizeKb = (Buffer.byteLength(finalOutput, 'utf-8') / 1024).toFixed(1);
1054
+ console.log(` ${routePath} -> ${entry} (${sizeKb} KB)`);
1055
+ // The not-found document is reported separately: it has no route path,
1056
+ // so listing it as `/404` invents a route, and an app that really does
1057
+ // define `/404` would appear twice with no way to tell the entries apart.
1058
+ if (page.job.linkBase === null) {
1059
+ notFoundEntry = entry;
1060
+ }
1061
+ else {
1062
+ rendered.push(routePath);
1063
+ }
1064
+ }
1065
+ const totalTime = performance.now() - startTime;
1066
+ const totalTimeSec = (totalTime / 1000).toFixed(2);
1067
+ console.log(`\n--- Results ---`);
1068
+ console.log(` Mode: ${mode}`);
1069
+ const pageJobCount = renderJobs.filter(j => j.linkBase !== null).length;
1070
+ // `rendered` holds route paths and `pageJobCount` counts the jobs that have
1071
+ // one, so the first can never exceed the second. It did: a one-token edit
1072
+ // that treated the 404 job as an ordinary page printed `Rendered: 3/2` and
1073
+ // nothing objected. An impossible ratio is a wiring bug, and the output is
1074
+ // already wrong by the time it prints — so say so rather than print it.
1075
+ if (rendered.length > pageJobCount) {
1076
+ throw new Error(`SSG internal invariant violated: wrote ${rendered.length} page(s) from ` +
1077
+ `${pageJobCount} page job(s). The not-found job is being counted as an ` +
1078
+ `ordinary page, so its entry and link base are wrong too.`);
1079
+ }
1080
+ console.log(` Rendered: ${rendered.length}/${pageJobCount}`);
1081
+ if (notFoundEntry) {
1082
+ console.log(` Not found: ${notFoundEntry}`);
1083
+ }
1084
+ reportLayoutDiagnostics();
1085
+ console.log(` Failed: ${failed.length}`);
1086
+ console.log(` Time: ${totalTimeSec}s`);
1087
+ console.log(` Output: ${outDir}`);
1088
+ if (clientBuild.script) {
1089
+ console.log(` Client: ${clientBuild.script}`);
1090
+ }
1091
+ console.log(`\n Open in browser: ${path.resolve(outDir, 'index.html')}`);
1092
+ console.log(` Or serve: npx serve ${path.relative(root, outDir)} -p 3939\n`);
1093
+ if (failed.length > 0) {
1094
+ console.log('Failed routes:');
1095
+ for (const f of failed) {
1096
+ console.log(` ${f.path}: ${f.error.message}`);
1097
+ }
1098
+ // No `--allow-partial` hint here. `buildSSG()` is a library API and
1099
+ // cannot see whether the flag was passed, so an unconditional hint
1100
+ // printed even when it HAD been — directly contradicting the note
1101
+ // `endCliProcess()` prints two lines later. The CLI knows; it tells.
1102
+ console.log('');
1103
+ }
1104
+ if (buildFailures.length > 0) {
1105
+ // Printed after the route list so it is the last thing on screen: it
1106
+ // applies to every page above it, and --allow-partial does not waive it.
1107
+ console.error('Build failures (not waived by --allow-partial):');
1108
+ for (const f of buildFailures) {
1109
+ console.error(` ${f.stage}: ${f.error.message}`);
1110
+ }
1111
+ console.error('');
1112
+ }
1113
+ return {
1114
+ rendered,
1115
+ notFound: notFoundEntry,
1116
+ failed,
1117
+ buildFailures,
1118
+ totalTime,
1119
+ };
1120
+ }
1121
+ finally {
1122
+ // The icon registry is module-singleton state the UI Kit documents as
1123
+ // client-only. A build-time SSG run is a legitimate exception, but leaving
1124
+ // it populated would leak into anything sharing the process — a watch-mode
1125
+ // rebuild, a test run, a second buildSSG() for a different app.
1126
+ await clearSpriteForSsg(vite).catch(() => { });
1127
+ await vite.close();
1128
+ }
1129
+ }
1130
+ //# sourceMappingURL=vite-ssg.js.map