@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,404 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.build.ssg",
4
+ "title": "Static Site Generation Pipeline",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - Static Site Generation (SSG)
10
+ *
11
+ * Pre-renders routes to static HTML files at build time.
12
+ * Uses renderToString + htmlShell to generate complete HTML documents.
13
+ */
14
+ import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
16
+ import { renderToString } from '../server/render.js';
17
+ import { htmlShell } from '../server/html-shell.js';
18
+ import { pathToFilePath } from '../shared/shell-helpers.js';
19
+ import { entryCollisionKey } from '../shared/entry-path.js';
20
+ import { NOT_FOUND_OUTPUT } from './not-found.js';
21
+ // =============================================================================
22
+ // Path Collection
23
+ // =============================================================================
24
+ /** @codexApi {"parent":"pithy.ssr.build.ssg","name":"collectStaticPaths","stability":"internal","signature":"(routes: RouteNode[]) => Promise<string[]>"} */
25
+ /**
26
+ * Collect paths from static routes for pre-rendering.
27
+ *
28
+ * Walks the route tree and collects paths for routes that:
29
+ * - Are not dynamic (no :param segments)
30
+ * - Are not catch-all (no * or [...] segments)
31
+ * - Have a page import
32
+ * - Do not have prerender=false in their config
33
+ *
34
+ * @param routes - Route node tree
35
+ * @returns Array of static paths to pre-render
36
+ */
37
+ export async function collectStaticPaths(routes) {
38
+ const paths = [];
39
+ const seen = new Set();
40
+ async function walk(nodes) {
41
+ for (const node of nodes) {
42
+ // Only collect routes that have a page component
43
+ if (node.imports.page) {
44
+ // Check if route should be pre-rendered
45
+ const shouldPrerender = await shouldPrerenderRoute(node);
46
+ if (shouldPrerender && !seen.has(node.pattern)) {
47
+ seen.add(node.pattern);
48
+ paths.push(node.pattern);
49
+ }
50
+ }
51
+ // Recurse into children
52
+ if (node.children.length > 0) {
53
+ await walk(node.children);
54
+ }
55
+ }
56
+ }
57
+ await walk(routes);
58
+ return paths;
59
+ }
60
+ /**
61
+ * Determine if a route should be pre-rendered
62
+ *
63
+ * Rules:
64
+ * - Static routes (no dynamic params, no catch-all): yes by default
65
+ * - Dynamic / catch-all routes: no (never auto-collected here)
66
+ * - Config with prerender=false: no (override for static)
67
+ * - Config with prerender=true: yes for static routes; for dynamic / catch-all routes
68
+ * it only signals intent and still requires explicit paths elsewhere
69
+ *
70
+ * **The catch-all exclusion is deliberate and stays.** The site-wide `404.html`
71
+ * (see {@link findRootCatchAllRoute}) is emitted by a *separate* step, not by
72
+ * widening this predicate. Letting a catch-all through here would also emit it
73
+ * at its own literal pattern path — the `/*` route would land in a directory
74
+ * literally named `*`, which no host will ever request.
75
+ */
76
+ async function shouldPrerenderRoute(node) {
77
+ const isStatic = node.metadata.isStatic &&
78
+ !node.metadata.isDynamic &&
79
+ !node.metadata.isCatchAll;
80
+ // Check config for explicit prerender setting
81
+ if (node.imports.config) {
82
+ try {
83
+ const config = await node.imports.config();
84
+ if (typeof config.prerender === 'boolean') {
85
+ // For dynamic routes, prerender=true only signals intent
86
+ // The route still needs explicit paths (can't auto-generate param values)
87
+ if (!isStatic && config.prerender) {
88
+ return false; // Dynamic routes can't be auto-collected
89
+ }
90
+ return config.prerender;
91
+ }
92
+ }
93
+ catch {
94
+ // Config import failed, use default behavior
95
+ }
96
+ }
97
+ return isStatic;
98
+ }
99
+ // =============================================================================
100
+ // Not-found (404) discovery
101
+ // =============================================================================
102
+ /**
103
+ * The only route pattern that can back a site-wide not-found document.
104
+ *
105
+ * The route scanner turns a `src/routes/[...slug]/` folder into the single
106
+ * wildcard segment `*`, so a ROOT catch-all's pattern is `/*` — never
107
+ * `/[...slug]`. Local to this module: `buildSSG()` finds its catch-all through
108
+ * `findRootCatchAllRoute()` below rather than by matching the pattern itself.
109
+ */
110
+ const ROOT_CATCH_ALL_PATTERN = '/*';
111
+ /** @codexApi {"parent":"pithy.ssr.build.ssg","name":"findRootCatchAllRoute","stability":"internal","signature":"(routes: RouteNode[]) => RouteNode | undefined"} */
112
+ /**
113
+ * Find the top-level catch-all route that backs the site-wide `404.html`.
114
+ *
115
+ * Netlify, Vercel, GitHub Pages and Cloudflare Pages serve a root `404.html`
116
+ * for an unmatched path with no per-host configuration; S3 needs
117
+ * `ErrorDocument: 404.html` on its static-website endpoint. So rendering
118
+ * the app's own catch-all into that file is the one framework-side answer that
119
+ * works everywhere. Emission is automatic when a top-level catch-all exists —
120
+ * there is no config key to set.
121
+ *
122
+ * Semantics, all deliberate:
123
+ *
124
+ * - **Only a TOP-LEVEL catch-all qualifies.** A nested one (`/admin/*`) answers
125
+ * only for URLs beneath its own prefix, so it cannot stand in as the
126
+ * site-wide not-found document and is ignored.
127
+ * - **No catch-all at all is a complete no-op.** The caller writes no file and
128
+ * reports no failure; a site without a not-found page is a valid site.
129
+ * - **More than one top-level catch-all** cannot arise from the file scanner,
130
+ * but this takes an arbitrary array. The FIRST match in depth-first traversal
131
+ * order wins, deterministically. It does not throw — an ambiguous route tree
132
+ * is not a reason to fail an otherwise complete export.
133
+ *
134
+ * Children ARE walked, and that is load-bearing rather than defensive: an app
135
+ * with a root `+layout` nests its catch-all under that layout node, and because
136
+ * patterns are absolute the child's pattern is still `/*`. The pattern check is
137
+ * what confines the result to the site-wide catch-all — a nested `/admin/*`
138
+ * fails it at any depth — so recursion cannot promote a nested catch-all.
139
+ *
140
+ * @param routes - Route node tree.
141
+ * @returns The top-level catch-all node, or `undefined` if the app has none.
142
+ */
143
+ export function findRootCatchAllRoute(routes) {
144
+ for (const node of routes) {
145
+ const pattern = node.pattern.replace(/\/+$/, '') || '/';
146
+ if (node.metadata.isCatchAll && pattern === ROOT_CATCH_ALL_PATTERN) {
147
+ return node;
148
+ }
149
+ if (node.children.length > 0) {
150
+ const nested = findRootCatchAllRoute(node.children);
151
+ if (nested)
152
+ return nested;
153
+ }
154
+ }
155
+ return undefined;
156
+ }
157
+ // Re-export for backward compatibility (canonical in shell-helpers)
158
+ export { pathToFilePath } from '../shared/shell-helpers.js';
159
+ /**
160
+ * Normalize a URL path for deduplication.
161
+ * Collapses slashes, ensures leading /, strips trailing /, removes query/hash.
162
+ */
163
+ function normalizePath(urlPath) {
164
+ const cleanPath = urlPath.split(/[?#]/)[0];
165
+ const collapsed = cleanPath.replace(/\/+/g, '/').replace(/\/$/, '');
166
+ return collapsed || '/';
167
+ }
168
+ // =============================================================================
169
+ // Main SSG Function
170
+ // =============================================================================
171
+ /** @codexApi {"parent":"pithy.ssr.build.ssg","name":"generateStaticSite","stability":"experimental","signature":"(options: GenerateStaticSiteOptions) => Promise<SSGResult>"} */
172
+ /**
173
+ * Generate a static site by pre-rendering routes to HTML files.
174
+ *
175
+ * This function:
176
+ * 1. Collects paths to render (from explicit list or auto-detected from routes)
177
+ * 2. Renders each path using renderToString
178
+ * 3. Wraps in htmlShell for complete HTML documents
179
+ * 4. Writes files to the output directory
180
+ *
181
+ * @param options - SSG options
182
+ * @returns Build result with rendered/failed paths and timing
183
+ *
184
+ * @example Basic usage with explicit paths
185
+ * ```ts
186
+ * const result = await generateStaticSite({
187
+ * outDir: './dist',
188
+ * App: MyApp,
189
+ * paths: ['/', '/about', '/blog/post-1'],
190
+ * scripts: ['/entry-client.js'],
191
+ * });
192
+ *
193
+ * console.log(`Rendered ${result.rendered.length} pages`);
194
+ * ```
195
+ *
196
+ * @example Auto-detect from route tree
197
+ * ```ts
198
+ * const result = await generateStaticSite({
199
+ * outDir: './dist',
200
+ * App: MyApp,
201
+ * routes: myRouteTree,
202
+ * });
203
+ * ```
204
+ */
205
+ export async function generateStaticSite(options) {
206
+ const { outDir, App, paths: explicitPaths, routes, base, scripts, styles, onPage, onError, } = options;
207
+ const startTime = performance.now();
208
+ const rendered = [];
209
+ const failed = [];
210
+ const entryOwners = new Map();
211
+ // 1. Collect paths to render
212
+ let pathsToRender;
213
+ if (explicitPaths && explicitPaths.length > 0) {
214
+ // Normalize and deduplicate: collapse slashes, ensure leading /, strip trailing /
215
+ // so '/about' and '/about/' map to a single render
216
+ const normalized = explicitPaths.map(normalizePath);
217
+ pathsToRender = [...new Set(normalized)];
218
+ }
219
+ else if (routes) {
220
+ // Auto-detect from route tree
221
+ pathsToRender = await collectStaticPaths(routes);
222
+ }
223
+ else {
224
+ // No paths and no routes - nothing to render
225
+ pathsToRender = [];
226
+ }
227
+ // The route tree is the only thing that knows about a catch-all, so this is
228
+ // driven by `routes` even when `paths` overrode the page list: the two are
229
+ // separate concerns, and `paths` selects *pages*, not the fallback document.
230
+ const notFoundRoute = routes ? findRootCatchAllRoute(routes) : undefined;
231
+ if (pathsToRender.length === 0 && !notFoundRoute) {
232
+ return {
233
+ rendered,
234
+ notFound: null,
235
+ failed,
236
+ totalTime: performance.now() - startTime,
237
+ };
238
+ }
239
+ // 2. Ensure output directory exists
240
+ fs.mkdirSync(outDir, { recursive: true });
241
+ // 3. Prepare script/style paths with base URL
242
+ const resolvedScripts = scripts?.map(s => prependBase(s, base)) ?? [];
243
+ const resolvedStyles = styles?.map(s => prependBase(s, base)) ?? [];
244
+ // 4. Render pages sequentially
245
+ // Concurrent rendering requires isolated DOM environments per render.
246
+ // Each renderToString() call sets up/tears down shared happy-dom globals,
247
+ // so concurrent calls within the same thread would conflict.
248
+ // Use SSRWorkerPool for concurrent SSR with isolated DOM per worker.
249
+ const notFound = { entry: null };
250
+ const ctx = {
251
+ outDir,
252
+ App,
253
+ scripts: resolvedScripts,
254
+ styles: resolvedStyles,
255
+ rendered,
256
+ notFound,
257
+ failed,
258
+ entryOwners,
259
+ onPage,
260
+ onError,
261
+ };
262
+ for (const pagePath of pathsToRender) {
263
+ await renderPage(pagePath, ctx);
264
+ }
265
+ // 5. Emit the site-wide not-found document, if the app has a top-level
266
+ // catch-all. Written at the OUTPUT ROOT (`404.html`, not `404/index.html`),
267
+ // because that is the filename every static host looks for.
268
+ //
269
+ // This engine and `buildSSG()` reach that document by different routes, and
270
+ // the difference is visible to an app that defines BOTH a catch-all and a
271
+ // literal `/404` page. `buildSSG()` renders the catch-all node it found;
272
+ // here there is no node to render — the API takes an `App`, so the only
273
+ // lever is the URL, and the app's own router resolves `/404` to the literal
274
+ // page when one exists. Neither is wrong: both emit a full document with the
275
+ // app's chrome, and an app with a literal `/404` has said what it wants that
276
+ // URL to show. Worth knowing when comparing output between the two, and
277
+ // worth collapsing when they are finally unified.
278
+ //
279
+ // The absolute-vs-relative link question that `buildSSG()` has to answer for
280
+ // this document does not arise here: this engine never relativises links.
281
+ if (notFoundRoute) {
282
+ await renderPage(NOT_FOUND_OUTPUT.renderPath, ctx, NOT_FOUND_OUTPUT.entry);
283
+ }
284
+ return {
285
+ rendered,
286
+ notFound: notFound.entry,
287
+ failed,
288
+ totalTime: performance.now() - startTime,
289
+ };
290
+ }
291
+ /**
292
+ * Record one emitted document.
293
+ *
294
+ * The not-found document is reported separately from `rendered`: it has no
295
+ * route path, so listing it as `/404` invents a route, and an app that really
296
+ * does define `/404` would appear twice with no way to tell which entry was
297
+ * which.
298
+ */
299
+ function recordRendered(ctx, pagePath, outFile) {
300
+ if (outFile === NOT_FOUND_OUTPUT.entry) {
301
+ ctx.notFound.entry = outFile;
302
+ return;
303
+ }
304
+ ctx.rendered.push(pagePath);
305
+ }
306
+ /**
307
+ * Render a single page and write to disk.
308
+ *
309
+ * @param pagePath - URL to render at.
310
+ * @param ctx - Shared render/write state.
311
+ * @param outFile - Output path relative to `outDir`, overriding the usual
312
+ * `pathToFilePath(pagePath)` mapping. Used for the root `404.html`, which
313
+ * must NOT be nested as `404/index.html`.
314
+ */
315
+ async function renderPage(pagePath, ctx, outFile) {
316
+ try {
317
+ // Reject paths containing traversal segments early — before rendering
318
+ // (pathToFilePath strips ".." silently for defense-in-depth, but we
319
+ // still want to report the attempt as an explicit error)
320
+ const segments = pagePath.replace(/^\//, '').split('/');
321
+ if (segments.some(s => s === '..' || s === '.')) {
322
+ throw new Error(`Path traversal detected: "${pagePath}" contains ".." or "." segments`);
323
+ }
324
+ // Render component to HTML
325
+ const result = await renderToString({
326
+ url: pagePath,
327
+ App: ctx.App,
328
+ });
329
+ // Handle redirects - skip writing, record as rendered
330
+ if (result.redirectTo) {
331
+ // An ordinary page still counts as rendered here; the not-found document
332
+ // must NOT, because `notFound` names the entry a file was WRITTEN to and
333
+ // a redirect writes none. Reporting it left callers with `notFound:
334
+ // '404.html'` and no such file on disk.
335
+ if (outFile !== NOT_FOUND_OUTPUT.entry)
336
+ ctx.rendered.push(pagePath);
337
+ ctx.onPage?.(pagePath, '');
338
+ return;
339
+ }
340
+ // Generate complete HTML document
341
+ const shellOptions = {
342
+ html: result.html,
343
+ head: result.head,
344
+ state: result.state,
345
+ scripts: ctx.scripts,
346
+ styles: ctx.styles,
347
+ };
348
+ const fullHtml = htmlShell(shellOptions);
349
+ // Write to file
350
+ const relPath = outFile ?? pathToFilePath(pagePath);
351
+ // `/About` and `/about` are two names on ext4 and one file on APFS and
352
+ // NTFS — writing both silently ships whichever rendered last.
353
+ const collisionKey = entryCollisionKey(relPath);
354
+ const owner = ctx.entryOwners.get(collisionKey);
355
+ if (owner !== undefined) {
356
+ const detail = owner.entry === relPath
357
+ ? `both write to "${relPath}"`
358
+ : `write to "${owner.entry}" and "${relPath}", which are one file on a filesystem that ignores case or Unicode normalization`;
359
+ throw new Error(`Output collision: paths "${owner.path}" and "${pagePath}" ${detail}`);
360
+ }
361
+ ctx.entryOwners.set(collisionKey, { path: pagePath, entry: relPath });
362
+ const filePath = path.resolve(ctx.outDir, relPath);
363
+ const resolvedOutDir = path.resolve(ctx.outDir);
364
+ // Prevent path traversal - ensure output stays within outDir
365
+ const relative = path.relative(resolvedOutDir, filePath);
366
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
367
+ throw new Error(`Path traversal detected: "${pagePath}" resolves outside output directory`);
368
+ }
369
+ const fileDir = path.dirname(filePath);
370
+ // Ensure directory exists
371
+ fs.mkdirSync(fileDir, { recursive: true });
372
+ fs.writeFileSync(filePath, fullHtml, 'utf-8');
373
+ recordRendered(ctx, pagePath, outFile);
374
+ ctx.onPage?.(pagePath, fullHtml);
375
+ }
376
+ catch (err) {
377
+ const error = err instanceof Error ? err : new Error(String(err));
378
+ ctx.failed.push({ path: pagePath, error });
379
+ ctx.onError?.(pagePath, error);
380
+ }
381
+ }
382
+ /**
383
+ * Prepend base URL to a path
384
+ */
385
+ function prependBase(assetPath, base) {
386
+ if (!base)
387
+ return assetPath;
388
+ // Skip absolute URLs, protocol-relative URLs, and data URIs
389
+ if (/^(?:https?:\/\/|\/\/|data:)/i.test(assetPath))
390
+ return assetPath;
391
+ // Normalize base: remove trailing slash
392
+ const normalizedBase = base.replace(/\/$/, '');
393
+ // If asset already starts with base, don't double-prepend
394
+ // Check segment boundary to avoid false positives (e.g., base="/my" matching "/my-app")
395
+ if (assetPath === normalizedBase ||
396
+ assetPath.startsWith(normalizedBase + '/'))
397
+ return assetPath;
398
+ // If asset starts with /, replace with base
399
+ if (assetPath.startsWith('/')) {
400
+ return normalizedBase + assetPath;
401
+ }
402
+ return normalizedBase + '/' + assetPath;
403
+ }
404
+ //# sourceMappingURL=ssg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssg.js","sourceRoot":"","sources":["../../src/build/ssg.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAIlC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AA8BlD,gFAAgF;AAChF,kBAAkB;AAClB,gFAAgF;AAEhF,6JAA6J;AAC7J;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,MAAmB;IAEnB,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAE/B,KAAK,UAAU,IAAI,CAAC,KAAkB;QACpC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,iDAAiD;YACjD,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;gBACtB,wCAAwC;gBACxC,MAAM,eAAe,GAAG,MAAM,oBAAoB,CAAC,IAAI,CAAC,CAAC;gBAEzD,IAAI,eAAe,IAAI,CAAC,IAAI,CAAC,GAAG,CA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AC,UAAU,CAAC,cAAc,GAAG,GAAG,CAAC;QAE1C,OAAO,SAAS,CAAC;IAEnB,4CAA4C;IAC5C,IAAI,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QAC9B,OAAO,cAAc,GAAG,SAAS,CAAC;IACpC,CAAC;IAED,OAAO,cAAc,GAAG,GAAG,GAAG,SAAS,CAAC;AAC1C,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.build.ssg\",\n \"title\": \"Static Site Generation Pipeline\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - Static Site Generation (SSG)\n *\n * Pre-renders routes to static HTML files at build time.\n * Uses renderToString + htmlShell to generate complete HTML documents.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { RouteNode } from '@pithyjs/router';\nimport type { Component } from '@pithyjs/core';\nimport type { SSGResult, ShellOptions } from '../shared/types.js';\nimport { renderToString } from '../server/render.js';\nimport { htmlShell } from '../server/html-shell.js';\nimport { pathToFilePath } from '../shared/shell-helpers.js';\nimport { entryCollisionKey } from '../shared/entry-path.js';\nimport { NOT_FOUND_OUTPUT } from './not-found.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for static site generation\n */\nexport interface GenerateStaticSiteOptions {\n /** Output directory for generated HTML files */\n outDir: string;\n /** Root component to render */\n App: Component;\n /** Explicit paths to pre-render (takes priority over auto-detection) */\n paths?: string[];\n /** Route tree for auto-detecting static paths (used when paths not provided) */\n routes?: RouteNode[];\n /** Base URL to prepend to asset paths (e.g., '/my-app') */\n base?: string;\n /** Script URLs to include in generated HTML */\n scripts?: string[];\n /** Stylesheet URLs to include in generated HTML */\n styles?: string[];\n /** Callback for each successfully rendered page */\n onPage?: (path: string, html: string) => void;\n /** Callback on render error */\n onError?: (path: string, error: Error) => void;\n}\n\n// =============================================================================\n// Path Collection\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.build.ssg\",\"name\":\"collectStaticPaths\",\"stability\":\"internal\",\"signature\":\"(routes: RouteNode[]) => Promise<string[]>\"} */\n/**\n * Collect paths from static routes for pre-rendering.\n *\n * Walks the route tree and collects paths for routes that:\n * - Are not dynamic (no :param segments)\n * - Are not catch-all (no * or [...] segments)\n * - Have a page import\n * - Do not have prerender=false in their config\n *\n * @param routes - Route node tree\n * @returns Array of static paths to pre-render\n */\nexport async function collectStaticPaths(\n routes: RouteNode[]\n): Promise<string[]> {\n const paths: string[] = [];\n const seen = new Set<string>();\n\n async function walk(nodes: RouteNode[]): Promise<void> {\n for (const node of nodes) {\n // Only collect routes that have a page component\n if (node.imports.page) {\n // Check if route should be pre-rendered\n const shouldPrerender = await shouldPrerenderRoute(node);\n\n if (shouldPrerender && !seen.has(node.pattern)) {\n seen.add(node.pattern);\n paths.push(node.pattern);\n }\n }\n\n // Recurse into children\n if (node.children.length > 0) {\n await walk(node.children);\n }\n }\n }\n\n await walk(routes);\n return paths;\n}\n\n/**\n * Determine if a route should be pre-rendered\n *\n * Rules:\n * - Static routes (no dynamic params, no catch-all): yes by default\n * - Dynamic / catch-all routes: no (never auto-collected here)\n * - Config with prerender=false: no (override for static)\n * - Config with prerender=true: yes for static routes; for dynamic / catch-all routes\n * it only signals intent and still requires explicit paths elsewhere\n *\n * **The catch-all exclusion is deliberate and stays.** The site-wide `404.html`\n * (see {@link findRootCatchAllRoute}) is emitted by a *separate* step, not by\n * widening this predicate. Letting a catch-all through here would also emit it\n * at its own literal pattern path — the `/*` route would land in a directory\n * literally named `*`, which no host will ever request.\n */\nasync function shouldPrerenderRoute(node: RouteNode): Promise<boolean> {\n const isStatic =\n node.metadata.isStatic &&\n !node.metadata.isDynamic &&\n !node.metadata.isCatchAll;\n\n // Check config for explicit prerender setting\n if (node.imports.config) {\n try {\n const config = await node.imports.config();\n if (typeof config.prerender === 'boolean') {\n // For dynamic routes, prerender=true only signals intent\n // The route still needs explicit paths (can't auto-generate param values)\n if (!isStatic && config.prerender) {\n return false; // Dynamic routes can't be auto-collected\n }\n return config.prerender;\n }\n } catch {\n // Config import failed, use default behavior\n }\n }\n\n return isStatic;\n}\n\n// =============================================================================\n// Not-found (404) discovery\n// =============================================================================\n\n/**\n * The only route pattern that can back a site-wide not-found document.\n *\n * The route scanner turns a `src/routes/[...slug]/` folder into the single\n * wildcard segment `*`, so a ROOT catch-all's pattern is `/*` — never\n * `/[...slug]`. Local to this module: `buildSSG()` finds its catch-all through\n * `findRootCatchAllRoute()` below rather than by matching the pattern itself.\n */\nconst ROOT_CATCH_ALL_PATTERN = '/*';\n\n/** @codexApi {\"parent\":\"pithy.ssr.build.ssg\",\"name\":\"findRootCatchAllRoute\",\"stability\":\"internal\",\"signature\":\"(routes: RouteNode[]) => RouteNode | undefined\"} */\n/**\n * Find the top-level catch-all route that backs the site-wide `404.html`.\n *\n * Netlify, Vercel, GitHub Pages and Cloudflare Pages serve a root `404.html`\n * for an unmatched path with no per-host configuration; S3 needs\n * `ErrorDocument: 404.html` on its static-website endpoint. So rendering\n * the app's own catch-all into that file is the one framework-side answer that\n * works everywhere. Emission is automatic when a top-level catch-all exists —\n * there is no config key to set.\n *\n * Semantics, all deliberate:\n *\n * - **Only a TOP-LEVEL catch-all qualifies.** A nested one (`/admin/*`) answers\n * only for URLs beneath its own prefix, so it cannot stand in as the\n * site-wide not-found document and is ignored.\n * - **No catch-all at all is a complete no-op.** The caller writes no file and\n * reports no failure; a site without a not-found page is a valid site.\n * - **More than one top-level catch-all** cannot arise from the file scanner,\n * but this takes an arbitrary array. The FIRST match in depth-first traversal\n * order wins, deterministically. It does not throw — an ambiguous route tree\n * is not a reason to fail an otherwise complete export.\n *\n * Children ARE walked, and that is load-bearing rather than defensive: an app\n * with a root `+layout` nests its catch-all under that layout node, and because\n * patterns are absolute the child's pattern is still `/*`. The pattern check is\n * what confines the result to the site-wide catch-all — a nested `/admin/*`\n * fails it at any depth — so recursion cannot promote a nested catch-all.\n *\n * @param routes - Route node tree.\n * @returns The top-level catch-all node, or `undefined` if the app has none.\n */\nexport function findRootCatchAllRoute(\n routes: RouteNode[]\n): RouteNode | undefined {\n for (const node of routes) {\n const pattern = node.pattern.replace(/\\/+$/, '') || '/';\n if (node.metadata.isCatchAll && pattern === ROOT_CATCH_ALL_PATTERN) {\n return node;\n }\n\n if (node.children.length > 0) {\n const nested = findRootCatchAllRoute(node.children);\n if (nested) return nested;\n }\n }\n\n return undefined;\n}\n\n// Re-export for backward compatibility (canonical in shell-helpers)\nexport { pathToFilePath } from '../shared/shell-helpers.js';\n\n/**\n * Normalize a URL path for deduplication.\n * Collapses slashes, ensures leading /, strips trailing /, removes query/hash.\n */\nfunction normalizePath(urlPath: string): string {\n const cleanPath = urlPath.split(/[?#]/)[0];\n const collapsed = cleanPath.replace(/\\/+/g, '/').replace(/\\/$/, '');\n return collapsed || '/';\n}\n\n// =============================================================================\n// Main SSG Function\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.build.ssg\",\"name\":\"generateStaticSite\",\"stability\":\"experimental\",\"signature\":\"(options: GenerateStaticSiteOptions) => Promise<SSGResult>\"} */\n/**\n * Generate a static site by pre-rendering routes to HTML files.\n *\n * This function:\n * 1. Collects paths to render (from explicit list or auto-detected from routes)\n * 2. Renders each path using renderToString\n * 3. Wraps in htmlShell for complete HTML documents\n * 4. Writes files to the output directory\n *\n * @param options - SSG options\n * @returns Build result with rendered/failed paths and timing\n *\n * @example Basic usage with explicit paths\n * ```ts\n * const result = await generateStaticSite({\n * outDir: './dist',\n * App: MyApp,\n * paths: ['/', '/about', '/blog/post-1'],\n * scripts: ['/entry-client.js'],\n * });\n *\n * console.log(`Rendered ${result.rendered.length} pages`);\n * ```\n *\n * @example Auto-detect from route tree\n * ```ts\n * const result = await generateStaticSite({\n * outDir: './dist',\n * App: MyApp,\n * routes: myRouteTree,\n * });\n * ```\n */\nexport async function generateStaticSite(\n options: GenerateStaticSiteOptions\n): Promise<SSGResult> {\n const {\n outDir,\n App,\n paths: explicitPaths,\n routes,\n base,\n scripts,\n styles,\n onPage,\n onError,\n } = options;\n\n const startTime = performance.now();\n const rendered: string[] = [];\n const failed: Array<{ path: string; error: Error }> = [];\n const entryOwners = new Map<string, { path: string; entry: string }>();\n\n // 1. Collect paths to render\n let pathsToRender: string[];\n\n if (explicitPaths && explicitPaths.length > 0) {\n // Normalize and deduplicate: collapse slashes, ensure leading /, strip trailing /\n // so '/about' and '/about/' map to a single render\n const normalized = explicitPaths.map(normalizePath);\n pathsToRender = [...new Set(normalized)];\n } else if (routes) {\n // Auto-detect from route tree\n pathsToRender = await collectStaticPaths(routes);\n } else {\n // No paths and no routes - nothing to render\n pathsToRender = [];\n }\n\n // The route tree is the only thing that knows about a catch-all, so this is\n // driven by `routes` even when `paths` overrode the page list: the two are\n // separate concerns, and `paths` selects *pages*, not the fallback document.\n const notFoundRoute = routes ? findRootCatchAllRoute(routes) : undefined;\n\n if (pathsToRender.length === 0 && !notFoundRoute) {\n return {\n rendered,\n notFound: null,\n failed,\n totalTime: performance.now() - startTime,\n };\n }\n\n // 2. Ensure output directory exists\n fs.mkdirSync(outDir, { recursive: true });\n\n // 3. Prepare script/style paths with base URL\n const resolvedScripts = scripts?.map(s => prependBase(s, base)) ?? [];\n const resolvedStyles = styles?.map(s => prependBase(s, base)) ?? [];\n\n // 4. Render pages sequentially\n // Concurrent rendering requires isolated DOM environments per render.\n // Each renderToString() call sets up/tears down shared happy-dom globals,\n // so concurrent calls within the same thread would conflict.\n // Use SSRWorkerPool for concurrent SSR with isolated DOM per worker.\n const notFound: { entry: string | null } = { entry: null };\n const ctx: RenderPageContext = {\n outDir,\n App,\n scripts: resolvedScripts,\n styles: resolvedStyles,\n rendered,\n notFound,\n failed,\n entryOwners,\n onPage,\n onError,\n };\n\n for (const pagePath of pathsToRender) {\n await renderPage(pagePath, ctx);\n }\n\n // 5. Emit the site-wide not-found document, if the app has a top-level\n // catch-all. Written at the OUTPUT ROOT (`404.html`, not `404/index.html`),\n // because that is the filename every static host looks for.\n //\n // This engine and `buildSSG()` reach that document by different routes, and\n // the difference is visible to an app that defines BOTH a catch-all and a\n // literal `/404` page. `buildSSG()` renders the catch-all node it found;\n // here there is no node to render — the API takes an `App`, so the only\n // lever is the URL, and the app's own router resolves `/404` to the literal\n // page when one exists. Neither is wrong: both emit a full document with the\n // app's chrome, and an app with a literal `/404` has said what it wants that\n // URL to show. Worth knowing when comparing output between the two, and\n // worth collapsing when they are finally unified.\n //\n // The absolute-vs-relative link question that `buildSSG()` has to answer for\n // this document does not arise here: this engine never relativises links.\n if (notFoundRoute) {\n await renderPage(NOT_FOUND_OUTPUT.renderPath, ctx, NOT_FOUND_OUTPUT.entry);\n }\n\n return {\n rendered,\n notFound: notFound.entry,\n failed,\n totalTime: performance.now() - startTime,\n };\n}\n\n// =============================================================================\n// Rendering Helpers\n// =============================================================================\n\ninterface RenderPageContext {\n outDir: string;\n App: Component;\n scripts: string[];\n styles: string[];\n rendered: string[];\n /** Set to the entry when the not-found document is written. */\n notFound: { entry: string | null };\n failed: Array<{ path: string; error: Error }>;\n /** Collision key → the path that claimed it, so two routes cannot overwrite. */\n entryOwners: Map<string, { path: string; entry: string }>;\n onPage?: (path: string, html: string) => void;\n onError?: (path: string, error: Error) => void;\n}\n\n/**\n * Record one emitted document.\n *\n * The not-found document is reported separately from `rendered`: it has no\n * route path, so listing it as `/404` invents a route, and an app that really\n * does define `/404` would appear twice with no way to tell which entry was\n * which.\n */\nfunction recordRendered(\n ctx: RenderPageContext,\n pagePath: string,\n outFile: string | undefined\n): void {\n if (outFile === NOT_FOUND_OUTPUT.entry) {\n ctx.notFound.entry = outFile;\n return;\n }\n\n ctx.rendered.push(pagePath);\n}\n\n/**\n * Render a single page and write to disk.\n *\n * @param pagePath - URL to render at.\n * @param ctx - Shared render/write state.\n * @param outFile - Output path relative to `outDir`, overriding the usual\n * `pathToFilePath(pagePath)` mapping. Used for the root `404.html`, which\n * must NOT be nested as `404/index.html`.\n */\nasync function renderPage(\n pagePath: string,\n ctx: RenderPageContext,\n outFile?: string\n): Promise<void> {\n try {\n // Reject paths containing traversal segments early — before rendering\n // (pathToFilePath strips \"..\" silently for defense-in-depth, but we\n // still want to report the attempt as an explicit error)\n const segments = pagePath.replace(/^\\//, '').split('/');\n if (segments.some(s => s === '..' || s === '.')) {\n throw new Error(\n `Path traversal detected: \"${pagePath}\" contains \"..\" or \".\" segments`\n );\n }\n\n // Render component to HTML\n const result = await renderToString({\n url: pagePath,\n App: ctx.App,\n });\n\n // Handle redirects - skip writing, record as rendered\n if (result.redirectTo) {\n // An ordinary page still counts as rendered here; the not-found document\n // must NOT, because `notFound` names the entry a file was WRITTEN to and\n // a redirect writes none. Reporting it left callers with `notFound:\n // '404.html'` and no such file on disk.\n if (outFile !== NOT_FOUND_OUTPUT.entry) ctx.rendered.push(pagePath);\n ctx.onPage?.(pagePath, '');\n return;\n }\n\n // Generate complete HTML document\n const shellOptions: ShellOptions = {\n html: result.html,\n head: result.head,\n state: result.state,\n scripts: ctx.scripts,\n styles: ctx.styles,\n };\n\n const fullHtml = htmlShell(shellOptions);\n\n // Write to file\n const relPath = outFile ?? pathToFilePath(pagePath);\n\n // `/About` and `/about` are two names on ext4 and one file on APFS and\n // NTFS — writing both silently ships whichever rendered last.\n const collisionKey = entryCollisionKey(relPath);\n const owner = ctx.entryOwners.get(collisionKey);\n if (owner !== undefined) {\n const detail =\n owner.entry === relPath\n ? `both write to \"${relPath}\"`\n : `write to \"${owner.entry}\" and \"${relPath}\", which are one file on a filesystem that ignores case or Unicode normalization`;\n throw new Error(\n `Output collision: paths \"${owner.path}\" and \"${pagePath}\" ${detail}`\n );\n }\n ctx.entryOwners.set(collisionKey, { path: pagePath, entry: relPath });\n\n const filePath = path.resolve(ctx.outDir, relPath);\n const resolvedOutDir = path.resolve(ctx.outDir);\n\n // Prevent path traversal - ensure output stays within outDir\n const relative = path.relative(resolvedOutDir, filePath);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error(\n `Path traversal detected: \"${pagePath}\" resolves outside output directory`\n );\n }\n\n const fileDir = path.dirname(filePath);\n\n // Ensure directory exists\n fs.mkdirSync(fileDir, { recursive: true });\n fs.writeFileSync(filePath, fullHtml, 'utf-8');\n\n recordRendered(ctx, pagePath, outFile);\n ctx.onPage?.(pagePath, fullHtml);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n ctx.failed.push({ path: pagePath, error });\n ctx.onError?.(pagePath, error);\n }\n}\n\n/**\n * Prepend base URL to a path\n */\nfunction prependBase(assetPath: string, base?: string): string {\n if (!base) return assetPath;\n\n // Skip absolute URLs, protocol-relative URLs, and data URIs\n if (/^(?:https?:\\/\\/|\\/\\/|data:)/i.test(assetPath)) return assetPath;\n\n // Normalize base: remove trailing slash\n const normalizedBase = base.replace(/\\/$/, '');\n\n // If asset already starts with base, don't double-prepend\n // Check segment boundary to avoid false positives (e.g., base=\"/my\" matching \"/my-app\")\n if (\n assetPath === normalizedBase ||\n assetPath.startsWith(normalizedBase + '/')\n )\n return assetPath;\n\n // If asset starts with /, replace with base\n if (assetPath.startsWith('/')) {\n return normalizedBase + assetPath;\n }\n\n return normalizedBase + '/' + assetPath;\n}\n"]}