@pithyjs/ssr 0.2.0-beta.13 → 0.2.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/vite-ssg.d.ts +140 -1
- package/dist/build/vite-ssg.d.ts.map +1 -1
- package/dist/build/vite-ssg.js +310 -11
- package/dist/build/vite-ssg.js.map +1 -1
- package/package.json +6 -6
package/dist/build/vite-ssg.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { type SpriteBundle } from '@pithyjs/shared/sprite';
|
|
10
10
|
import type { RouteNode } from '@pithyjs/router';
|
|
11
|
-
import type { HeadState } from '../shared/types.js';
|
|
11
|
+
import type { HeadState, ShellOptions } from '../shared/types.js';
|
|
12
12
|
import { NOT_FOUND_OUTPUT, hasRenderedText } from './not-found.js';
|
|
13
13
|
interface SSGBuildResult {
|
|
14
14
|
/**
|
|
@@ -22,6 +22,8 @@ interface SSGBuildResult {
|
|
|
22
22
|
* rendered no content, or a hand-authored `public/404.html` that won.
|
|
23
23
|
*/
|
|
24
24
|
notFound: string | null;
|
|
25
|
+
/** Entries written for `ssg.shells`, e.g. `app/index.html`. */
|
|
26
|
+
shells: string[];
|
|
25
27
|
failed: Array<{
|
|
26
28
|
path: string;
|
|
27
29
|
error: Error;
|
|
@@ -82,7 +84,30 @@ export interface ClientBuildResult {
|
|
|
82
84
|
script?: string;
|
|
83
85
|
/** Relative paths to extracted CSS files */
|
|
84
86
|
css?: string[];
|
|
87
|
+
/** `base` as the client build resolved it (`/`, `/sub/`, a CDN URL, `./`). */
|
|
88
|
+
base?: string;
|
|
89
|
+
/** `publicDir` as the client build resolved it (`''` when disabled). */
|
|
90
|
+
publicDir?: string;
|
|
91
|
+
/** `build.copyPublicDir` as the client build resolved it. */
|
|
92
|
+
copyPublicDir?: boolean;
|
|
85
93
|
}
|
|
94
|
+
/** Where a build's `public/` files came from, and whether they were copied. */
|
|
95
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"PublicCopy","stability":"experimental","signature":"interface PublicCopy"} */
|
|
96
|
+
export interface PublicCopy {
|
|
97
|
+
publicDir: string | false | undefined;
|
|
98
|
+
copyPublicDir: boolean;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The `public/` settings that produced the output. In hydrate mode the
|
|
102
|
+
* production client build copied it, under its own config, which can differ
|
|
103
|
+
* from the serve-mode config the prerender server resolved.
|
|
104
|
+
*
|
|
105
|
+
* @param hydrate - Whether a client build ran.
|
|
106
|
+
* @param clientBuild - What it recorded.
|
|
107
|
+
* @param serve - The prerender server's `publicDir` and `build.copyPublicDir`.
|
|
108
|
+
*/
|
|
109
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"publicCopySource","stability":"experimental","signature":"(hydrate: boolean, clientBuild: ClientBuildResult, serve: PublicCopy) => PublicCopy"} */
|
|
110
|
+
export declare function publicCopySource(hydrate: boolean, clientBuild: ClientBuildResult, serve: PublicCopy): PublicCopy;
|
|
86
111
|
export { pathToFilePath } from '../shared/shell-helpers.js';
|
|
87
112
|
export { NOT_FOUND_OUTPUT, hasRenderedText };
|
|
88
113
|
/** One route {@link buildSSG}'s render loop renders and writes. */
|
|
@@ -130,6 +155,120 @@ export interface RenderJob {
|
|
|
130
155
|
*/
|
|
131
156
|
/** @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[]"} */
|
|
132
157
|
export declare function planRenderJobs(staticPaths: string[], notFoundRoute: RouteNode | null | undefined, findRouteByPattern: (routePath: string) => RouteNode | null | undefined): RenderJob[];
|
|
158
|
+
/** One SPA shell {@link buildSSG} writes: a document with no prerendered content. */
|
|
159
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"ShellJob","stability":"experimental","signature":"interface ShellJob"} */
|
|
160
|
+
export interface ShellJob {
|
|
161
|
+
/** URL path the shell is written for, normalised (`/app`). */
|
|
162
|
+
path: string;
|
|
163
|
+
/** Output file relative to `outDir` (`app/index.html`). */
|
|
164
|
+
entry: string;
|
|
165
|
+
}
|
|
166
|
+
/** What {@link planShellJobs} made of `ssg.shells`. */
|
|
167
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"ShellPlan","stability":"experimental","signature":"interface ShellPlan"} */
|
|
168
|
+
export interface ShellPlan {
|
|
169
|
+
/** Shells to write, in config order, duplicates removed. */
|
|
170
|
+
jobs: ShellJob[];
|
|
171
|
+
/** Entries that cannot be written. The build reports them as build failures. */
|
|
172
|
+
errors: string[];
|
|
173
|
+
/** Non-fatal notes, e.g. shells configured for a static (no-JS) build. */
|
|
174
|
+
warnings: string[];
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Plan the SPA shells listed in `pithy.config` `ssg.shells`.
|
|
178
|
+
*
|
|
179
|
+
* Each path must be a literal URL path: no parameter, wildcard, query, hash,
|
|
180
|
+
* percent-escape, dot or empty segment, and no segment ending in `.` or a
|
|
181
|
+
* space (Win32 trims those from file names). One trailing slash is dropped. A shell is only useful with a client bundle, so static
|
|
182
|
+
* mode plans none and warns instead.
|
|
183
|
+
*
|
|
184
|
+
* @param shells - The raw `ssg.shells` value; not trusted to be well-typed.
|
|
185
|
+
* @param hydrate - Whether the build emits a client bundle.
|
|
186
|
+
* @returns The jobs to write plus any errors and warnings.
|
|
187
|
+
*/
|
|
188
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"planShellJobs","stability":"experimental","signature":"(shells: unknown, hydrate: boolean) => ShellPlan"} */
|
|
189
|
+
export declare function planShellJobs(shells: unknown, hydrate: boolean): ShellPlan;
|
|
190
|
+
/** Inputs to {@link renderShellDocument}. */
|
|
191
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"ShellDocumentOptions","stability":"experimental","signature":"interface ShellDocumentOptions"} */
|
|
192
|
+
export interface ShellDocumentOptions {
|
|
193
|
+
/** Head from the app's HTML shell file. */
|
|
194
|
+
head: HeadState;
|
|
195
|
+
/** Root-absolute client script URLs (`/assets/…`). */
|
|
196
|
+
scripts: string[];
|
|
197
|
+
/** Root-absolute client stylesheet URLs, linked in `<head>`. */
|
|
198
|
+
styles: string[];
|
|
199
|
+
/** The production build's `base` (default `/`): every URL is moved under it. */
|
|
200
|
+
base?: string;
|
|
201
|
+
/** The `base` the head was read with (default `/`), which its root-absolute URLs carry. */
|
|
202
|
+
headBase?: string;
|
|
203
|
+
/** App container id (default `app`). */
|
|
204
|
+
appId?: string;
|
|
205
|
+
/** The app's icon sprite, or the empty bundle. */
|
|
206
|
+
sprite: SpriteBundle;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Render one SPA shell: head, every stylesheet, the module script, an empty
|
|
210
|
+
* app root and no hydration state, so `bootstrap()` mounts fresh.
|
|
211
|
+
*
|
|
212
|
+
* Links stay absolute (`linkBase: null`, as for the 404): one shell answers
|
|
213
|
+
* every URL under its path, at any depth. Relative `href`/`src` in the head's
|
|
214
|
+
* links and scripts are resolved against `base`, as the root `index.html` they
|
|
215
|
+
* came from would; with a `<base>` in the head they are left alone, with a
|
|
216
|
+
* warning. The head gets `robots: noindex` unless it sets robots itself: a
|
|
217
|
+
* shell has no content and answers arbitrary URLs.
|
|
218
|
+
*
|
|
219
|
+
* @param htmlShellFn - `htmlShell` from `@pithyjs/ssr/server`.
|
|
220
|
+
* @param options - See {@link ShellDocumentOptions}.
|
|
221
|
+
* @returns The document as it will be written.
|
|
222
|
+
*/
|
|
223
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"renderShellDocument","stability":"experimental","signature":"(htmlShellFn: (options: ShellOptions) => string, options: ShellDocumentOptions) => FinalizePageResult"} */
|
|
224
|
+
export declare function renderShellDocument(htmlShellFn: (options: ShellOptions) => string, options: ShellDocumentOptions): FinalizePageResult;
|
|
225
|
+
/** What {@link excludeShellPaths} made of the static paths. */
|
|
226
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"ShellExclusion","stability":"experimental","signature":"interface ShellExclusion"} */
|
|
227
|
+
export interface ShellExclusion {
|
|
228
|
+
/** Paths still prerendered. */
|
|
229
|
+
kept: string[];
|
|
230
|
+
/** Paths a shell serves instead, so they are not prerendered. */
|
|
231
|
+
skipped: string[];
|
|
232
|
+
/** One message per path that sets `prerender = true` under a shell. */
|
|
233
|
+
errors: string[];
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Drop the static paths a shell serves: its own path and, unless it is the
|
|
237
|
+
* root shell, every URL path below it, compared as written (one trailing slash
|
|
238
|
+
* ignored). Such routes need no `prerender = false` of their own. A path that
|
|
239
|
+
* only folds onto the shell's file (`/App`) is kept, and the entry check in
|
|
240
|
+
* {@link claimShellEntries} reports it.
|
|
241
|
+
* A path whose config says `prerender = true` contradicts the shell and is an
|
|
242
|
+
* error.
|
|
243
|
+
*
|
|
244
|
+
* @param staticPaths - Every literal path `collectStaticPaths()` found.
|
|
245
|
+
* @param shells - Planned shells, see {@link planShellJobs}.
|
|
246
|
+
* @param forced - Paths whose route config sets `prerender = true`.
|
|
247
|
+
*/
|
|
248
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"excludeShellPaths","stability":"experimental","signature":"(staticPaths: readonly string[], shells: readonly ShellJob[], forced: ReadonlySet<string>) => ShellExclusion"} */
|
|
249
|
+
export declare function excludeShellPaths(staticPaths: readonly string[], shells: readonly ShellJob[], forced: ReadonlySet<string>): ShellExclusion;
|
|
250
|
+
/** Who wrote an output entry: a route path and the file it went to. */
|
|
251
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"EntryOwner","stability":"experimental","signature":"interface EntryOwner"} */
|
|
252
|
+
export interface EntryOwner {
|
|
253
|
+
path: string;
|
|
254
|
+
entry: string;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Decide which shells may be written, given the entries the pages already
|
|
258
|
+
* wrote (keyed by `entryCollisionKey`). A shell is refused when a page owns its
|
|
259
|
+
* file (`/App` against `/app` on a case-insensitive filesystem) or when the app
|
|
260
|
+
* ships that file in `public/`, which the shell would overwrite. Claimed shells
|
|
261
|
+
* are registered in `owners`, which this mutates.
|
|
262
|
+
*
|
|
263
|
+
* @param shells - Planned shells, see {@link planShellJobs}.
|
|
264
|
+
* @param owners - Entries written so far.
|
|
265
|
+
* @param isAuthored - Whether `public/` holds a file at an entry.
|
|
266
|
+
*/
|
|
267
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"claimShellEntries","stability":"experimental","signature":"(shells: readonly ShellJob[], owners: Map<string, EntryOwner>, isAuthored: (entry: string) => boolean) => { claimed: ShellJob[]; errors: string[] }"} */
|
|
268
|
+
export declare function claimShellEntries(shells: readonly ShellJob[], owners: Map<string, EntryOwner>, isAuthored: (entry: string) => boolean): {
|
|
269
|
+
claimed: ShellJob[];
|
|
270
|
+
errors: string[];
|
|
271
|
+
};
|
|
133
272
|
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"copyPublicAssets","stability":"experimental","signature":"(publicDir: string | false | undefined, outDir: string) => string[]"} */
|
|
134
273
|
/**
|
|
135
274
|
* Copy the app's public directory into the output.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-ssg.d.ts","sourceRoot":"","sources":["../../src/build/vite-ssg.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AA8BF,OAAO,EAEL,KAAK,YAAY,EAClB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"vite-ssg.d.ts","sourceRoot":"","sources":["../../src/build/vite-ssg.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AA8BF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,GAAE,SAAS;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,OAAO,CAAA;CAAE,EAAO,GACxD,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAyC9B"}
|
package/dist/build/vite-ssg.js
CHANGED
|
@@ -43,6 +43,30 @@ import { loadSpriteForSsg, clearSpriteForSsg } from './sprite-ssg.js';
|
|
|
43
43
|
import { readShellHead, resolvePageHead } from './shell-head.js';
|
|
44
44
|
import { injectIntoOutlet, pathToFilePath, wrapInLayouts, } from '../shared/shell-helpers.js';
|
|
45
45
|
import { entryCollisionKey } from '../shared/entry-path.js';
|
|
46
|
+
/**
|
|
47
|
+
* The `public/` settings that produced the output. In hydrate mode the
|
|
48
|
+
* production client build copied it, under its own config, which can differ
|
|
49
|
+
* from the serve-mode config the prerender server resolved.
|
|
50
|
+
*
|
|
51
|
+
* @param hydrate - Whether a client build ran.
|
|
52
|
+
* @param clientBuild - What it recorded.
|
|
53
|
+
* @param serve - The prerender server's `publicDir` and `build.copyPublicDir`.
|
|
54
|
+
*/
|
|
55
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"publicCopySource","stability":"experimental","signature":"(hydrate: boolean, clientBuild: ClientBuildResult, serve: PublicCopy) => PublicCopy"} */
|
|
56
|
+
export function publicCopySource(hydrate, clientBuild, serve) {
|
|
57
|
+
if (!hydrate)
|
|
58
|
+
return serve;
|
|
59
|
+
return {
|
|
60
|
+
publicDir: clientBuild.publicDir || false,
|
|
61
|
+
copyPublicDir: clientBuild.copyPublicDir ?? false,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Whether `public/` supplied a file at `entry` in the output. */
|
|
65
|
+
function isAuthoredPublicFile(source, entry) {
|
|
66
|
+
return (source.copyPublicDir &&
|
|
67
|
+
typeof source.publicDir === 'string' &&
|
|
68
|
+
fs.existsSync(path.join(source.publicDir, entry)));
|
|
69
|
+
}
|
|
46
70
|
// Re-export pathToFilePath for test access (canonical definition in shell-helpers)
|
|
47
71
|
export { pathToFilePath } from '../shared/shell-helpers.js';
|
|
48
72
|
// Canonical in `./not-found.js`, so `generateStaticSite()` and `buildSSG()`
|
|
@@ -89,6 +113,204 @@ export function planRenderJobs(staticPaths, notFoundRoute, findRouteByPattern) {
|
|
|
89
113
|
}
|
|
90
114
|
return renderJobs;
|
|
91
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Plan the SPA shells listed in `pithy.config` `ssg.shells`.
|
|
118
|
+
*
|
|
119
|
+
* Each path must be a literal URL path: no parameter, wildcard, query, hash,
|
|
120
|
+
* percent-escape, dot or empty segment, and no segment ending in `.` or a
|
|
121
|
+
* space (Win32 trims those from file names). One trailing slash is dropped. A shell is only useful with a client bundle, so static
|
|
122
|
+
* mode plans none and warns instead.
|
|
123
|
+
*
|
|
124
|
+
* @param shells - The raw `ssg.shells` value; not trusted to be well-typed.
|
|
125
|
+
* @param hydrate - Whether the build emits a client bundle.
|
|
126
|
+
* @returns The jobs to write plus any errors and warnings.
|
|
127
|
+
*/
|
|
128
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"planShellJobs","stability":"experimental","signature":"(shells: unknown, hydrate: boolean) => ShellPlan"} */
|
|
129
|
+
export function planShellJobs(shells, hydrate) {
|
|
130
|
+
const plan = { jobs: [], errors: [], warnings: [] };
|
|
131
|
+
if (shells === undefined)
|
|
132
|
+
return plan;
|
|
133
|
+
if (!Array.isArray(shells)) {
|
|
134
|
+
plan.errors.push(`ssg.shells must be an array of URL paths; got ${describe(shells)}.`);
|
|
135
|
+
return plan;
|
|
136
|
+
}
|
|
137
|
+
const seen = new Map();
|
|
138
|
+
for (const raw of shells) {
|
|
139
|
+
// Strip ONE trailing slash, so `//` stays invalid rather than becoming `/`.
|
|
140
|
+
const urlPath = typeof raw === 'string' && raw.length > 1 ? raw.replace(/\/$/, '') : raw;
|
|
141
|
+
const segments = typeof urlPath === 'string' ? urlPath.split('/').slice(1) : [];
|
|
142
|
+
const valid = typeof urlPath === 'string' &&
|
|
143
|
+
urlPath.startsWith('/') &&
|
|
144
|
+
!/[?#:*%\\]/.test(urlPath) &&
|
|
145
|
+
(raw === '/' || segments.every(s => s !== '' && !/[. ]$/.test(s)));
|
|
146
|
+
if (!valid) {
|
|
147
|
+
plan.errors.push(`ssg.shells entry ${JSON.stringify(raw)} is not a literal URL path ` +
|
|
148
|
+
`such as "/app".`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
// `/app` and `/App` are one file on a case-insensitive filesystem.
|
|
152
|
+
const key = entryCollisionKey(pathToFilePath(urlPath));
|
|
153
|
+
const twin = seen.get(key);
|
|
154
|
+
if (twin === urlPath)
|
|
155
|
+
continue;
|
|
156
|
+
if (twin !== undefined) {
|
|
157
|
+
plan.errors.push(`ssg.shells entries "${twin}" and "${urlPath}" write the same file.`);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
seen.set(key, urlPath);
|
|
161
|
+
plan.jobs.push({ path: urlPath, entry: pathToFilePath(urlPath) });
|
|
162
|
+
}
|
|
163
|
+
if (!hydrate && plan.jobs.length > 0) {
|
|
164
|
+
plan.warnings.push(`ssg.shells (${plan.jobs.map(j => j.path).join(', ')}) ignored: a shell ` +
|
|
165
|
+
`is empty until JavaScript runs, so it is written only with --hydrate.`);
|
|
166
|
+
plan.jobs = [];
|
|
167
|
+
}
|
|
168
|
+
return plan;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Render one SPA shell: head, every stylesheet, the module script, an empty
|
|
172
|
+
* app root and no hydration state, so `bootstrap()` mounts fresh.
|
|
173
|
+
*
|
|
174
|
+
* Links stay absolute (`linkBase: null`, as for the 404): one shell answers
|
|
175
|
+
* every URL under its path, at any depth. Relative `href`/`src` in the head's
|
|
176
|
+
* links and scripts are resolved against `base`, as the root `index.html` they
|
|
177
|
+
* came from would; with a `<base>` in the head they are left alone, with a
|
|
178
|
+
* warning. The head gets `robots: noindex` unless it sets robots itself: a
|
|
179
|
+
* shell has no content and answers arbitrary URLs.
|
|
180
|
+
*
|
|
181
|
+
* @param htmlShellFn - `htmlShell` from `@pithyjs/ssr/server`.
|
|
182
|
+
* @param options - See {@link ShellDocumentOptions}.
|
|
183
|
+
* @returns The document as it will be written.
|
|
184
|
+
*/
|
|
185
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"renderShellDocument","stability":"experimental","signature":"(htmlShellFn: (options: ShellOptions) => string, options: ShellDocumentOptions) => FinalizePageResult"} */
|
|
186
|
+
export function renderShellDocument(htmlShellFn, options) {
|
|
187
|
+
// A shell answers at any depth, so its URLs cannot be depth-relative like a
|
|
188
|
+
// page's; they carry the deployment prefix instead.
|
|
189
|
+
const base = options.base || '/';
|
|
190
|
+
const underBase = (u) => base + u.replace(/^\//, '');
|
|
191
|
+
const html = htmlShellFn({
|
|
192
|
+
html: '',
|
|
193
|
+
head: withRobotsNoindex(absolutiseHeadUrls(options.head, base, options.headBase || '/')),
|
|
194
|
+
state: undefined,
|
|
195
|
+
scripts: options.scripts.map(underBase),
|
|
196
|
+
styles: options.styles.map(underBase),
|
|
197
|
+
appId: options.appId,
|
|
198
|
+
});
|
|
199
|
+
return finalizeForOutput(html, { linkBase: null }, { relativeLinks: false, hydrate: true, sprite: options.sprite });
|
|
200
|
+
}
|
|
201
|
+
/** A URL a browser would resolve against the request rather than the origin. */
|
|
202
|
+
function isRelativeUrl(url) {
|
|
203
|
+
return !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url);
|
|
204
|
+
}
|
|
205
|
+
function resolveAgainstBase(url, base) {
|
|
206
|
+
// A CDN base (`https://cdn.example/`) keeps its origin; a path base does not.
|
|
207
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(base))
|
|
208
|
+
return new URL(url, base).href;
|
|
209
|
+
const resolved = new URL(url, new URL(base, 'http://shell.invalid/'));
|
|
210
|
+
return resolved.pathname + resolved.search + resolved.hash;
|
|
211
|
+
}
|
|
212
|
+
/** Resolve the head's relative link/script URLs against `base`. */
|
|
213
|
+
function absolutiseHeadUrls(head, base, headBase) {
|
|
214
|
+
const relative = [
|
|
215
|
+
...head.link.map(l => l.href),
|
|
216
|
+
...head.script.flatMap(sc => (sc.src ? [sc.src] : [])),
|
|
217
|
+
].filter(u => u !== '' && isRelativeUrl(u));
|
|
218
|
+
const keepRelative = relative.length > 0 && head.base !== undefined;
|
|
219
|
+
if (keepRelative) {
|
|
220
|
+
console.warn(` WARN SPA shell: the head sets <base>, so relative URLs ` +
|
|
221
|
+
`(${relative.join(', ')}) are left as written and resolve against it.`);
|
|
222
|
+
}
|
|
223
|
+
// Root-absolute URLs already carry `headBase`; move them onto `base`.
|
|
224
|
+
const fix = (u) => {
|
|
225
|
+
if (!u)
|
|
226
|
+
return u;
|
|
227
|
+
if (isRelativeUrl(u))
|
|
228
|
+
return keepRelative ? u : resolveAgainstBase(u, base);
|
|
229
|
+
if (u.startsWith(headBase) && !u.startsWith('//'))
|
|
230
|
+
return base + u.slice(headBase.length);
|
|
231
|
+
return u;
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
...head,
|
|
235
|
+
link: head.link.map(l => ({ ...l, href: fix(l.href) })),
|
|
236
|
+
script: head.script.map(sc => (sc.src ? { ...sc, src: fix(sc.src) } : sc)),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function withRobotsNoindex(head) {
|
|
240
|
+
if (head.meta.some(m => m.name?.toLowerCase() === 'robots'))
|
|
241
|
+
return head;
|
|
242
|
+
return {
|
|
243
|
+
...head,
|
|
244
|
+
meta: [...head.meta, { name: 'robots', content: 'noindex' }],
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Drop the static paths a shell serves: its own path and, unless it is the
|
|
249
|
+
* root shell, every URL path below it, compared as written (one trailing slash
|
|
250
|
+
* ignored). Such routes need no `prerender = false` of their own. A path that
|
|
251
|
+
* only folds onto the shell's file (`/App`) is kept, and the entry check in
|
|
252
|
+
* {@link claimShellEntries} reports it.
|
|
253
|
+
* A path whose config says `prerender = true` contradicts the shell and is an
|
|
254
|
+
* error.
|
|
255
|
+
*
|
|
256
|
+
* @param staticPaths - Every literal path `collectStaticPaths()` found.
|
|
257
|
+
* @param shells - Planned shells, see {@link planShellJobs}.
|
|
258
|
+
* @param forced - Paths whose route config sets `prerender = true`.
|
|
259
|
+
*/
|
|
260
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"excludeShellPaths","stability":"experimental","signature":"(staticPaths: readonly string[], shells: readonly ShellJob[], forced: ReadonlySet<string>) => ShellExclusion"} */
|
|
261
|
+
export function excludeShellPaths(staticPaths, shells, forced) {
|
|
262
|
+
const result = { kept: [], skipped: [], errors: [] };
|
|
263
|
+
const covers = (urlPath, shell) => urlPath === shell.path ||
|
|
264
|
+
(shell.path !== '/' && urlPath.startsWith(`${shell.path}/`));
|
|
265
|
+
for (const routePath of staticPaths) {
|
|
266
|
+
const urlPath = routePath.length > 1 ? routePath.replace(/\/$/, '') : routePath;
|
|
267
|
+
const cover = shells.find(shell => covers(urlPath, shell));
|
|
268
|
+
if (!cover) {
|
|
269
|
+
result.kept.push(routePath);
|
|
270
|
+
}
|
|
271
|
+
else if (forced.has(routePath)) {
|
|
272
|
+
result.errors.push(`Page "${routePath}" sets \`prerender = true\` but SPA shell ` +
|
|
273
|
+
`"${cover.path}" serves it. Drop one of the two.`);
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
result.skipped.push(routePath);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return result;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Decide which shells may be written, given the entries the pages already
|
|
283
|
+
* wrote (keyed by `entryCollisionKey`). A shell is refused when a page owns its
|
|
284
|
+
* file (`/App` against `/app` on a case-insensitive filesystem) or when the app
|
|
285
|
+
* ships that file in `public/`, which the shell would overwrite. Claimed shells
|
|
286
|
+
* are registered in `owners`, which this mutates.
|
|
287
|
+
*
|
|
288
|
+
* @param shells - Planned shells, see {@link planShellJobs}.
|
|
289
|
+
* @param owners - Entries written so far.
|
|
290
|
+
* @param isAuthored - Whether `public/` holds a file at an entry.
|
|
291
|
+
*/
|
|
292
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"claimShellEntries","stability":"experimental","signature":"(shells: readonly ShellJob[], owners: Map<string, EntryOwner>, isAuthored: (entry: string) => boolean) => { claimed: ShellJob[]; errors: string[] }"} */
|
|
293
|
+
export function claimShellEntries(shells, owners, isAuthored) {
|
|
294
|
+
const claimed = [];
|
|
295
|
+
const errors = [];
|
|
296
|
+
for (const shell of shells) {
|
|
297
|
+
const key = entryCollisionKey(shell.entry);
|
|
298
|
+
const owner = owners.get(key);
|
|
299
|
+
if (owner !== undefined) {
|
|
300
|
+
errors.push(`SPA shell "${shell.path}" and page "${owner.path}" both write to ` +
|
|
301
|
+
`"${owner.entry}".`);
|
|
302
|
+
}
|
|
303
|
+
else if (isAuthored(shell.entry)) {
|
|
304
|
+
errors.push(`SPA shell "${shell.path}" would overwrite ${shell.entry}, which ` +
|
|
305
|
+
`the client build copied from publicDir. Remove the file or drop the shell.`);
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
owners.set(key, { path: shell.path, entry: shell.entry });
|
|
309
|
+
claimed.push(shell);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return { claimed, errors };
|
|
313
|
+
}
|
|
92
314
|
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"copyPublicAssets","stability":"experimental","signature":"(publicDir: string | false | undefined, outDir: string) => string[]"} */
|
|
93
315
|
/**
|
|
94
316
|
* Copy the app's public directory into the output.
|
|
@@ -163,12 +385,7 @@ export function copyPublicAssets(publicDir, outDir) {
|
|
|
163
385
|
export function withNotFoundRobots(head, job) {
|
|
164
386
|
if (job.linkBase !== null)
|
|
165
387
|
return head;
|
|
166
|
-
|
|
167
|
-
return head;
|
|
168
|
-
return {
|
|
169
|
-
...head,
|
|
170
|
-
meta: [...head.meta, { name: 'robots', content: 'noindex' }],
|
|
171
|
-
};
|
|
388
|
+
return withRobotsNoindex(head);
|
|
172
389
|
}
|
|
173
390
|
/**
|
|
174
391
|
* Finalize a rendered page for the URL(s) it will be SERVED at.
|
|
@@ -374,8 +591,10 @@ export async function buildClientBundle(root, outDir, entryClient) {
|
|
|
374
591
|
// It must sit inside the project — see createClientConfigDir().
|
|
375
592
|
const tempConfigDir = createClientConfigDir(root);
|
|
376
593
|
const tempConfigPath = path.resolve(tempConfigDir, 'client.config.mjs');
|
|
594
|
+
const resolvedPath = path.resolve(tempConfigDir, 'resolved.json');
|
|
377
595
|
const entryClientAbs = path.resolve(root, entryClient).replace(/\\/g, '/');
|
|
378
596
|
const outDirAbs = outDir.replace(/\\/g, '/');
|
|
597
|
+
let resolved = {};
|
|
379
598
|
// Opened immediately after the directory exists, not just around the build:
|
|
380
599
|
// anything that throws in between would otherwise strand the generated
|
|
381
600
|
// config inside the user's project.
|
|
@@ -384,6 +603,8 @@ export async function buildClientBundle(root, outDir, entryClient) {
|
|
|
384
603
|
fs.writeFileSync(tempConfigPath, `
|
|
385
604
|
import { loadConfigFromFile, mergeConfig } from 'vite';
|
|
386
605
|
|
|
606
|
+
import { writeFileSync } from 'node:fs';
|
|
607
|
+
|
|
387
608
|
const root = ${JSON.stringify(root.replace(/\\/g, '/'))};
|
|
388
609
|
const loaded = await loadConfigFromFile(
|
|
389
610
|
{ command: 'build', mode: 'production' },
|
|
@@ -395,6 +616,18 @@ const appConfig = loaded?.config ?? {};
|
|
|
395
616
|
|
|
396
617
|
// Take everything from app config, override build
|
|
397
618
|
export default mergeConfig(appConfig, {
|
|
619
|
+
plugins: [
|
|
620
|
+
{
|
|
621
|
+
name: 'pithy-ssg:record-config',
|
|
622
|
+
configResolved(config) {
|
|
623
|
+
writeFileSync(${JSON.stringify(resolvedPath.replace(/\\/g, '/'))}, JSON.stringify({
|
|
624
|
+
base: config.base,
|
|
625
|
+
publicDir: config.publicDir,
|
|
626
|
+
copyPublicDir: config.build.copyPublicDir,
|
|
627
|
+
}));
|
|
628
|
+
},
|
|
629
|
+
},
|
|
630
|
+
],
|
|
398
631
|
build: {
|
|
399
632
|
outDir: ${JSON.stringify(outDirAbs)},
|
|
400
633
|
emptyOutDir: true,
|
|
@@ -409,6 +642,9 @@ export default mergeConfig(appConfig, {
|
|
|
409
642
|
cwd: root,
|
|
410
643
|
stdio: 'inherit',
|
|
411
644
|
});
|
|
645
|
+
if (fs.existsSync(resolvedPath)) {
|
|
646
|
+
resolved = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8'));
|
|
647
|
+
}
|
|
412
648
|
}
|
|
413
649
|
finally {
|
|
414
650
|
// Clean up the generated config and Vite's .timestamp-*.mjs sidecars
|
|
@@ -433,7 +669,7 @@ export default mergeConfig(appConfig, {
|
|
|
433
669
|
` Tried keys: "${entryClientAbs}", "${relativeKey}", isEntry fallback\n` +
|
|
434
670
|
` Available keys: ${Object.keys(manifest).join(', ')}`);
|
|
435
671
|
}
|
|
436
|
-
const result = {};
|
|
672
|
+
const result = { ...resolved };
|
|
437
673
|
result.script = entry.file;
|
|
438
674
|
const jsSize = (fs.statSync(path.resolve(outDir, entry.file)).size / 1024).toFixed(1);
|
|
439
675
|
console.log(`\n Client JS: ${result.script} (${jsSize} KB)`);
|
|
@@ -748,6 +984,12 @@ async function runBuildSSG(options) {
|
|
|
748
984
|
console.log('Loading app configuration...');
|
|
749
985
|
const configMod = await vite.ssrLoadModule(configPath);
|
|
750
986
|
const config = configMod.default ?? {};
|
|
987
|
+
const shellPlan = planShellJobs(config.ssg?.shells, hydrate);
|
|
988
|
+
for (const warning of shellPlan.warnings)
|
|
989
|
+
console.warn(` WARN ${warning}`);
|
|
990
|
+
for (const message of shellPlan.errors) {
|
|
991
|
+
buildFailures.push({ stage: 'spa-shell', error: new Error(message) });
|
|
992
|
+
}
|
|
751
993
|
console.log('Loading route manifest...');
|
|
752
994
|
const routesMod = await vite.ssrLoadModule('virtual:pithy/routes.gen');
|
|
753
995
|
const routes = routesMod.routes;
|
|
@@ -801,7 +1043,26 @@ async function runBuildSSG(options) {
|
|
|
801
1043
|
console.log(`Registered icon sprite (${sprite.symbols.size} symbols).`);
|
|
802
1044
|
}
|
|
803
1045
|
// ── Discover static routes ──
|
|
804
|
-
const
|
|
1046
|
+
const forced = new Set();
|
|
1047
|
+
const collected = await collectStaticPaths(routes);
|
|
1048
|
+
if (shellPlan.jobs.length > 0) {
|
|
1049
|
+
for (const routePath of collected) {
|
|
1050
|
+
const loadConfig = findRouteByPattern(routes, routePath)?.imports
|
|
1051
|
+
.config;
|
|
1052
|
+
const routeConfig = await loadConfig?.().catch(() => undefined);
|
|
1053
|
+
if (routeConfig?.prerender === true)
|
|
1054
|
+
forced.add(routePath);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
const shellPaths = excludeShellPaths(collected, shellPlan.jobs, forced);
|
|
1058
|
+
for (const message of shellPaths.errors) {
|
|
1059
|
+
console.log(` FAIL ${message}`);
|
|
1060
|
+
buildFailures.push({ stage: 'spa-shell', error: new Error(message) });
|
|
1061
|
+
}
|
|
1062
|
+
if (shellPaths.skipped.length > 0) {
|
|
1063
|
+
console.log(`Served by an SPA shell: ${shellPaths.skipped.join(', ')}`);
|
|
1064
|
+
}
|
|
1065
|
+
const staticPaths = shellPaths.kept;
|
|
805
1066
|
console.log(`Found ${staticPaths.length} static paths to render.\n`);
|
|
806
1067
|
// `collectStaticPaths()` excludes catch-all routes by design, and that stays
|
|
807
1068
|
// — a catch-all has no literal path of its own to be written at. The
|
|
@@ -1007,9 +1268,11 @@ async function runBuildSSG(options) {
|
|
|
1007
1268
|
}
|
|
1008
1269
|
// Asked of `publicDir` itself, not of the copied output: in hydrate mode
|
|
1009
1270
|
// Vite's own client build does the copying, so nothing here would see it.
|
|
1010
|
-
const
|
|
1011
|
-
|
|
1012
|
-
|
|
1271
|
+
const publicCopy = publicCopySource(hydrate, clientBuild, {
|
|
1272
|
+
publicDir: vite.config.publicDir,
|
|
1273
|
+
copyPublicDir: vite.config.build.copyPublicDir,
|
|
1274
|
+
});
|
|
1275
|
+
const hasAuthoredNotFound = isAuthoredPublicFile(publicCopy, NOT_FOUND_OUTPUT.entry);
|
|
1013
1276
|
let notFoundEntry = null;
|
|
1014
1277
|
console.log('\nWriting portable static files...');
|
|
1015
1278
|
const entryOwners = new Map();
|
|
@@ -1080,6 +1343,38 @@ async function runBuildSSG(options) {
|
|
|
1080
1343
|
rendered.push(routePath);
|
|
1081
1344
|
}
|
|
1082
1345
|
}
|
|
1346
|
+
const shells = [];
|
|
1347
|
+
const shellClaim = claimShellEntries(shellPlan.jobs, entryOwners, entry => isAuthoredPublicFile(publicCopy, entry));
|
|
1348
|
+
const shellBase = clientBuild.base ?? '/';
|
|
1349
|
+
// A relative base cannot resolve at every depth a shell answers.
|
|
1350
|
+
if (shellClaim.claimed.length > 0 &&
|
|
1351
|
+
!/^(?:\/|[a-z][a-z\d+.-]*:)/i.test(shellBase)) {
|
|
1352
|
+
shellClaim.errors.push(`SPA shells need an absolute Vite \`base\`; the client build uses ` +
|
|
1353
|
+
`${JSON.stringify(shellBase)}.`);
|
|
1354
|
+
shellClaim.claimed = [];
|
|
1355
|
+
}
|
|
1356
|
+
for (const message of shellClaim.errors) {
|
|
1357
|
+
console.log(` FAIL ${message}`);
|
|
1358
|
+
buildFailures.push({ stage: 'spa-shell', error: new Error(message) });
|
|
1359
|
+
}
|
|
1360
|
+
for (const shell of shellClaim.claimed) {
|
|
1361
|
+
const { html: shellHtml } = renderShellDocument(htmlShellFn, {
|
|
1362
|
+
head: resolvePageHead(shellHead, {}, {}),
|
|
1363
|
+
scripts,
|
|
1364
|
+
styles,
|
|
1365
|
+
// The PRODUCTION base: the serve-mode one drops a CDN origin and
|
|
1366
|
+
// ignores a base that depends on the command or mode.
|
|
1367
|
+
base: shellBase,
|
|
1368
|
+
headBase: vite.config.base,
|
|
1369
|
+
appId: config.appId,
|
|
1370
|
+
sprite,
|
|
1371
|
+
});
|
|
1372
|
+
const absFile = path.resolve(outDir, shell.entry);
|
|
1373
|
+
fs.mkdirSync(path.dirname(absFile), { recursive: true });
|
|
1374
|
+
fs.writeFileSync(absFile, shellHtml, 'utf-8');
|
|
1375
|
+
console.log(` ${shell.path} -> ${shell.entry} (SPA shell)`);
|
|
1376
|
+
shells.push(shell.entry);
|
|
1377
|
+
}
|
|
1083
1378
|
const totalTime = performance.now() - startTime;
|
|
1084
1379
|
const totalTimeSec = (totalTime / 1000).toFixed(2);
|
|
1085
1380
|
console.log(`\n--- Results ---`);
|
|
@@ -1099,6 +1394,9 @@ async function runBuildSSG(options) {
|
|
|
1099
1394
|
if (notFoundEntry) {
|
|
1100
1395
|
console.log(` Not found: ${notFoundEntry}`);
|
|
1101
1396
|
}
|
|
1397
|
+
if (shells.length > 0) {
|
|
1398
|
+
console.log(` Shells: ${shells.join(', ')}`);
|
|
1399
|
+
}
|
|
1102
1400
|
reportLayoutDiagnostics();
|
|
1103
1401
|
console.log(` Failed: ${failed.length}`);
|
|
1104
1402
|
console.log(` Time: ${totalTimeSec}s`);
|
|
@@ -1131,6 +1429,7 @@ async function runBuildSSG(options) {
|
|
|
1131
1429
|
return {
|
|
1132
1430
|
rendered,
|
|
1133
1431
|
notFound: notFoundEntry,
|
|
1432
|
+
shells,
|
|
1134
1433
|
failed,
|
|
1135
1434
|
buildFailures,
|
|
1136
1435
|
totalTime,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-ssg.js","sourceRoot":"","sources":["../../src/build/vite-ssg.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EA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I,MAAM,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YACjD,CAAC;YACD,oEAAoE;YACpE,mEAAmE;YACnE,kEAAkE;YAClE,qEAAqE;YACrE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClB,CAAC;QAED,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC7B,qEAAqE;YACrE,yEAAyE;YACzE,OAAO,CAAC,KAAK,CAAC,iDAAiD,CAAC,CAAC;YACjE,KAAK,MAAM,CAAC,IAAI,aAAa,EAAE,CAAC;gBAC9B,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YACpD,CAAC;YACD,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACpB,CAAC;QAED,OAAO;YACL,QAAQ;YACR,QAAQ,EAAE,aAAa;YACvB,MAAM;YACN,aAAa;YACb,SAAS;SACV,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,sEAAsE;QACtE,2EAA2E;QAC3E,2EAA2E;QAC3E,gEAAgE;QAChE,MAAM,iBAAiB,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC9C,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.build.vite-ssg\",\n \"title\": \"Vite-integrated SSG Build Orchestrator\",\n \"category\": \"feature\",\n \"risk\": \"critical\"\n}\n*/\n\n/**\n * Vite-integrated SSG Build Orchestrator\n *\n * Provides `buildSSG()` — a single function that apps call to produce\n * a fully portable static site with optional client-side hydration.\n *\n * The framework handles everything internally:\n * - Loads pithy.config.ts for app configuration\n * - Auto-discovers routes from the virtual route manifest\n * - Renders the App shell and injects page content\n * - Collects CSS from the Vite module graph, and in static mode purges the\n * rules no rendered page uses (see `css-purge.ts`)\n * - Registers the app's icon sprite and inlines the symbols each page uses\n * (both modes — a prerendered document must stand on its own before any\n * client JS runs)\n * - Builds the client JS bundle for hydration mode\n *\n * Apps need zero entry files — just `pithy.config.ts` at the root.\n *\n * Usage:\n * pithy-ssg — static HTML only (no JS)\n * pithy-ssg --hydrate — static HTML + client JS\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { execFileSync } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport {\n inlineSpriteIntoHtml,\n type SpriteBundle,\n} from '@pithyjs/shared/sprite';\nimport type { RouteNode } from '@pithyjs/router';\nimport type { HeadState } from '../shared/types.js';\nimport { collectCss } from './collect-css.js';\nimport { purgeCssForPages } from './css-purge.js';\nimport {\n purgeDeadCustomProps,\n collectHtmlSources,\n asSafelistArray,\n} from './css-live-props.js';\nimport { makeLinksRelative } from './relative-links.js';\nimport { NOT_FOUND_OUTPUT, hasRenderedText } from './not-found.js';\nimport { loadSpriteForSsg, clearSpriteForSsg } from './sprite-ssg.js';\nimport { readShellHead, resolvePageHead } from './shell-head.js';\nimport {\n injectIntoOutlet,\n pathToFilePath,\n wrapInLayouts,\n} from '../shared/shell-helpers.js';\nimport { entryCollisionKey } from '../shared/entry-path.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface SSGBuildResult {\n /**\n * Successfully rendered ROUTE paths. Excludes the not-found document, which\n * has no route path of its own — see {@link SSGBuildResult.notFound}.\n */\n rendered: string[];\n /**\n * Entry the site-wide not-found document was written to (`404.html`), or\n * `null` when none was emitted — no top-level catch-all, a catch-all that\n * rendered no content, or a hand-authored `public/404.html` that won.\n */\n notFound: string | null;\n failed: Array<{ path: string; error: Error }>;\n /**\n * Failures that belong to the export as a whole rather than to one route.\n *\n * Separate from {@link SSGBuildResult.failed} because the two deserve\n * different answers: a failed route costs one page and `--allow-partial` can\n * waive it, whereas a failed design-system stylesheet unstyles every page\n * that was written and nothing can. Both are reported; only the first is\n * waivable.\n *\n * Recorded here rather than thrown so the pages still get written —\n * `collectCss()` runs before the first file is written, so a throw would turn\n * a CSS problem into an empty output directory.\n */\n buildFailures: Array<{ stage: string; error: Error }>;\n totalTime: number;\n}\n\nexport interface BuildSSGOptions {\n /** App root directory (default: process.cwd()) */\n root?: string;\n /** Output directory relative to root (default: 'out') */\n outDir?: string;\n /** Build client JS and enable hydration (default: false) */\n hydrate?: boolean;\n /** Path to pithy.config as Vite module ID (default: '/pithy.config') */\n configPath?: string;\n /** Path to client entry relative to root (default: 'src/main.ts') */\n entryClient?: string;\n /**\n * Convert absolute links to relative for portability (default: true).\n *\n * In static mode: all links (routes + assets) are rewritten to relative\n * paths, making the output fully file:// compatible.\n *\n * In hydrate mode: only asset URLs (.css, .js, etc.) are rewritten;\n * route links (/about, /dashboard) stay absolute so the client router\n * can match them. This means hydrate output requires a static file server\n * (e.g. `npx serve`) and is NOT file:// compatible.\n */\n relativeLinks?: boolean;\n /**\n * Document title for pages that set none.\n *\n * Overrides the `<title>` read from the app's HTML shell; a `head()` call in\n * a layout or page still wins over both.\n */\n title?: string;\n}\n\n/** What {@link buildClientBundle} found in the client build's Vite manifest. */\nexport interface ClientBuildResult {\n /** Relative path to client JS (e.g., 'assets/main-abc123.js') */\n script?: string;\n /** Relative paths to extracted CSS files */\n css?: string[];\n}\n\n// Re-export pathToFilePath for test access (canonical definition in shell-helpers)\nexport { pathToFilePath } from '../shared/shell-helpers.js';\n\n// Canonical in `./not-found.js`, so `generateStaticSite()` and `buildSSG()`\n// cannot drift apart. Re-exported here because this is the module the build\n// entry point and the tests address.\nexport { NOT_FOUND_OUTPUT, hasRenderedText };\n\n/** One route {@link buildSSG}'s render loop renders and writes. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"RenderJob\",\"stability\":\"experimental\",\"signature\":\"interface RenderJob\"} */\nexport interface RenderJob {\n /** URL to render the page at (a real route path, or the 404 job's synthetic {@link NOT_FOUND_OUTPUT.renderPath}). */\n routePath: string;\n /** Route matched for `routePath`, or absent if none was found. */\n routeNode: RouteNode | null | undefined;\n /** Output file relative to `outDir`. */\n entry: string;\n /**\n * Path `makeLinksRelative()` derives its `../` depth from, or `null` when the\n * document has no fixed depth and must keep ABSOLUTE URLs.\n *\n * A browser resolves relative URLs against the REQUEST url, not against where\n * the file sits in `outDir`. An ordinary page is served at exactly one URL, so\n * a relative base is correct for it. The 404 is served at EVERY unmatched URL,\n * at every depth, so no relative base can be — `assets/x.css` in a document\n * answered for `/docs/whatever` resolves to `/docs/assets/x.css` and 404s.\n */\n linkBase: string | null;\n}\n\n/**\n * Build the list of pages {@link buildSSG} renders and writes, in emission order.\n *\n * Extracted as a pure, side-effect-free seam because this is the exact wiring\n * BUG-015 got wrong three times before it shipped: the `linkBase` a job carries,\n * the `entry` filename it writes to, and whether a 404 job is appended at all\n * are three independent decisions that nothing but a real `pithy-ssg --hydrate`\n * run used to exercise. `findRouteByPattern` is injected rather than looked up\n * here so a fake tree can stand in for the real route module in a unit test —\n * no `ssrLoadModule`, no Vite server.\n *\n * The not-found job, when `notFoundRoute` is present, is always appended LAST.\n * Its `entry` lands at the output root rather than nested like every ordinary\n * page, so it must not shift collision-detection order for the paths ahead of\n * it. No `notFoundRoute` (the app has no top-level catch-all) is a complete\n * no-op — no job appended, nothing written, build still exits 0.\n *\n * @param staticPaths - Every literal path `collectStaticPaths()` found.\n * @param notFoundRoute - The app's top-level catch-all, or null/undefined if\n * it has none. See {@link findRootCatchAllRoute} in `ssg.ts`.\n * @param findRouteByPattern - Resolves a route path to its `RouteNode`.\n */\n/** @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[]\"} */\nexport function planRenderJobs(\n staticPaths: string[],\n notFoundRoute: RouteNode | null | undefined,\n findRouteByPattern: (routePath: string) => RouteNode | null | undefined\n): RenderJob[] {\n const renderJobs: RenderJob[] = staticPaths.map(routePath => ({\n routePath,\n routeNode: findRouteByPattern(routePath),\n entry: pathToFilePath(routePath),\n linkBase: routePath,\n }));\n\n if (notFoundRoute) {\n renderJobs.push({\n routePath: NOT_FOUND_OUTPUT.renderPath,\n routeNode: notFoundRoute,\n entry: NOT_FOUND_OUTPUT.entry,\n linkBase: NOT_FOUND_OUTPUT.linkBase,\n });\n }\n\n return renderJobs;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"copyPublicAssets\",\"stability\":\"experimental\",\"signature\":\"(publicDir: string | false | undefined, outDir: string) => string[]\"} */\n/**\n * Copy the app's public directory into the output.\n *\n * Hydrate output gets this for free — the client `vite build` writes into the\n * same `outDir` and copies `publicDir` itself. Static mode runs no client\n * build, so it emitted a document referencing a favicon it never shipped.\n *\n * Call before the pages are written: a page and a public file that resolve to\n * the same path should end with the rendered page, not the raw asset.\n *\n * Walks with `statSync`, which follows symlinks as Vite's own `copyDir` does:\n * a `Dirent` reports a symlink as neither file nor directory, so a linked\n * asset would be dropped and its document reference would 404.\n *\n * Following them is what makes the two guards necessary. Directories are\n * compared by real path, so an `outDir` inside `publicDir` is skipped whether\n * it is reached directly or through a link, and the chain of real paths\n * already open is carried down so a cycle — `public/loop -> public` — ends the\n * branch instead of recursing until the filesystem refuses. The chain is per\n * branch, not global: the same directory linked from two places is legitimate\n * content and is copied to both.\n *\n * @param publicDir - Vite's resolved `publicDir` (`false` when disabled).\n * @param outDir - Directory the build writes into.\n * @returns Paths copied, relative to `publicDir`.\n */\nexport function copyPublicAssets(\n publicDir: string | false | undefined,\n outDir: string\n): string[] {\n if (!publicDir || !fs.existsSync(publicDir)) return [];\n\n const outReal = fs.existsSync(outDir)\n ? fs.realpathSync(outDir)\n : path.resolve(outDir);\n const copied: string[] = [];\n const walk = (dir: string, rel: string, open: ReadonlySet<string>): void => {\n for (const name of fs.readdirSync(dir)) {\n const from = path.resolve(dir, name);\n const relPath = rel ? `${rel}/${name}` : name;\n if (fs.statSync(from).isDirectory()) {\n const real = fs.realpathSync(from);\n if (real === outReal || open.has(real)) continue;\n fs.mkdirSync(path.resolve(outDir, relPath), { recursive: true });\n walk(from, relPath, new Set(open).add(real));\n } else {\n const to = path.resolve(outDir, relPath);\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.copyFileSync(from, to);\n copied.push(relPath);\n }\n }\n };\n walk(publicDir, '', new Set([fs.realpathSync(publicDir)]));\n return copied;\n}\n\n// =============================================================================\n// Page finalization\n// =============================================================================\n\n/** Inputs to {@link finalizePageHtml}. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"FinalizePageOptions\",\"stability\":\"experimental\",\"signature\":\"interface FinalizePageOptions\"} */\nexport interface FinalizePageOptions {\n /** Rewrite absolute links to relative (see {@link BuildSSGOptions.relativeLinks}). */\n relativeLinks: boolean;\n /**\n * Hydrate mode. Narrows the relative-link rewrite to assets only, so route\n * links stay absolute for the client router. It does **not** gate sprite\n * inlining — see {@link finalizePageHtml}.\n */\n hydrate: boolean;\n /** The app's icon sprite, or the empty bundle. */\n sprite: SpriteBundle;\n}\n\n/** Result of {@link finalizePageHtml}. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"FinalizePageResult\",\"stability\":\"experimental\",\"signature\":\"interface FinalizePageResult\"} */\nexport interface FinalizePageResult {\n /** The document as it will be written to disk. */\n html: string;\n /** Icon names referenced against the sprite that it does not define. */\n missingIcons: string[];\n}\n\n/**\n * Keep the generated not-found document out of search indexes.\n *\n * `404.html` is a real, crawlable URL — a host that serves it for unmatched\n * paths also serves it at `/404.html` — and it inherits the shell's `<title>`,\n * so left alone it gets indexed as a duplicate of the home page.\n *\n * Only the generated 404 is touched (`linkBase === null` identifies it), and\n * only when the page has said nothing about robots itself: an app that sets its\n * own directive has made a decision, and this is not the place to overrule it.\n *\n * The title is deliberately left alone. `noindex` removes the search-result\n * problem, and the tab title belongs to the catch-all page, which can set it.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"withNotFoundRobots\",\"stability\":\"internal\",\"signature\":\"(head: HeadState, job: Pick<RenderJob, 'linkBase'>) => HeadState\"} */\nexport function withNotFoundRobots(\n head: HeadState,\n job: Pick<RenderJob, 'linkBase'>\n): HeadState {\n if (job.linkBase !== null) return head;\n if (head.meta.some(m => m.name?.toLowerCase() === 'robots')) return head;\n\n return {\n ...head,\n meta: [...head.meta, { name: 'robots', content: 'noindex' }],\n };\n}\n\n/**\n * Finalize a rendered page for the URL(s) it will be SERVED at.\n *\n * Takes the JOB, not a path, and reads `linkBase` from it. That is deliberate:\n * an earlier shape took `{ path, linkPath }`, where `path` was never read and\n * existed only to be swapped in — so the mutation this seam was added to close\n * survived it, one token to the right, with 951 tests still green. Passing the\n * already-tested `planRenderJobs` output leaves nothing to swap.\n *\n * `linkBase: null` means the document has no fixed depth — the 404, served at\n * every unmatched URL — so relativisation is DISABLED for it regardless of the\n * caller's `relativeLinks`. Relative URLs resolve against the request, not the\n * file, so `assets/x.css` works for `/nope` and breaks for `/docs/whatever`.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"finalizeForOutput\",\"stability\":\"experimental\",\"signature\":\"(html: string, job: Pick<RenderJob, 'linkBase'>, options: FinalizePageOptions) => FinalizePageResult\"} */\nexport function finalizeForOutput(\n html: string,\n job: Pick<RenderJob, 'linkBase'>,\n options: FinalizePageOptions\n): FinalizePageResult {\n if (job.linkBase === null) {\n return finalizePageHtml(html, '/', { ...options, relativeLinks: false });\n }\n\n return finalizePageHtml(html, job.linkBase, options);\n}\n\n/**\n * Apply the last two transforms before a page is written to disk.\n *\n * Extracted from {@link buildSSG} as a pure seam, because the two properties\n * that matter here are exactly the ones an end-to-end build cannot pin in CI:\n *\n * 1. **Ordering.** Sprite inlining must run *after* `makeLinksRelative`, since\n * that is what the emitted file actually contains — `assets/icons-HASH.svg`,\n * not `/assets/…`. Asserting against the pre-rebase URL is the false negative\n * that once made this bug read as fixed.\n * 2. **Hydrate output is inlined too.** It used to be gated off, on the theory\n * that the client build emits the hashed sprite and `virtual:pithy-icons`\n * re-registers it at runtime. Both halves are true of the *client bundle*\n * and neither is true of the *prerendered document*. The app registers its\n * sprite from module scope (`registerIconSprite(SPRITE_URL, …)`), and during\n * SSG that module is loaded through the Vite **dev** server — so `SPRITE_URL`\n * is the dev virtual path `/@pithy-icons-sprite.svg`, a route that exists\n * only under `vite dev` and is never emitted by a build. Hydrate pages\n * therefore shipped `<use href=\"@pithy-icons-sprite.svg#name\">`: a 404 per\n * icon, a blank brand mark until `hydrate()` discards the DOM and re-renders,\n * and permanently blank with JS off.\n *\n * Inlining is the fix rather than rewriting the href at the hashed asset,\n * because the icon has to paint *before* any request resolves — a prerendered\n * document that needs a second round trip to show its logo has given up the\n * thing prerendering is for. It is safe on the hydrate path: the symbol block\n * is inserted at `<body>` level, outside the container `hydrate()` clears, and\n * the client re-registers the real hashed `SPRITE_URL` on boot, so\n * post-hydration `<use>` references resolve against the emitted asset.\n *\n * @param html - The assembled `htmlShell()` output for one route.\n * @param routePath - Route the page was rendered for (e.g. `/about`).\n * @param options - See {@link FinalizePageOptions}.\n * @returns The final document plus any unresolved icon names.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"finalizePageHtml\",\"stability\":\"experimental\",\"signature\":\"(html: string, routePath: string, options: FinalizePageOptions) => FinalizePageResult\"} */\nexport function finalizePageHtml(\n html: string,\n routePath: string,\n options: FinalizePageOptions\n): FinalizePageResult {\n const relativized = options.relativeLinks\n ? makeLinksRelative(html, routePath, { assetsOnly: options.hydrate })\n : html;\n\n // Run the inliner even when the bundle carries no symbols for this page.\n // Returning early on an empty bundle would suppress the *reporting* too, and\n // a page whose `<use href>` references cannot be resolved is exactly the case\n // worth hearing about: bailing silently is how a dangling reference reaches a\n // published page looking like a successful build. `urlKeys` still gates it,\n // so an app with no sprite at all does no work.\n if (options.sprite.urlKeys.size === 0) {\n return { html: relativized, missingIcons: [] };\n }\n\n const inlined = inlineSpriteIntoHtml(relativized, options.sprite);\n return { html: inlined.html, missingIcons: inlined.missing };\n}\n\n// =============================================================================\n// Client Bundle Build\n// =============================================================================\n\n/** Where the generated client config lives, relative to the app root. */\nconst CLIENT_CONFIG_DIRNAME = path.join('node_modules', '.pithy-ssg');\n\n/**\n * Create the throwaway directory the generated client config is written into.\n *\n * It has to live **inside the app**, not in `os.tmpdir()`. The config file\n * `import`s from `'vite'`, and Node resolves a module's specifiers from that\n * file's own directory, walking up for `node_modules` — the cwd of the process\n * that spawned it is irrelevant. From the OS temp dir there is no\n * `node_modules/vite` anywhere up the chain, so `--hydrate` died with\n * `ERR_MODULE_NOT_FOUND` for every app (BUG-014). Vite compounds it by\n * rewriting the config into a `.timestamp-*.mjs` sidecar in the same directory.\n *\n * `<root>/node_modules/.pithy-ssg/` reaches `<root>/node_modules` on the second\n * hop of that walk, is already ignored by every VCS, and matches the `.vite` /\n * `.cache` convention.\n *\n * @throws If the directory cannot be created — a silent fallback to a location\n * outside the project would just resurrect the original failure.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"createClientConfigDir\",\"stability\":\"internal\",\"signature\":\"(root: string) => string\"} */\nexport function createClientConfigDir(root: string): string {\n const base = path.resolve(root, CLIENT_CONFIG_DIRNAME);\n try {\n fs.mkdirSync(base, { recursive: true });\n return fs.mkdtempSync(path.join(base, 'build-'));\n } catch (error) {\n throw new Error(\n `Could not create the pithy-ssg client config directory at ${base}.\\n` +\n ` The generated Vite config must live inside the project so Node can\\n` +\n ` resolve 'vite' from it, so this cannot fall back elsewhere.\\n` +\n ` Check that ${root}/node_modules/ exists and is writable — a\\n` +\n ` read-only checkout, a permission-denied mount, or a plain file\\n` +\n ` named node_modules all land here. If it is simply missing, run\\n` +\n ` your package manager's install in the app workspace.\\n` +\n ` Cause: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n\n/**\n * Remove a directory made by {@link createClientConfigDir}.\n *\n * Recursive so Vite's `client.config.mjs.timestamp-*.mjs` sidecars — written\n * next to the config — go with it. Never throws: this runs in a `finally` and\n * must not mask a build error.\n *\n * The shared `.pithy-ssg` PARENT is deliberately left in place. Removing it when\n * it looked empty raced with a concurrently starting build: that build can be\n * between its own `mkdirSync(base)` and `mkdtempSync(base/build-*)`, at which\n * point the parent really is empty, and deleting it makes the other build fail\n * with `ENOENT` — a cleanup step breaking an unrelated build. Retrying creation\n * would narrow that window rather than close it, so the parent simply stays.\n *\n * What it costs is one empty directory under `node_modules/`, which is neither\n * user-facing nor version-controlled. That is a better trade than a build that\n * fails once in a while for a reason nobody can reproduce.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"removeClientConfigDir\",\"stability\":\"internal\",\"signature\":\"(dir: string) => void\"} */\nexport function removeClientConfigDir(dir: string): void {\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* ignore — cleanup must never mask the build result */\n }\n}\n\n/**\n * Build client JS/CSS bundle using Vite.\n *\n * Loads the app's vite.config.ts and overrides build options.\n * Uses subprocess to avoid sass resolution issues with programmatic API.\n *\n * Exported as a test seam. {@link createClientConfigDir} being correct is worth\n * nothing if this function stops calling it — a suite that only exercises the\n * helpers stays green through a revert to `mkdtemp(os.tmpdir())` right here,\n * which is the exact regression this file's header exists to prevent. The one\n * test that matters therefore drives `buildClientBundle` itself and inspects the\n * `--config` path handed to the vite binary.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"buildClientBundle\",\"stability\":\"internal\",\"signature\":\"(root: string, outDir: string, entryClient: string) => Promise<ClientBuildResult>\"} */\nexport async function buildClientBundle(\n root: string,\n outDir: string,\n entryClient: string\n): Promise<ClientBuildResult> {\n console.log('Building client bundle...\\n');\n\n // Vite's JavaScript ENTRY, run with this same Node — not the `.bin` shim.\n //\n // The shim looked simpler and is a cross-platform trap: on Windows it is\n // `vite.cmd`, and a batch file cannot be executed by `execFileSync` without\n // `shell: true` — Node refuses outright since the CVE-2024-27980 fix. So the\n // shim meant hydrate builds failed on Windows, while the alternative, turning\n // `shell: true` back on, reintroduces exactly the path-with-spaces quoting\n // problem that avoiding the shell was meant to solve.\n //\n // Running the entry with `process.execPath` needs neither: one code path, no\n // shell, no quoting, identical on every platform. It also pins the Node\n // already running this build rather than whatever a shim happens to resolve.\n //\n // Checked *before* the config directory is created, not after: this throw is\n // between the write and the `try`/`finally` that cleans it up, so a missing\n // install used to leave `node_modules/.pithy-ssg/build-XXXX/client.config.mjs`\n // sitting in the user's project. Failing first costs one `existsSync`.\n // Resolved through Node's OWN algorithm, not a hardcoded path.\n //\n // `<root>/node_modules/vite/bin/vite.js` only exists under a nested layout.\n // With pnpm's `node-linker=hoisted`, `shamefully-hoist`, or any hoisting\n // package manager, Vite is installed and importable while that exact directory\n // is absent — so probing it with `existsSync` aborts the build telling the\n // user to install something they already have. `createRequire` finds it\n // wherever the layout put it, and reading `bin.vite` from the manifest also\n // survives Vite renaming its own entry file.\n let viteEntry: string;\n try {\n const requireFromApp = createRequire(path.join(root, 'noop.js'));\n const pkgPath = requireFromApp.resolve('vite/package.json');\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as {\n bin?: string | Record<string, string>;\n };\n const binField =\n typeof pkg.bin === 'string' ? pkg.bin : (pkg.bin?.vite ?? 'bin/vite.js');\n viteEntry = path.resolve(path.dirname(pkgPath), binField);\n } catch (cause) {\n throw new Error(\n `Vite could not be resolved from ${root}.\\n` +\n ` Install it in the app workspace: pnpm add -D vite\\n` +\n ` Cause: ${cause instanceof Error ? cause.message : String(cause)}`\n );\n }\n\n if (!fs.existsSync(viteEntry)) {\n throw new Error(\n `Vite resolved to ${viteEntry}, which does not exist.\\n` +\n ` This usually means a partial install — reinstall dependencies.`\n );\n }\n\n // Generate a temp config that extends the app's config with build overrides.\n // It must sit inside the project — see createClientConfigDir().\n const tempConfigDir = createClientConfigDir(root);\n\n const tempConfigPath = path.resolve(tempConfigDir, 'client.config.mjs');\n const entryClientAbs = path.resolve(root, entryClient).replace(/\\\\/g, '/');\n const outDirAbs = outDir.replace(/\\\\/g, '/');\n\n // Opened immediately after the directory exists, not just around the build:\n // anything that throws in between would otherwise strand the generated\n // config inside the user's project.\n try {\n // Write temp config that loads the app's config and overrides build section\n fs.writeFileSync(\n tempConfigPath,\n `\nimport { loadConfigFromFile, mergeConfig } from 'vite';\n\nconst root = ${JSON.stringify(root.replace(/\\\\/g, '/'))};\nconst loaded = await loadConfigFromFile(\n { command: 'build', mode: 'production' },\n undefined,\n root\n);\n\nconst appConfig = loaded?.config ?? {};\n\n// Take everything from app config, override build\nexport default mergeConfig(appConfig, {\n build: {\n outDir: ${JSON.stringify(outDirAbs)},\n emptyOutDir: true,\n manifest: true,\n rollupOptions: {\n input: ${JSON.stringify(entryClientAbs)},\n },\n },\n});\n`,\n 'utf-8'\n );\n\n execFileSync(\n process.execPath,\n [viteEntry, 'build', '--config', tempConfigPath.replace(/\\\\/g, '/')],\n {\n cwd: root,\n stdio: 'inherit',\n }\n );\n } finally {\n // Clean up the generated config and Vite's .timestamp-*.mjs sidecars\n removeClientConfigDir(tempConfigDir);\n }\n\n // Read Vite build manifest to locate entry chunk + CSS reliably,\n // regardless of custom rollup output naming in the app's vite.config.\n const manifestPath = path.resolve(outDir, '.vite', 'manifest.json');\n if (!fs.existsSync(manifestPath)) {\n throw new Error(\n 'Client build did not produce .vite/manifest.json.\\n' +\n ' Ensure build.manifest is not explicitly disabled in vite.config.'\n );\n }\n\n const manifest: Record<\n string,\n { file: string; css?: string[]; isEntry?: boolean; src?: string }\n > = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));\n\n // Vite manifest keys are typically root-relative posix paths.\n // Try absolute path first, then relative, then fall back to isEntry lookup.\n const relativeKey = entryClient.replace(/\\\\/g, '/');\n const entry =\n manifest[entryClientAbs] ??\n manifest[relativeKey] ??\n Object.values(manifest).find(e => e.isEntry);\n if (!entry) {\n throw new Error(\n `Client build succeeded but entry not found in manifest.\\n` +\n ` Tried keys: \"${entryClientAbs}\", \"${relativeKey}\", isEntry fallback\\n` +\n ` Available keys: ${Object.keys(manifest).join(', ')}`\n );\n }\n\n const result: ClientBuildResult = {};\n\n result.script = entry.file;\n const jsSize = (\n fs.statSync(path.resolve(outDir, entry.file)).size / 1024\n ).toFixed(1);\n console.log(`\\n Client JS: ${result.script} (${jsSize} KB)`);\n\n // EVERY stylesheet the client build emitted, not only the entry's.\n //\n // `cssCodeSplit` is Vite's default, so a route's CSS lands in its own chunk\n // that `__vitePreload` fetches only AFTER the JS boots. A prerendered document\n // linking just the entry's CSS therefore paints unstyled until hydration — and\n // stays unstyled permanently with JS off, which is the exact reader the\n // prerender exists for. Static mode never had this gap because `collectCss()`\n // walked the whole module graph; switching an app to `--hydrate` silently lost\n // it, with browser checks hiding it because the chunk lands in milliseconds\n // when JS is on.\n //\n // Linking them all up front also matches what hydrate output does next: it is\n // a client-routed app after first paint, so the router would fetch these on\n // the first navigation regardless.\n //\n // Entry CSS first, so the base layer (design system, ui-kit, global styles)\n // precedes route rules in the cascade rather than depending on chunk order.\n const entryCss = entry.css ?? [];\n const routeCss = Object.values(manifest)\n .filter(chunk => chunk !== entry)\n .flatMap(chunk => chunk.css ?? []);\n const allCss = [...new Set([...entryCss, ...routeCss])];\n\n if (allCss.length > 0) {\n result.css = allCss;\n for (const cssFile of allCss) {\n const cssSize = (\n fs.statSync(path.resolve(outDir, cssFile)).size / 1024\n ).toFixed(1);\n console.log(` Client CSS: ${cssFile} (${cssSize} KB)`);\n }\n console.log('');\n } else {\n console.log(' No extracted CSS file found\\n');\n }\n\n return result;\n}\n\n// =============================================================================\n// Main SSG Build\n// =============================================================================\n\n/**\n * Layout-taint findings across the whole export, aggregated.\n *\n * Aggregated rather than reported per page: the same declaration on a component\n * used site-wide would otherwise print once per route and bury the one-off that\n * actually needs looking at.\n */\ninterface LayoutDiagnosticsAccumulator {\n dropped: Map<string, number>;\n suspicious: Map<string, string[]>;\n}\n\nconst layoutDiagnostics: LayoutDiagnosticsAccumulator = {\n dropped: new Map(),\n suspicious: new Map(),\n};\n\nfunction recordLayoutDiagnostics(\n routePath: string,\n diagnostics:\n | { droppedStyles: string[]; suspiciousGeometry: string[] }\n | undefined\n): void {\n if (!diagnostics) return;\n\n for (const declaration of diagnostics.droppedStyles) {\n layoutDiagnostics.dropped.set(\n declaration,\n (layoutDiagnostics.dropped.get(declaration) ?? 0) + 1\n );\n }\n for (const declaration of diagnostics.suspiciousGeometry) {\n const routes = layoutDiagnostics.suspicious.get(declaration) ?? [];\n routes.push(routePath);\n layoutDiagnostics.suspicious.set(declaration, routes);\n }\n}\n\n/** Print the aggregated findings once, after every page has rendered. */\nfunction reportLayoutDiagnostics(): void {\n if (layoutDiagnostics.dropped.size > 0) {\n const total = [...layoutDiagnostics.dropped.values()].reduce(\n (a, b) => a + b,\n 0\n );\n const names = [...layoutDiagnostics.dropped.keys()]\n .map(d => d.split(':')[0]?.trim())\n .filter((v, i, all) => v && all.indexOf(v) === i);\n console.log(\n ` Layout: dropped ${total} measurement-derived style declaration(s) ` +\n `(${names.join(', ')}) — no layout engine during static render.`\n );\n }\n\n for (const [declaration, routes] of layoutDiagnostics.suspicious) {\n console.warn(\n ` WARN zero-valued geometry \"${declaration}\" on ${routes.length} page(s), ` +\n `e.g. ${routes[0]}. Usually a measurement taken where there is no layout ` +\n `engine; a genuine zero is possible.`\n );\n }\n\n layoutDiagnostics.dropped.clear();\n layoutDiagnostics.suspicious.clear();\n}\n\n/**\n * Run `body` with `globalThis.__PITHY_SSR__` set, restoring it exactly.\n *\n * ## Why the flag spans the whole export\n *\n * `setupEnvironment()` sets this flag around a single `renderToString()` call,\n * which is the right scope for a live SSR server handling one request. It is\n * the wrong scope here: every app module is **evaluated** outside that window —\n * `ssrLoadModule(appPath)`, and each route's `imports.page()` in the render\n * loop — and module evaluation is exactly where a module-level reference to a\n * DOM global lives.\n *\n * `apps/playground` proved it. `class PithyDemoElement extends HTMLElement`\n * evaluates its `extends` clause the instant the module loads, so an\n * `isSSRMode()` guard on it was answering `false` during a static export and\n * the route died with `ReferenceError: HTMLElement is not defined` (BUG-027).\n * A guard that cannot be trusted at module scope is not a guard.\n *\n * ## Why the restore is exact, and why it is a `finally`\n *\n * `buildSSG()` is a library export a caller may invoke mid-process and carry on\n * afterwards, so leaving the flag set would silently put the rest of that\n * process into SSR mode. A flag that was **absent** is deleted rather than set\n * to `false`, because `'__PITHY_SSR__' in globalThis` is observable and the two\n * are not the same state. The `finally` means a throwing export restores it\n * too — the case a `--allow-partial`-less build hits routinely.\n *\n * This nests correctly with `setupEnvironment()`: the inner one saves `true`\n * and restores `true`.\n *\n * Safe for `--hydrate` even though the client bundle is built inside this\n * window: `buildClientBundle()` runs Vite in a **separate process**\n * (`execFileSync`), so a global in this one cannot reach it.\n *\n * @param body - The export to run. Its resolution or rejection is passed through.\n * @returns Whatever `body` resolves to.\n * @internal Exported for testing\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"withSsrExportFlag\",\"stability\":\"experimental\",\"signature\":\"<T>(body: () => Promise<T>) => Promise<T>\"} */\nexport async function withSsrExportFlag<T>(body: () => Promise<T>): Promise<T> {\n const host = globalThis as Record<string, unknown>;\n\n // Depth-counted, and the snapshot is taken ONCE at depth 0 — on the host, not\n // per call. Capturing `had`/`previous` per call looked equivalent and was not:\n // for two INTERLEAVED exports, the second captures `true` (the first already\n // set it), and whichever finishes last restores that mid-export snapshot, so\n // the flag stays set forever. Strict nesting happened to work either way,\n // which is exactly why the per-call version read as correct.\n const depth = (host.__PITHY_SSR_DEPTH__ as number | undefined) ?? 0;\n if (depth === 0) {\n host.__PITHY_SSR_SAVED__ = {\n had: '__PITHY_SSR__' in host,\n previous: host.__PITHY_SSR__,\n };\n }\n host.__PITHY_SSR_DEPTH__ = depth + 1;\n host.__PITHY_SSR__ = true;\n try {\n return await body();\n } finally {\n const remaining = (host.__PITHY_SSR_DEPTH__ as number) - 1;\n if (remaining > 0) {\n host.__PITHY_SSR_DEPTH__ = remaining;\n } else {\n const saved = host.__PITHY_SSR_SAVED__ as\n | { had: boolean; previous: unknown }\n | undefined;\n delete host.__PITHY_SSR_DEPTH__;\n delete host.__PITHY_SSR_SAVED__;\n if (saved?.had) host.__PITHY_SSR__ = saved.previous;\n else delete host.__PITHY_SSR__;\n }\n }\n}\n\n/**\n * Build a static site with optional client-side hydration.\n *\n * Loads the app's configuration, routes, and App component directly via Vite.\n * No entry-server.ts or entry-client.ts needed — the framework handles everything.\n *\n * A thin wrapper whose own job is to own the SSR-mode window: see\n * {@link withSsrExportFlag} for why the flag has to span the whole export\n * rather than each render, and why the restore is a `finally`.\n *\n * @param options - See {@link BuildSSGOptions}.\n * @returns Rendered route paths, the not-found entry, per-route failures and\n * export-wide {@link SSGBuildResult.buildFailures}.\n *\n * @example Static mode (no JS)\n * ```ts\n * await buildSSG();\n * ```\n *\n * @example Hydrate mode (with JS)\n * ```ts\n * await buildSSG({ hydrate: true });\n * ```\n */\nexport async function buildSSG(\n options?: BuildSSGOptions\n): Promise<SSGBuildResult> {\n return withSsrExportFlag(() => runBuildSSG(options));\n}\n\n/**\n * What a bad option VALUE is, for a warning: `typeof` alone reports `object`\n * for a `Set`, for `null` and for an array alike, which names none of them.\n */\nfunction describe(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value !== 'object') return typeof value;\n return (value as object).constructor?.name ?? 'object';\n}\n\n/**\n * Every name the dead-declaration purge must keep regardless of liveness: the\n * app's own `keepCustomProperties`, plus the design-system plugin's\n * `channelVarSafelist` read off its published `api`.\n *\n * The plugin's entries are the ones its gate could not prove used — composed at\n * runtime — so this pass cannot see a reference to them either, and without the\n * forward it drops precisely what the author asked the gate to keep.\n *\n * Read rather than imported: `@pithyjs/ssr` does not depend on\n * `@pithyjs/vite-plugin`. Shape-checked because the plugin may be absent, an\n * older version, or a user's own plugin of the same name.\n *\n * Assembled here, not at the call site: `runBuildSSG` needs a live Vite server,\n * so nothing reaches its body from a unit test and logic written inline there\n * can be gutted without reddening anything.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"livePropSafelist\",\"stability\":\"experimental\",\"signature\":\"(config: { keepCustomProperties?: unknown }, plugins?: readonly { name?: string; api?: unknown }[]) => readonly (string | RegExp)[]\"} */\nexport function livePropSafelist(\n config: { keepCustomProperties?: unknown },\n plugins: readonly { name?: string; api?: unknown }[] = []\n): readonly (string | RegExp)[] {\n // Coerced before anything spreads it. The option is typed, but a JS config\n // written without `defineConfig` is not: a bare string spread into single\n // characters, and a number or object threw `is not iterable` here — outside\n // the purge's own try/catch, so the whole build failed.\n const own = asSafelistArray(config.keepCustomProperties);\n const api = plugins.find(p => p?.name === 'pithy-design-system')?.api as\n | { channelVarSafelist?: unknown }\n | undefined;\n const channel = api?.channelVarSafelist;\n if (channel !== undefined && !Array.isArray(channel)) {\n console.warn(\n `[pithy:ssg] channelVarSafelist must be an ARRAY; got ` +\n `${describe(channel)}. Its names are NOT protected from the ` +\n `dead-declaration purge — list them in keepCustomProperties.`\n );\n return own;\n }\n const usable = (channel ?? []).filter(\n (e: unknown): e is string | RegExp =>\n typeof e === 'string' || e instanceof RegExp\n );\n if (usable.length !== (channel ?? []).length) {\n const unusable = (channel ?? [])\n .filter((e: unknown) => !(typeof e === 'string' || e instanceof RegExp))\n .map(describe);\n // The plugin treats the same input as fatal and keeps every channel\n // variable, so staying silent here left the two passes disagreeing about\n // one option with nothing said. This pass cannot mirror `keepAll` — it\n // would have to guess which names are channel variables — so it says\n // plainly which entries it could not use.\n console.warn(\n `[pithy:ssg] channelVarSafelist: ignoring ` +\n `${(channel ?? []).length - usable.length} entry/entries that are ` +\n `neither a string nor a RegExp (${unusable.join(', ')}). The ` +\n `design-system plugin keeps ALL ` +\n `channel variables for this input; this pass keeps only the entries ` +\n `it can read, so the two disagree until the option is fixed.`\n );\n }\n return [...own, ...usable];\n}\n\nasync function runBuildSSG(options?: BuildSSGOptions): Promise<SSGBuildResult> {\n const root = path.resolve(options?.root ?? process.cwd());\n const outDir = path.resolve(root, options?.outDir ?? 'out');\n\n // Prevent path traversal — outDir must resolve within root to avoid\n // accidental deletion of directories outside the project\n const relativeOutDir = path.relative(root, outDir);\n if (\n !relativeOutDir ||\n relativeOutDir === '.' ||\n relativeOutDir.startsWith('..') ||\n path.isAbsolute(relativeOutDir)\n ) {\n throw new Error(\n `outDir \"${options?.outDir ?? ''}\" resolves to the project root or outside it.\\n` +\n ` Resolved: ${outDir}\\n` +\n ` Root: ${root}\\n` +\n ` Use a subdirectory path (e.g. \"out\" or \"dist/static\").`\n );\n }\n\n const hydrate = options?.hydrate ?? false;\n const configPath = options?.configPath ?? '/pithy.config';\n const entryClient = options?.entryClient ?? 'src/main.ts';\n const relativeLinks = options?.relativeLinks ?? true;\n\n const mode = hydrate ? 'interactive (with hydration)' : 'static (no JS)';\n console.log(`\\n--- SSG Build: ${mode} ---\\n`);\n\n const startTime = performance.now();\n\n // Phase 1: Build client bundle (only in hydrate mode)\n let clientBuild: ClientBuildResult = {};\n\n if (hydrate) {\n clientBuild = await buildClientBundle(root, outDir, entryClient);\n } else {\n if (fs.existsSync(outDir)) {\n fs.rmSync(outDir, { recursive: true, force: true });\n }\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Phase 2: SSG render via Vite dev server\n let createServer: (typeof import('vite'))['createServer'];\n try {\n ({ createServer } = await import('vite'));\n } catch {\n throw new Error(\n 'Vite is required for SSG builds but could not be found.\\n' +\n 'Install it with: pnpm add -D vite'\n );\n }\n\n const vite = await createServer({\n root,\n server: { middlewareMode: true },\n appType: 'custom',\n // Evaluate every @pithyjs module in Vite's runner. Externalized, a module\n // loaded here and the same file imported by the app are two instances, so\n // loadJITCompiler() below would load parse5 into the wrong one.\n ssr: { noExternal: [/^@pithyjs\\//] },\n // Force legacy sass API to avoid sass-embedded's initAsyncCompiler issue\n // in programmatic SSR context (same class of issue that buildClientBundle\n // works around by using a subprocess).\n css: {\n preprocessorOptions: {\n scss: { api: 'legacy' },\n },\n },\n });\n\n const rendered: string[] = [];\n const failed: Array<{ path: string; error: Error }> = [];\n const buildFailures: Array<{ stage: string; error: Error }> = [];\n\n try {\n // Read the shell THROUGH Vite, not off disk: `%VITE_*%` placeholders and\n // `transformIndexHtml` plugin hooks are what dev and `vite build` render,\n // so parsing the raw file would carry a literal `%VITE_APP_TITLE%` into the\n // artifact and diverge from every other way the app is built.\n const shellHead = await readShellHead(root, {\n transform: html => vite.transformIndexHtml('/', html),\n });\n if (options?.title) shellHead.title = options.title;\n\n // ── Load modules through Vite (resolves virtual modules, aliases, workspace deps) ──\n\n console.log('Loading app configuration...');\n const configMod = await vite.ssrLoadModule(configPath);\n const config = configMod.default ?? {};\n\n console.log('Loading route manifest...');\n const routesMod = await vite.ssrLoadModule('virtual:pithy/routes.gen');\n const routes = routesMod.routes;\n\n // Normalize app path to root-absolute Vite module ID (e.g. /src/App)\n const rawAppPath: string = config.app ?? '/src/App';\n const appPath = rawAppPath.replace(/^\\.\\//, '/').replace(/^(?!\\/)/, '/');\n console.log(`Loading App component from ${appPath}...`);\n const appMod = await vite.ssrLoadModule(appPath);\n const App = appMod.default;\n\n // Load framework modules through Vite too (avoids tsx resolution issues)\n const ssrServerMod = await vite.ssrLoadModule('@pithyjs/ssr/server');\n const renderToString = ssrServerMod.renderToString;\n const htmlShellFn = ssrServerMod.htmlShell;\n\n const ssrBuildMod = await vite.ssrLoadModule('@pithyjs/ssr/build');\n const collectStaticPaths = ssrBuildMod.collectStaticPaths;\n const findRootCatchAllRoute = ssrBuildMod.findRootCatchAllRoute;\n\n const routerMod = await vite.ssrLoadModule('@pithyjs/router');\n // A layout-only node shares its pattern with a route it wraps\n const findRouteByPattern =\n routerMod.findNavigableRoute ?? routerMod.findRouteByPattern;\n const findLayoutChain: (r: RouteNode[], n: RouteNode) => RouteNode[] =\n routerMod.findLayoutChain ?? (() => []);\n\n // Load JIT compiler (parse5) for runtime html`` templates.\n // Must run before any renderToString() call.\n // Imported from compile/parseHtml directly (not the barrel) to avoid\n // pulling parse5 into client bundles via the barrel re-export chain.\n // Wrapped in try/catch: parse5 is an optional peer dep — AOT-only apps may not have it.\n try {\n const parseHtmlMod = await vite.ssrLoadModule(\n '@pithyjs/core/compile/parseHtml'\n );\n await parseHtmlMod.loadJITCompiler();\n } catch (err) {\n // parse5 not installed — fine for AOT-only apps where all templates are pre-compiled.\n // Log so genuine load errors (corrupt install, version mismatch) aren't invisible.\n console.warn(\n '[pithy:ssg] Could not load JIT compiler (parse5). AOT-only apps can ignore this.',\n err\n );\n }\n\n // Initialize design system if configured — creates the ThemeManager\n // singleton so components calling getThemeManager() don't crash.\n if (config.designSystem) {\n const dsMod = await vite.ssrLoadModule('@pithyjs/design-system');\n dsMod.initDesignSystem(config.designSystem);\n }\n\n // Icon sprite. Both modes: the sprite URL these pages reference comes from\n // the *dev* `virtual:pithy-icons` module this Vite server serves, so it is\n // `/@pithy-icons-sprite.svg` — a dev-only route no build ever emits. Left\n // alone it is a 404 per icon in the prerendered document, whichever mode\n // produced it. See finalizePageHtml().\n //\n // Must run before the render loop — registration is what makes\n // `resolveIconSvg()` emit a `<use>` instead of the missing-icon placeholder.\n const sprite: SpriteBundle = await loadSpriteForSsg(vite);\n if (sprite.symbols.size > 0) {\n console.log(`Registered icon sprite (${sprite.symbols.size} symbols).`);\n }\n\n // ── Discover static routes ──\n\n const staticPaths: string[] = await collectStaticPaths(routes);\n console.log(`Found ${staticPaths.length} static paths to render.\\n`);\n\n // `collectStaticPaths()` excludes catch-all routes by design, and that stays\n // — a catch-all has no literal path of its own to be written at. The\n // site-wide not-found document is a separate emission: one extra render of\n // the TOP-LEVEL catch-all, written to the output root as `404.html`.\n // No top-level catch-all (or a nested-only one) is a complete no-op.\n // See NOT_FOUND_OUTPUT and findRootCatchAllRoute().\n const notFoundRoute: RouteNode | undefined = findRootCatchAllRoute(routes);\n if (notFoundRoute) {\n console.log(\n `Found a top-level catch-all (${notFoundRoute.pattern}); ` +\n `it will also be written to ${NOT_FOUND_OUTPUT.entry}.\\n`\n );\n }\n\n // Scripts and styles to inject (only in hydrate mode)\n const scripts = clientBuild.script ? [`/${clientBuild.script}`] : [];\n const styles = clientBuild.css ? clientBuild.css.map(f => `/${f}`) : [];\n const outletId = config.outletId ?? 'outlet';\n\n // ── Render all routes ──\n\n console.log('Rendering routes...\\n');\n\n // The JOB itself, not fields copied out of it. Copying re-opened the exact\n // seam `finalizeForOutput` was reshaped to close: with `entry` and\n // `linkBase` restated here, `linkBase: linkBase ?? '/'` was a one-token\n // edit that passed 977 tests, reverted the absolute-links fix AND the\n // noindex fix, and printed an impossible `Rendered: 3/2`. There is nothing\n // to restate now, so there is nothing to quietly restate wrongly.\n const pageResults: Array<{\n job: RenderJob;\n html: string;\n head: unknown;\n state: unknown;\n }> = [];\n\n // The not-found job renders the catch-all's page at a synthetic URL and\n // lands at the output root, so its entry and link depth differ from the\n // usual `pathToFilePath(routePath)` / `routePath` pair. See planRenderJobs().\n const renderJobs: RenderJob[] = planRenderJobs(\n staticPaths,\n notFoundRoute,\n routePath => findRouteByPattern(routes, routePath)\n );\n\n for (const job of renderJobs) {\n const { routePath, routeNode, entry, linkBase } = job;\n try {\n if (!routeNode || !routeNode.imports.page) {\n console.log(` SKIP ${routePath} -- no page component`);\n continue;\n }\n\n // The route's layout.ts files, outermost first, then the page in the\n // innermost outlet. A layout gate (auth, feature flag) redirects\n // before the page is imported or rendered, exactly as a page does.\n const loadPage = routeNode.imports.page;\n let hasDefault = true;\n const wrapped = await wrapInLayouts(\n findLayoutChain(routes, routeNode).flatMap(n =>\n n.imports.layout ? [n.imports.layout] : []\n ),\n async () => {\n const PageComponent = (await loadPage()).default;\n if (!PageComponent) {\n hasDefault = false;\n return { html: '' } as Awaited<ReturnType<typeof renderToString>>;\n }\n return renderToString({ url: routePath, App: PageComponent });\n },\n async Layout => {\n const layoutResult = await renderToString({\n url: routePath,\n App: Layout,\n });\n recordLayoutDiagnostics(routePath, layoutResult.layoutDiagnostics);\n return layoutResult;\n },\n outletId,\n '[SSG]'\n );\n if (!hasDefault) {\n console.log(` SKIP ${routePath} -- no default export`);\n continue;\n }\n if (wrapped.redirectTo || !wrapped.page) {\n console.log(` REDIRECT ${routePath} -> ${wrapped.redirectTo}`);\n continue;\n }\n const pageResult = wrapped.page;\n\n // Layout-taint findings are returned, not logged, because\n // `renderToString()` also serves live SSR requests. The static export is\n // the caller that wants them, and it aggregates rather than repeating\n // the same declaration once per page.\n recordLayoutDiagnostics(routePath, pageResult.layoutDiagnostics);\n const outletHtml = wrapped.html;\n const status = wrapped.status;\n\n // Render App shell per route so layouts reading SSR context\n // (active nav, canonical URL, route-based head) get correct values\n const shellResult = await renderToString({ url: routePath, App });\n const shellHtml = shellResult.html;\n\n // Inject page HTML into the App shell's outlet\n const finalHtml = injectIntoOutlet(\n shellHtml,\n outletHtml,\n outletId,\n '[SSG]'\n );\n\n // A 404 whose page contributed NOTHING is worse than no 404 at all.\n //\n // `buildSSG` renders the catch-all's page standalone and injects the\n // result into the shell's outlet, so a page that portals its content to\n // `document.body` and returns an empty `el` loses that content here —\n // apps/studio's not-found page does exactly this. What survives is the\n // shell alone: measured, a 554 KB copy of the editor home screen with\n // no \"Page not found\" anywhere in it, shipped as the site-wide 404 and\n // fully dead without client JS.\n //\n // The test is TEXT, not an empty string: the page returns an inert\n // `<div>` placeholder, so the injected html is `<div></div>` — not\n // blank, and carrying nothing a reader could see. Refusing to write it\n // leaves the host's own 404, which is honest.\n if (linkBase === null && !hasRenderedText(pageResult.html)) {\n console.warn(\n ` SKIP ${routePath} -- catch-all page rendered no outlet content, ` +\n `so ${entry} would ship the app shell alone. Not written. ` +\n `A page that portals its content out of the outlet cannot be prerendered.`\n );\n continue;\n }\n\n console.log(` OK(${status}) ${routePath}`);\n pageResults.push({\n job,\n html: finalHtml,\n head: resolvePageHead(shellHead, shellResult.head, pageResult.head),\n state: pageResult.state,\n });\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n console.log(` FAIL ${routePath} -- ${error.message}`);\n failed.push({ path: routePath, error });\n }\n }\n\n // ── Collect CSS from module graph (static mode only) ──\n\n let extraCss: string | undefined;\n\n if (!hydrate) {\n console.log('\\nCollecting CSS from Vite module graph...');\n // `entryClient` is passed even though SSR never executes it: its\n // side-effect stylesheet imports are most of the app's CSS, and without\n // warming it the module graph contains almost none of them.\n const collectedCss = await collectCss(vite, entryClient, {\n // The app's DECLARATION, not a probe for a registered plugin. Declared-\n // but-unserved is exactly what BUG-028 was, and a registration probe\n // answered \"false\" for it — the one case the gate exists to catch.\n designSystemDeclared: Boolean(config.designSystem),\n // Recorded, not thrown. Page writing has not started yet, so throwing\n // would trade \"a site with no design tokens\" for \"no site at all\".\n onDesignSystemFailure: error => {\n buildFailures.push({ stage: 'design-system-css', error });\n },\n });\n if (collectedCss.length > 0) {\n console.log(\n ` Collected ${collectedCss.length} chars of additional CSS`\n );\n extraCss = collectedCss;\n } else {\n console.log(' No additional CSS collected');\n }\n\n // ── Purge CSS the rendered pages never use ──\n //\n // Runs HERE, after the render loop, because the pages are what proves a\n // rule unused. `pageResults` already carries the 404 — `planRenderJobs`\n // appends its job to the same list every other page comes from — so the\n // union covers it without a second parameter. It must: a rule only the\n // 404 uses would otherwise be proven unused, dropped, and the 404 would\n // fall back to the user agent's own defaults.\n //\n // Static mode only. Hydrate mode links `clientBuild.css` files and runs\n // JS, so the rendered DOM is not the DOM the stylesheet has to cover.\n if (extraCss) {\n const before = Buffer.byteLength(extraCss, 'utf-8');\n // `p.html` is the body FRAGMENT; `htmlShellFn` wraps it in\n // `<html>`/`<body>`/`<div id=\"{appId}\">` further down, carrying these\n // attributes. An app that themes with\n // `head({ bodyAttrs: { class: 'dark' } })` has a `.dark .x` rule that\n // the fragment alone proves unused, and the same goes for any rule\n // anchored on the app root.\n extraCss = await purgeCssForPages(\n extraCss,\n pageResults.map(p => ({\n html: p.html,\n // The same `appId` handed to `htmlShellFn` below. It wraps the\n // fragment in `<div id=\"{appId}\">`, so without this every\n // `#app ...` rule is proven unused and dropped.\n appId: config.appId,\n htmlAttrs: (p.head as HeadState).htmlAttrs,\n bodyAttrs: (p.head as HeadState).bodyAttrs,\n }))\n );\n // Second pass, over what the first one left. Ordering is load-bearing:\n // a channel variable is dead only once the unused utility rule that\n // referenced it has gone, so running this first would keep the whole\n // family.\n //\n // The attribute values join the page HTML, and the asymmetry with the\n // rule purge above is the reason: a RULE in `extraCss` that no element\n // matches really is unused, but a DECLARATION can be consumed from\n // anywhere in the document — `bodyAttrs: { style: 'color:var(--x)' }`\n // included. Anything consuming it from OUTSIDE the document, such as an\n // author-supplied `<link rel=\"stylesheet\">`, needs\n // `keepCustomProperties` in `pithy.config.ts`.\n extraCss = purgeDeadCustomProps(extraCss, {\n safelist: livePropSafelist(config, vite.config.plugins),\n htmlSources: collectHtmlSources(\n pageResults.map(p => ({\n html: p.html,\n head: p.head as HeadState,\n })),\n sprite\n ),\n });\n const after = Buffer.byteLength(extraCss, 'utf-8');\n if (after < before) {\n console.log(\n ` Purged unused CSS: ${(before / 1024).toFixed(1)} KB -> ` +\n `${(after / 1024).toFixed(1)} KB`\n );\n }\n }\n }\n\n // ── Write output files ──\n\n if (!hydrate) {\n // `build.copyPublicDir: false` is an explicit opt-out that `vite build`\n // honours, so hydrate output omits these. Copying anyway would ship\n // assets the caller excluded, in the one mode they cannot check.\n const copied = vite.config.build.copyPublicDir\n ? copyPublicAssets(vite.config.publicDir, outDir)\n : [];\n if (copied.length > 0) {\n console.log(\n `\\n Copied ${copied.length} public asset(s) to the output.`\n );\n }\n }\n\n // Asked of `publicDir` itself, not of the copied output: in hydrate mode\n // Vite's own client build does the copying, so nothing here would see it.\n const hasAuthoredNotFound =\n vite.config.build.copyPublicDir &&\n typeof vite.config.publicDir === 'string' &&\n fs.existsSync(path.join(vite.config.publicDir, NOT_FOUND_OUTPUT.entry));\n\n let notFoundEntry: string | null = null;\n console.log('\\nWriting portable static files...');\n const entryOwners = new Map<string, { path: string; entry: string }>();\n for (const page of pageResults) {\n const { html, head, state } = page;\n const { routePath, entry } = page.job;\n const fullHtml = htmlShellFn({\n html,\n head: withNotFoundRobots(head as HeadState, page.job),\n state: hydrate ? state : undefined,\n scripts,\n styles,\n criticalCss: extraCss,\n appId: config.appId,\n });\n\n // Reject traversal segments — consistent with ssg.ts renderPage()\n const segments = routePath.replace(/^\\//, '').split('/');\n if (segments.some(s => s === '..' || s === '.')) {\n failed.push({\n path: routePath,\n error: new Error(\n `Path traversal detected: \"${routePath}\" contains \"..\" or \".\" segments`\n ),\n });\n continue;\n }\n\n const { html: finalOutput, missingIcons } = finalizeForOutput(\n fullHtml,\n page.job,\n { relativeLinks, hydrate, sprite }\n );\n\n if (missingIcons.length > 0) {\n console.warn(\n ` WARN ${routePath} -- ${missingIcons.length} icon(s) referenced but absent ` +\n `from the sprite (${missingIcons.join(', ')}); they will render empty.`\n );\n }\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 // A hand-authored `public/404.html` is an explicit not-found document;\n // the generated one is inferred from the presence of a catch-all route.\n // Explicit wins, and this is the only way to opt out of generation.\n //\n // Scoped to the 404 on purpose: every other entry comes from a route the\n // author actually created, and page-wins is the long-standing behaviour\n // there. Only the 404 is emitted without anyone asking for it, so only\n // the 404 needs a way to say no.\n if (entry === NOT_FOUND_OUTPUT.entry && hasAuthoredNotFound) {\n console.warn(\n ` SKIP ${routePath} -- public/${NOT_FOUND_OUTPUT.entry} exists, so the ` +\n `hand-authored document is kept and the generated one discarded.`\n );\n continue;\n }\n\n const owner = entryOwners.get(entryCollisionKey(entry));\n if (owner !== undefined) {\n const detail =\n owner.entry === entry\n ? `both write to \"${entry}\"`\n : `write to \"${owner.entry}\" and \"${entry}\", which are one file on a filesystem that ignores case or Unicode normalization`;\n const error = new Error(\n `Output collision: paths \"${owner.path}\" and \"${routePath}\" ${detail}`\n );\n console.log(` FAIL ${routePath} -- ${error.message}`);\n failed.push({ path: routePath, error });\n continue;\n }\n entryOwners.set(entryCollisionKey(entry), { path: routePath, entry });\n\n const absFile = path.resolve(outDir, entry);\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, finalOutput, 'utf-8');\n\n const sizeKb = (Buffer.byteLength(finalOutput, 'utf-8') / 1024).toFixed(\n 1\n );\n console.log(` ${routePath} -> ${entry} (${sizeKb} KB)`);\n // The not-found document is reported separately: it has no route path,\n // so listing it as `/404` invents a route, and an app that really does\n // define `/404` would appear twice with no way to tell the entries apart.\n if (page.job.linkBase === null) {\n notFoundEntry = entry;\n } else {\n rendered.push(routePath);\n }\n }\n\n const totalTime = performance.now() - startTime;\n const totalTimeSec = (totalTime / 1000).toFixed(2);\n\n console.log(`\\n--- Results ---`);\n console.log(` Mode: ${mode}`);\n const pageJobCount = renderJobs.filter(j => j.linkBase !== null).length;\n // `rendered` holds route paths and `pageJobCount` counts the jobs that have\n // one, so the first can never exceed the second. It did: a one-token edit\n // that treated the 404 job as an ordinary page printed `Rendered: 3/2` and\n // nothing objected. An impossible ratio is a wiring bug, and the output is\n // already wrong by the time it prints — so say so rather than print it.\n if (rendered.length > pageJobCount) {\n throw new Error(\n `SSG internal invariant violated: wrote ${rendered.length} page(s) from ` +\n `${pageJobCount} page job(s). The not-found job is being counted as an ` +\n `ordinary page, so its entry and link base are wrong too.`\n );\n }\n console.log(` Rendered: ${rendered.length}/${pageJobCount}`);\n if (notFoundEntry) {\n console.log(` Not found: ${notFoundEntry}`);\n }\n reportLayoutDiagnostics();\n console.log(` Failed: ${failed.length}`);\n console.log(` Time: ${totalTimeSec}s`);\n console.log(` Output: ${outDir}`);\n if (clientBuild.script) {\n console.log(` Client: ${clientBuild.script}`);\n }\n console.log(`\\n Open in browser: ${path.resolve(outDir, 'index.html')}`);\n console.log(\n ` Or serve: npx serve ${path.relative(root, outDir)} -p 3939\\n`\n );\n\n if (failed.length > 0) {\n console.log('Failed routes:');\n for (const f of failed) {\n console.log(` ${f.path}: ${f.error.message}`);\n }\n // No `--allow-partial` hint here. `buildSSG()` is a library API and\n // cannot see whether the flag was passed, so an unconditional hint\n // printed even when it HAD been — directly contradicting the note\n // `endCliProcess()` prints two lines later. The CLI knows; it tells.\n console.log('');\n }\n\n if (buildFailures.length > 0) {\n // Printed after the route list so it is the last thing on screen: it\n // applies to every page above it, and --allow-partial does not waive it.\n console.error('Build failures (not waived by --allow-partial):');\n for (const f of buildFailures) {\n console.error(` ${f.stage}: ${f.error.message}`);\n }\n console.error('');\n }\n\n return {\n rendered,\n notFound: notFoundEntry,\n failed,\n buildFailures,\n totalTime,\n };\n } finally {\n // The icon registry is module-singleton state the UI Kit documents as\n // client-only. A build-time SSG run is a legitimate exception, but leaving\n // it populated would leak into anything sharing the process — a watch-mode\n // rebuild, a test run, a second buildSSG() for a different app.\n await clearSpriteForSsg(vite).catch(() => {});\n await vite.close();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"vite-ssg.js","sourceRoot":"","sources":["../../src/build/vite-ssg.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EACL,oBAAoB,GAErB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EACL,oBAAoB,EACpB,kBAAkB,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,EAAE,aAAa;YACvB,MAAM;YACN,MAAM;YACN,aAAa;YACb,SAAS;SACV,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,sEAAsE;QACtE,2EAA2E;QAC3E,2EAA2E;QAC3E,gEAAgE;QAChE,MAAM,iBAAiB,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC9C,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.build.vite-ssg\",\n \"title\": \"Vite-integrated SSG Build Orchestrator\",\n \"category\": \"feature\",\n \"risk\": \"critical\"\n}\n*/\n\n/**\n * Vite-integrated SSG Build Orchestrator\n *\n * Provides `buildSSG()` — a single function that apps call to produce\n * a fully portable static site with optional client-side hydration.\n *\n * The framework handles everything internally:\n * - Loads pithy.config.ts for app configuration\n * - Auto-discovers routes from the virtual route manifest\n * - Renders the App shell and injects page content\n * - Collects CSS from the Vite module graph, and in static mode purges the\n * rules no rendered page uses (see `css-purge.ts`)\n * - Registers the app's icon sprite and inlines the symbols each page uses\n * (both modes — a prerendered document must stand on its own before any\n * client JS runs)\n * - Builds the client JS bundle for hydration mode\n *\n * Apps need zero entry files — just `pithy.config.ts` at the root.\n *\n * Usage:\n * pithy-ssg — static HTML only (no JS)\n * pithy-ssg --hydrate — static HTML + client JS\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { execFileSync } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport {\n inlineSpriteIntoHtml,\n type SpriteBundle,\n} from '@pithyjs/shared/sprite';\nimport type { RouteNode } from '@pithyjs/router';\nimport type { HeadState, ShellOptions } from '../shared/types.js';\nimport { collectCss } from './collect-css.js';\nimport { purgeCssForPages } from './css-purge.js';\nimport {\n purgeDeadCustomProps,\n collectHtmlSources,\n asSafelistArray,\n} from './css-live-props.js';\nimport { makeLinksRelative } from './relative-links.js';\nimport { NOT_FOUND_OUTPUT, hasRenderedText } from './not-found.js';\nimport { loadSpriteForSsg, clearSpriteForSsg } from './sprite-ssg.js';\nimport { readShellHead, resolvePageHead } from './shell-head.js';\nimport {\n injectIntoOutlet,\n pathToFilePath,\n wrapInLayouts,\n} from '../shared/shell-helpers.js';\nimport { entryCollisionKey } from '../shared/entry-path.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface SSGBuildResult {\n /**\n * Successfully rendered ROUTE paths. Excludes the not-found document, which\n * has no route path of its own — see {@link SSGBuildResult.notFound}.\n */\n rendered: string[];\n /**\n * Entry the site-wide not-found document was written to (`404.html`), or\n * `null` when none was emitted — no top-level catch-all, a catch-all that\n * rendered no content, or a hand-authored `public/404.html` that won.\n */\n notFound: string | null;\n /** Entries written for `ssg.shells`, e.g. `app/index.html`. */\n shells: string[];\n failed: Array<{ path: string; error: Error }>;\n /**\n * Failures that belong to the export as a whole rather than to one route.\n *\n * Separate from {@link SSGBuildResult.failed} because the two deserve\n * different answers: a failed route costs one page and `--allow-partial` can\n * waive it, whereas a failed design-system stylesheet unstyles every page\n * that was written and nothing can. Both are reported; only the first is\n * waivable.\n *\n * Recorded here rather than thrown so the pages still get written —\n * `collectCss()` runs before the first file is written, so a throw would turn\n * a CSS problem into an empty output directory.\n */\n buildFailures: Array<{ stage: string; error: Error }>;\n totalTime: number;\n}\n\nexport interface BuildSSGOptions {\n /** App root directory (default: process.cwd()) */\n root?: string;\n /** Output directory relative to root (default: 'out') */\n outDir?: string;\n /** Build client JS and enable hydration (default: false) */\n hydrate?: boolean;\n /** Path to pithy.config as Vite module ID (default: '/pithy.config') */\n configPath?: string;\n /** Path to client entry relative to root (default: 'src/main.ts') */\n entryClient?: string;\n /**\n * Convert absolute links to relative for portability (default: true).\n *\n * In static mode: all links (routes + assets) are rewritten to relative\n * paths, making the output fully file:// compatible.\n *\n * In hydrate mode: only asset URLs (.css, .js, etc.) are rewritten;\n * route links (/about, /dashboard) stay absolute so the client router\n * can match them. This means hydrate output requires a static file server\n * (e.g. `npx serve`) and is NOT file:// compatible.\n */\n relativeLinks?: boolean;\n /**\n * Document title for pages that set none.\n *\n * Overrides the `<title>` read from the app's HTML shell; a `head()` call in\n * a layout or page still wins over both.\n */\n title?: string;\n}\n\n/** What {@link buildClientBundle} found in the client build's Vite manifest. */\nexport interface ClientBuildResult {\n /** Relative path to client JS (e.g., 'assets/main-abc123.js') */\n script?: string;\n /** Relative paths to extracted CSS files */\n css?: string[];\n /** `base` as the client build resolved it (`/`, `/sub/`, a CDN URL, `./`). */\n base?: string;\n /** `publicDir` as the client build resolved it (`''` when disabled). */\n publicDir?: string;\n /** `build.copyPublicDir` as the client build resolved it. */\n copyPublicDir?: boolean;\n}\n\n/** Where a build's `public/` files came from, and whether they were copied. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"PublicCopy\",\"stability\":\"experimental\",\"signature\":\"interface PublicCopy\"} */\nexport interface PublicCopy {\n publicDir: string | false | undefined;\n copyPublicDir: boolean;\n}\n\n/**\n * The `public/` settings that produced the output. In hydrate mode the\n * production client build copied it, under its own config, which can differ\n * from the serve-mode config the prerender server resolved.\n *\n * @param hydrate - Whether a client build ran.\n * @param clientBuild - What it recorded.\n * @param serve - The prerender server's `publicDir` and `build.copyPublicDir`.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"publicCopySource\",\"stability\":\"experimental\",\"signature\":\"(hydrate: boolean, clientBuild: ClientBuildResult, serve: PublicCopy) => PublicCopy\"} */\nexport function publicCopySource(\n hydrate: boolean,\n clientBuild: ClientBuildResult,\n serve: PublicCopy\n): PublicCopy {\n if (!hydrate) return serve;\n return {\n publicDir: clientBuild.publicDir || false,\n copyPublicDir: clientBuild.copyPublicDir ?? false,\n };\n}\n\n/** Whether `public/` supplied a file at `entry` in the output. */\nfunction isAuthoredPublicFile(source: PublicCopy, entry: string): boolean {\n return (\n source.copyPublicDir &&\n typeof source.publicDir === 'string' &&\n fs.existsSync(path.join(source.publicDir, entry))\n );\n}\n\n// Re-export pathToFilePath for test access (canonical definition in shell-helpers)\nexport { pathToFilePath } from '../shared/shell-helpers.js';\n\n// Canonical in `./not-found.js`, so `generateStaticSite()` and `buildSSG()`\n// cannot drift apart. Re-exported here because this is the module the build\n// entry point and the tests address.\nexport { NOT_FOUND_OUTPUT, hasRenderedText };\n\n/** One route {@link buildSSG}'s render loop renders and writes. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"RenderJob\",\"stability\":\"experimental\",\"signature\":\"interface RenderJob\"} */\nexport interface RenderJob {\n /** URL to render the page at (a real route path, or the 404 job's synthetic {@link NOT_FOUND_OUTPUT.renderPath}). */\n routePath: string;\n /** Route matched for `routePath`, or absent if none was found. */\n routeNode: RouteNode | null | undefined;\n /** Output file relative to `outDir`. */\n entry: string;\n /**\n * Path `makeLinksRelative()` derives its `../` depth from, or `null` when the\n * document has no fixed depth and must keep ABSOLUTE URLs.\n *\n * A browser resolves relative URLs against the REQUEST url, not against where\n * the file sits in `outDir`. An ordinary page is served at exactly one URL, so\n * a relative base is correct for it. The 404 is served at EVERY unmatched URL,\n * at every depth, so no relative base can be — `assets/x.css` in a document\n * answered for `/docs/whatever` resolves to `/docs/assets/x.css` and 404s.\n */\n linkBase: string | null;\n}\n\n/**\n * Build the list of pages {@link buildSSG} renders and writes, in emission order.\n *\n * Extracted as a pure, side-effect-free seam because this is the exact wiring\n * BUG-015 got wrong three times before it shipped: the `linkBase` a job carries,\n * the `entry` filename it writes to, and whether a 404 job is appended at all\n * are three independent decisions that nothing but a real `pithy-ssg --hydrate`\n * run used to exercise. `findRouteByPattern` is injected rather than looked up\n * here so a fake tree can stand in for the real route module in a unit test —\n * no `ssrLoadModule`, no Vite server.\n *\n * The not-found job, when `notFoundRoute` is present, is always appended LAST.\n * Its `entry` lands at the output root rather than nested like every ordinary\n * page, so it must not shift collision-detection order for the paths ahead of\n * it. No `notFoundRoute` (the app has no top-level catch-all) is a complete\n * no-op — no job appended, nothing written, build still exits 0.\n *\n * @param staticPaths - Every literal path `collectStaticPaths()` found.\n * @param notFoundRoute - The app's top-level catch-all, or null/undefined if\n * it has none. See {@link findRootCatchAllRoute} in `ssg.ts`.\n * @param findRouteByPattern - Resolves a route path to its `RouteNode`.\n */\n/** @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[]\"} */\nexport function planRenderJobs(\n staticPaths: string[],\n notFoundRoute: RouteNode | null | undefined,\n findRouteByPattern: (routePath: string) => RouteNode | null | undefined\n): RenderJob[] {\n const renderJobs: RenderJob[] = staticPaths.map(routePath => ({\n routePath,\n routeNode: findRouteByPattern(routePath),\n entry: pathToFilePath(routePath),\n linkBase: routePath,\n }));\n\n if (notFoundRoute) {\n renderJobs.push({\n routePath: NOT_FOUND_OUTPUT.renderPath,\n routeNode: notFoundRoute,\n entry: NOT_FOUND_OUTPUT.entry,\n linkBase: NOT_FOUND_OUTPUT.linkBase,\n });\n }\n\n return renderJobs;\n}\n\n/** One SPA shell {@link buildSSG} writes: a document with no prerendered content. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"ShellJob\",\"stability\":\"experimental\",\"signature\":\"interface ShellJob\"} */\nexport interface ShellJob {\n /** URL path the shell is written for, normalised (`/app`). */\n path: string;\n /** Output file relative to `outDir` (`app/index.html`). */\n entry: string;\n}\n\n/** What {@link planShellJobs} made of `ssg.shells`. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"ShellPlan\",\"stability\":\"experimental\",\"signature\":\"interface ShellPlan\"} */\nexport interface ShellPlan {\n /** Shells to write, in config order, duplicates removed. */\n jobs: ShellJob[];\n /** Entries that cannot be written. The build reports them as build failures. */\n errors: string[];\n /** Non-fatal notes, e.g. shells configured for a static (no-JS) build. */\n warnings: string[];\n}\n\n/**\n * Plan the SPA shells listed in `pithy.config` `ssg.shells`.\n *\n * Each path must be a literal URL path: no parameter, wildcard, query, hash,\n * percent-escape, dot or empty segment, and no segment ending in `.` or a\n * space (Win32 trims those from file names). One trailing slash is dropped. A shell is only useful with a client bundle, so static\n * mode plans none and warns instead.\n *\n * @param shells - The raw `ssg.shells` value; not trusted to be well-typed.\n * @param hydrate - Whether the build emits a client bundle.\n * @returns The jobs to write plus any errors and warnings.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"planShellJobs\",\"stability\":\"experimental\",\"signature\":\"(shells: unknown, hydrate: boolean) => ShellPlan\"} */\nexport function planShellJobs(shells: unknown, hydrate: boolean): ShellPlan {\n const plan: ShellPlan = { jobs: [], errors: [], warnings: [] };\n if (shells === undefined) return plan;\n if (!Array.isArray(shells)) {\n plan.errors.push(\n `ssg.shells must be an array of URL paths; got ${describe(shells)}.`\n );\n return plan;\n }\n\n const seen = new Map<string, string>();\n for (const raw of shells) {\n // Strip ONE trailing slash, so `//` stays invalid rather than becoming `/`.\n const urlPath =\n typeof raw === 'string' && raw.length > 1 ? raw.replace(/\\/$/, '') : raw;\n const segments =\n typeof urlPath === 'string' ? urlPath.split('/').slice(1) : [];\n const valid =\n typeof urlPath === 'string' &&\n urlPath.startsWith('/') &&\n !/[?#:*%\\\\]/.test(urlPath) &&\n (raw === '/' || segments.every(s => s !== '' && !/[. ]$/.test(s)));\n if (!valid) {\n plan.errors.push(\n `ssg.shells entry ${JSON.stringify(raw)} is not a literal URL path ` +\n `such as \"/app\".`\n );\n continue;\n }\n // `/app` and `/App` are one file on a case-insensitive filesystem.\n const key = entryCollisionKey(pathToFilePath(urlPath));\n const twin = seen.get(key);\n if (twin === urlPath) continue;\n if (twin !== undefined) {\n plan.errors.push(\n `ssg.shells entries \"${twin}\" and \"${urlPath}\" write the same file.`\n );\n continue;\n }\n seen.set(key, urlPath);\n plan.jobs.push({ path: urlPath, entry: pathToFilePath(urlPath) });\n }\n\n if (!hydrate && plan.jobs.length > 0) {\n plan.warnings.push(\n `ssg.shells (${plan.jobs.map(j => j.path).join(', ')}) ignored: a shell ` +\n `is empty until JavaScript runs, so it is written only with --hydrate.`\n );\n plan.jobs = [];\n }\n return plan;\n}\n\n/** Inputs to {@link renderShellDocument}. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"ShellDocumentOptions\",\"stability\":\"experimental\",\"signature\":\"interface ShellDocumentOptions\"} */\nexport interface ShellDocumentOptions {\n /** Head from the app's HTML shell file. */\n head: HeadState;\n /** Root-absolute client script URLs (`/assets/…`). */\n scripts: string[];\n /** Root-absolute client stylesheet URLs, linked in `<head>`. */\n styles: string[];\n /** The production build's `base` (default `/`): every URL is moved under it. */\n base?: string;\n /** The `base` the head was read with (default `/`), which its root-absolute URLs carry. */\n headBase?: string;\n /** App container id (default `app`). */\n appId?: string;\n /** The app's icon sprite, or the empty bundle. */\n sprite: SpriteBundle;\n}\n\n/**\n * Render one SPA shell: head, every stylesheet, the module script, an empty\n * app root and no hydration state, so `bootstrap()` mounts fresh.\n *\n * Links stay absolute (`linkBase: null`, as for the 404): one shell answers\n * every URL under its path, at any depth. Relative `href`/`src` in the head's\n * links and scripts are resolved against `base`, as the root `index.html` they\n * came from would; with a `<base>` in the head they are left alone, with a\n * warning. The head gets `robots: noindex` unless it sets robots itself: a\n * shell has no content and answers arbitrary URLs.\n *\n * @param htmlShellFn - `htmlShell` from `@pithyjs/ssr/server`.\n * @param options - See {@link ShellDocumentOptions}.\n * @returns The document as it will be written.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"renderShellDocument\",\"stability\":\"experimental\",\"signature\":\"(htmlShellFn: (options: ShellOptions) => string, options: ShellDocumentOptions) => FinalizePageResult\"} */\nexport function renderShellDocument(\n htmlShellFn: (options: ShellOptions) => string,\n options: ShellDocumentOptions\n): FinalizePageResult {\n // A shell answers at any depth, so its URLs cannot be depth-relative like a\n // page's; they carry the deployment prefix instead.\n const base = options.base || '/';\n const underBase = (u: string): string => base + u.replace(/^\\//, '');\n const html = htmlShellFn({\n html: '',\n head: withRobotsNoindex(\n absolutiseHeadUrls(options.head, base, options.headBase || '/')\n ),\n state: undefined,\n scripts: options.scripts.map(underBase),\n styles: options.styles.map(underBase),\n appId: options.appId,\n });\n return finalizeForOutput(\n html,\n { linkBase: null },\n { relativeLinks: false, hydrate: true, sprite: options.sprite }\n );\n}\n\n/** A URL a browser would resolve against the request rather than the origin. */\nfunction isRelativeUrl(url: string): boolean {\n return !/^(?:[a-z][a-z\\d+.-]*:|\\/|#)/i.test(url);\n}\n\nfunction resolveAgainstBase(url: string, base: string): string {\n // A CDN base (`https://cdn.example/`) keeps its origin; a path base does not.\n if (/^[a-z][a-z\\d+.-]*:/i.test(base)) return new URL(url, base).href;\n const resolved = new URL(url, new URL(base, 'http://shell.invalid/'));\n return resolved.pathname + resolved.search + resolved.hash;\n}\n\n/** Resolve the head's relative link/script URLs against `base`. */\nfunction absolutiseHeadUrls(\n head: HeadState,\n base: string,\n headBase: string\n): HeadState {\n const relative = [\n ...head.link.map(l => l.href),\n ...head.script.flatMap(sc => (sc.src ? [sc.src] : [])),\n ].filter(u => u !== '' && isRelativeUrl(u));\n const keepRelative = relative.length > 0 && head.base !== undefined;\n if (keepRelative) {\n console.warn(\n ` WARN SPA shell: the head sets <base>, so relative URLs ` +\n `(${relative.join(', ')}) are left as written and resolve against it.`\n );\n }\n // Root-absolute URLs already carry `headBase`; move them onto `base`.\n const fix = (u: string): string => {\n if (!u) return u;\n if (isRelativeUrl(u)) return keepRelative ? u : resolveAgainstBase(u, base);\n if (u.startsWith(headBase) && !u.startsWith('//'))\n return base + u.slice(headBase.length);\n return u;\n };\n return {\n ...head,\n link: head.link.map(l => ({ ...l, href: fix(l.href) })),\n script: head.script.map(sc => (sc.src ? { ...sc, src: fix(sc.src) } : sc)),\n };\n}\n\nfunction withRobotsNoindex(head: HeadState): HeadState {\n if (head.meta.some(m => m.name?.toLowerCase() === 'robots')) return head;\n return {\n ...head,\n meta: [...head.meta, { name: 'robots', content: 'noindex' }],\n };\n}\n\n/** What {@link excludeShellPaths} made of the static paths. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"ShellExclusion\",\"stability\":\"experimental\",\"signature\":\"interface ShellExclusion\"} */\nexport interface ShellExclusion {\n /** Paths still prerendered. */\n kept: string[];\n /** Paths a shell serves instead, so they are not prerendered. */\n skipped: string[];\n /** One message per path that sets `prerender = true` under a shell. */\n errors: string[];\n}\n\n/**\n * Drop the static paths a shell serves: its own path and, unless it is the\n * root shell, every URL path below it, compared as written (one trailing slash\n * ignored). Such routes need no `prerender = false` of their own. A path that\n * only folds onto the shell's file (`/App`) is kept, and the entry check in\n * {@link claimShellEntries} reports it.\n * A path whose config says `prerender = true` contradicts the shell and is an\n * error.\n *\n * @param staticPaths - Every literal path `collectStaticPaths()` found.\n * @param shells - Planned shells, see {@link planShellJobs}.\n * @param forced - Paths whose route config sets `prerender = true`.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"excludeShellPaths\",\"stability\":\"experimental\",\"signature\":\"(staticPaths: readonly string[], shells: readonly ShellJob[], forced: ReadonlySet<string>) => ShellExclusion\"} */\nexport function excludeShellPaths(\n staticPaths: readonly string[],\n shells: readonly ShellJob[],\n forced: ReadonlySet<string>\n): ShellExclusion {\n const result: ShellExclusion = { kept: [], skipped: [], errors: [] };\n const covers = (urlPath: string, shell: ShellJob): boolean =>\n urlPath === shell.path ||\n (shell.path !== '/' && urlPath.startsWith(`${shell.path}/`));\n\n for (const routePath of staticPaths) {\n const urlPath =\n routePath.length > 1 ? routePath.replace(/\\/$/, '') : routePath;\n const cover = shells.find(shell => covers(urlPath, shell));\n if (!cover) {\n result.kept.push(routePath);\n } else if (forced.has(routePath)) {\n result.errors.push(\n `Page \"${routePath}\" sets \\`prerender = true\\` but SPA shell ` +\n `\"${cover.path}\" serves it. Drop one of the two.`\n );\n } else {\n result.skipped.push(routePath);\n }\n }\n return result;\n}\n\n/** Who wrote an output entry: a route path and the file it went to. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"EntryOwner\",\"stability\":\"experimental\",\"signature\":\"interface EntryOwner\"} */\nexport interface EntryOwner {\n path: string;\n entry: string;\n}\n\n/**\n * Decide which shells may be written, given the entries the pages already\n * wrote (keyed by `entryCollisionKey`). A shell is refused when a page owns its\n * file (`/App` against `/app` on a case-insensitive filesystem) or when the app\n * ships that file in `public/`, which the shell would overwrite. Claimed shells\n * are registered in `owners`, which this mutates.\n *\n * @param shells - Planned shells, see {@link planShellJobs}.\n * @param owners - Entries written so far.\n * @param isAuthored - Whether `public/` holds a file at an entry.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"claimShellEntries\",\"stability\":\"experimental\",\"signature\":\"(shells: readonly ShellJob[], owners: Map<string, EntryOwner>, isAuthored: (entry: string) => boolean) => { claimed: ShellJob[]; errors: string[] }\"} */\nexport function claimShellEntries(\n shells: readonly ShellJob[],\n owners: Map<string, EntryOwner>,\n isAuthored: (entry: string) => boolean\n): { claimed: ShellJob[]; errors: string[] } {\n const claimed: ShellJob[] = [];\n const errors: string[] = [];\n for (const shell of shells) {\n const key = entryCollisionKey(shell.entry);\n const owner = owners.get(key);\n if (owner !== undefined) {\n errors.push(\n `SPA shell \"${shell.path}\" and page \"${owner.path}\" both write to ` +\n `\"${owner.entry}\".`\n );\n } else if (isAuthored(shell.entry)) {\n errors.push(\n `SPA shell \"${shell.path}\" would overwrite ${shell.entry}, which ` +\n `the client build copied from publicDir. Remove the file or drop the shell.`\n );\n } else {\n owners.set(key, { path: shell.path, entry: shell.entry });\n claimed.push(shell);\n }\n }\n return { claimed, errors };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"copyPublicAssets\",\"stability\":\"experimental\",\"signature\":\"(publicDir: string | false | undefined, outDir: string) => string[]\"} */\n/**\n * Copy the app's public directory into the output.\n *\n * Hydrate output gets this for free — the client `vite build` writes into the\n * same `outDir` and copies `publicDir` itself. Static mode runs no client\n * build, so it emitted a document referencing a favicon it never shipped.\n *\n * Call before the pages are written: a page and a public file that resolve to\n * the same path should end with the rendered page, not the raw asset.\n *\n * Walks with `statSync`, which follows symlinks as Vite's own `copyDir` does:\n * a `Dirent` reports a symlink as neither file nor directory, so a linked\n * asset would be dropped and its document reference would 404.\n *\n * Following them is what makes the two guards necessary. Directories are\n * compared by real path, so an `outDir` inside `publicDir` is skipped whether\n * it is reached directly or through a link, and the chain of real paths\n * already open is carried down so a cycle — `public/loop -> public` — ends the\n * branch instead of recursing until the filesystem refuses. The chain is per\n * branch, not global: the same directory linked from two places is legitimate\n * content and is copied to both.\n *\n * @param publicDir - Vite's resolved `publicDir` (`false` when disabled).\n * @param outDir - Directory the build writes into.\n * @returns Paths copied, relative to `publicDir`.\n */\nexport function copyPublicAssets(\n publicDir: string | false | undefined,\n outDir: string\n): string[] {\n if (!publicDir || !fs.existsSync(publicDir)) return [];\n\n const outReal = fs.existsSync(outDir)\n ? fs.realpathSync(outDir)\n : path.resolve(outDir);\n const copied: string[] = [];\n const walk = (dir: string, rel: string, open: ReadonlySet<string>): void => {\n for (const name of fs.readdirSync(dir)) {\n const from = path.resolve(dir, name);\n const relPath = rel ? `${rel}/${name}` : name;\n if (fs.statSync(from).isDirectory()) {\n const real = fs.realpathSync(from);\n if (real === outReal || open.has(real)) continue;\n fs.mkdirSync(path.resolve(outDir, relPath), { recursive: true });\n walk(from, relPath, new Set(open).add(real));\n } else {\n const to = path.resolve(outDir, relPath);\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.copyFileSync(from, to);\n copied.push(relPath);\n }\n }\n };\n walk(publicDir, '', new Set([fs.realpathSync(publicDir)]));\n return copied;\n}\n\n// =============================================================================\n// Page finalization\n// =============================================================================\n\n/** Inputs to {@link finalizePageHtml}. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"FinalizePageOptions\",\"stability\":\"experimental\",\"signature\":\"interface FinalizePageOptions\"} */\nexport interface FinalizePageOptions {\n /** Rewrite absolute links to relative (see {@link BuildSSGOptions.relativeLinks}). */\n relativeLinks: boolean;\n /**\n * Hydrate mode. Narrows the relative-link rewrite to assets only, so route\n * links stay absolute for the client router. It does **not** gate sprite\n * inlining — see {@link finalizePageHtml}.\n */\n hydrate: boolean;\n /** The app's icon sprite, or the empty bundle. */\n sprite: SpriteBundle;\n}\n\n/** Result of {@link finalizePageHtml}. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"FinalizePageResult\",\"stability\":\"experimental\",\"signature\":\"interface FinalizePageResult\"} */\nexport interface FinalizePageResult {\n /** The document as it will be written to disk. */\n html: string;\n /** Icon names referenced against the sprite that it does not define. */\n missingIcons: string[];\n}\n\n/**\n * Keep the generated not-found document out of search indexes.\n *\n * `404.html` is a real, crawlable URL — a host that serves it for unmatched\n * paths also serves it at `/404.html` — and it inherits the shell's `<title>`,\n * so left alone it gets indexed as a duplicate of the home page.\n *\n * Only the generated 404 is touched (`linkBase === null` identifies it), and\n * only when the page has said nothing about robots itself: an app that sets its\n * own directive has made a decision, and this is not the place to overrule it.\n *\n * The title is deliberately left alone. `noindex` removes the search-result\n * problem, and the tab title belongs to the catch-all page, which can set it.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"withNotFoundRobots\",\"stability\":\"internal\",\"signature\":\"(head: HeadState, job: Pick<RenderJob, 'linkBase'>) => HeadState\"} */\nexport function withNotFoundRobots(\n head: HeadState,\n job: Pick<RenderJob, 'linkBase'>\n): HeadState {\n if (job.linkBase !== null) return head;\n return withRobotsNoindex(head);\n}\n\n/**\n * Finalize a rendered page for the URL(s) it will be SERVED at.\n *\n * Takes the JOB, not a path, and reads `linkBase` from it. That is deliberate:\n * an earlier shape took `{ path, linkPath }`, where `path` was never read and\n * existed only to be swapped in — so the mutation this seam was added to close\n * survived it, one token to the right, with 951 tests still green. Passing the\n * already-tested `planRenderJobs` output leaves nothing to swap.\n *\n * `linkBase: null` means the document has no fixed depth — the 404, served at\n * every unmatched URL — so relativisation is DISABLED for it regardless of the\n * caller's `relativeLinks`. Relative URLs resolve against the request, not the\n * file, so `assets/x.css` works for `/nope` and breaks for `/docs/whatever`.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"finalizeForOutput\",\"stability\":\"experimental\",\"signature\":\"(html: string, job: Pick<RenderJob, 'linkBase'>, options: FinalizePageOptions) => FinalizePageResult\"} */\nexport function finalizeForOutput(\n html: string,\n job: Pick<RenderJob, 'linkBase'>,\n options: FinalizePageOptions\n): FinalizePageResult {\n if (job.linkBase === null) {\n return finalizePageHtml(html, '/', { ...options, relativeLinks: false });\n }\n\n return finalizePageHtml(html, job.linkBase, options);\n}\n\n/**\n * Apply the last two transforms before a page is written to disk.\n *\n * Extracted from {@link buildSSG} as a pure seam, because the two properties\n * that matter here are exactly the ones an end-to-end build cannot pin in CI:\n *\n * 1. **Ordering.** Sprite inlining must run *after* `makeLinksRelative`, since\n * that is what the emitted file actually contains — `assets/icons-HASH.svg`,\n * not `/assets/…`. Asserting against the pre-rebase URL is the false negative\n * that once made this bug read as fixed.\n * 2. **Hydrate output is inlined too.** It used to be gated off, on the theory\n * that the client build emits the hashed sprite and `virtual:pithy-icons`\n * re-registers it at runtime. Both halves are true of the *client bundle*\n * and neither is true of the *prerendered document*. The app registers its\n * sprite from module scope (`registerIconSprite(SPRITE_URL, …)`), and during\n * SSG that module is loaded through the Vite **dev** server — so `SPRITE_URL`\n * is the dev virtual path `/@pithy-icons-sprite.svg`, a route that exists\n * only under `vite dev` and is never emitted by a build. Hydrate pages\n * therefore shipped `<use href=\"@pithy-icons-sprite.svg#name\">`: a 404 per\n * icon, a blank brand mark until `hydrate()` discards the DOM and re-renders,\n * and permanently blank with JS off.\n *\n * Inlining is the fix rather than rewriting the href at the hashed asset,\n * because the icon has to paint *before* any request resolves — a prerendered\n * document that needs a second round trip to show its logo has given up the\n * thing prerendering is for. It is safe on the hydrate path: the symbol block\n * is inserted at `<body>` level, outside the container `hydrate()` clears, and\n * the client re-registers the real hashed `SPRITE_URL` on boot, so\n * post-hydration `<use>` references resolve against the emitted asset.\n *\n * @param html - The assembled `htmlShell()` output for one route.\n * @param routePath - Route the page was rendered for (e.g. `/about`).\n * @param options - See {@link FinalizePageOptions}.\n * @returns The final document plus any unresolved icon names.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"finalizePageHtml\",\"stability\":\"experimental\",\"signature\":\"(html: string, routePath: string, options: FinalizePageOptions) => FinalizePageResult\"} */\nexport function finalizePageHtml(\n html: string,\n routePath: string,\n options: FinalizePageOptions\n): FinalizePageResult {\n const relativized = options.relativeLinks\n ? makeLinksRelative(html, routePath, { assetsOnly: options.hydrate })\n : html;\n\n // Run the inliner even when the bundle carries no symbols for this page.\n // Returning early on an empty bundle would suppress the *reporting* too, and\n // a page whose `<use href>` references cannot be resolved is exactly the case\n // worth hearing about: bailing silently is how a dangling reference reaches a\n // published page looking like a successful build. `urlKeys` still gates it,\n // so an app with no sprite at all does no work.\n if (options.sprite.urlKeys.size === 0) {\n return { html: relativized, missingIcons: [] };\n }\n\n const inlined = inlineSpriteIntoHtml(relativized, options.sprite);\n return { html: inlined.html, missingIcons: inlined.missing };\n}\n\n// =============================================================================\n// Client Bundle Build\n// =============================================================================\n\n/** Where the generated client config lives, relative to the app root. */\nconst CLIENT_CONFIG_DIRNAME = path.join('node_modules', '.pithy-ssg');\n\n/**\n * Create the throwaway directory the generated client config is written into.\n *\n * It has to live **inside the app**, not in `os.tmpdir()`. The config file\n * `import`s from `'vite'`, and Node resolves a module's specifiers from that\n * file's own directory, walking up for `node_modules` — the cwd of the process\n * that spawned it is irrelevant. From the OS temp dir there is no\n * `node_modules/vite` anywhere up the chain, so `--hydrate` died with\n * `ERR_MODULE_NOT_FOUND` for every app (BUG-014). Vite compounds it by\n * rewriting the config into a `.timestamp-*.mjs` sidecar in the same directory.\n *\n * `<root>/node_modules/.pithy-ssg/` reaches `<root>/node_modules` on the second\n * hop of that walk, is already ignored by every VCS, and matches the `.vite` /\n * `.cache` convention.\n *\n * @throws If the directory cannot be created — a silent fallback to a location\n * outside the project would just resurrect the original failure.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"createClientConfigDir\",\"stability\":\"internal\",\"signature\":\"(root: string) => string\"} */\nexport function createClientConfigDir(root: string): string {\n const base = path.resolve(root, CLIENT_CONFIG_DIRNAME);\n try {\n fs.mkdirSync(base, { recursive: true });\n return fs.mkdtempSync(path.join(base, 'build-'));\n } catch (error) {\n throw new Error(\n `Could not create the pithy-ssg client config directory at ${base}.\\n` +\n ` The generated Vite config must live inside the project so Node can\\n` +\n ` resolve 'vite' from it, so this cannot fall back elsewhere.\\n` +\n ` Check that ${root}/node_modules/ exists and is writable — a\\n` +\n ` read-only checkout, a permission-denied mount, or a plain file\\n` +\n ` named node_modules all land here. If it is simply missing, run\\n` +\n ` your package manager's install in the app workspace.\\n` +\n ` Cause: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n\n/**\n * Remove a directory made by {@link createClientConfigDir}.\n *\n * Recursive so Vite's `client.config.mjs.timestamp-*.mjs` sidecars — written\n * next to the config — go with it. Never throws: this runs in a `finally` and\n * must not mask a build error.\n *\n * The shared `.pithy-ssg` PARENT is deliberately left in place. Removing it when\n * it looked empty raced with a concurrently starting build: that build can be\n * between its own `mkdirSync(base)` and `mkdtempSync(base/build-*)`, at which\n * point the parent really is empty, and deleting it makes the other build fail\n * with `ENOENT` — a cleanup step breaking an unrelated build. Retrying creation\n * would narrow that window rather than close it, so the parent simply stays.\n *\n * What it costs is one empty directory under `node_modules/`, which is neither\n * user-facing nor version-controlled. That is a better trade than a build that\n * fails once in a while for a reason nobody can reproduce.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"removeClientConfigDir\",\"stability\":\"internal\",\"signature\":\"(dir: string) => void\"} */\nexport function removeClientConfigDir(dir: string): void {\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* ignore — cleanup must never mask the build result */\n }\n}\n\n/**\n * Build client JS/CSS bundle using Vite.\n *\n * Loads the app's vite.config.ts and overrides build options.\n * Uses subprocess to avoid sass resolution issues with programmatic API.\n *\n * Exported as a test seam. {@link createClientConfigDir} being correct is worth\n * nothing if this function stops calling it — a suite that only exercises the\n * helpers stays green through a revert to `mkdtemp(os.tmpdir())` right here,\n * which is the exact regression this file's header exists to prevent. The one\n * test that matters therefore drives `buildClientBundle` itself and inspects the\n * `--config` path handed to the vite binary.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"buildClientBundle\",\"stability\":\"internal\",\"signature\":\"(root: string, outDir: string, entryClient: string) => Promise<ClientBuildResult>\"} */\nexport async function buildClientBundle(\n root: string,\n outDir: string,\n entryClient: string\n): Promise<ClientBuildResult> {\n console.log('Building client bundle...\\n');\n\n // Vite's JavaScript ENTRY, run with this same Node — not the `.bin` shim.\n //\n // The shim looked simpler and is a cross-platform trap: on Windows it is\n // `vite.cmd`, and a batch file cannot be executed by `execFileSync` without\n // `shell: true` — Node refuses outright since the CVE-2024-27980 fix. So the\n // shim meant hydrate builds failed on Windows, while the alternative, turning\n // `shell: true` back on, reintroduces exactly the path-with-spaces quoting\n // problem that avoiding the shell was meant to solve.\n //\n // Running the entry with `process.execPath` needs neither: one code path, no\n // shell, no quoting, identical on every platform. It also pins the Node\n // already running this build rather than whatever a shim happens to resolve.\n //\n // Checked *before* the config directory is created, not after: this throw is\n // between the write and the `try`/`finally` that cleans it up, so a missing\n // install used to leave `node_modules/.pithy-ssg/build-XXXX/client.config.mjs`\n // sitting in the user's project. Failing first costs one `existsSync`.\n // Resolved through Node's OWN algorithm, not a hardcoded path.\n //\n // `<root>/node_modules/vite/bin/vite.js` only exists under a nested layout.\n // With pnpm's `node-linker=hoisted`, `shamefully-hoist`, or any hoisting\n // package manager, Vite is installed and importable while that exact directory\n // is absent — so probing it with `existsSync` aborts the build telling the\n // user to install something they already have. `createRequire` finds it\n // wherever the layout put it, and reading `bin.vite` from the manifest also\n // survives Vite renaming its own entry file.\n let viteEntry: string;\n try {\n const requireFromApp = createRequire(path.join(root, 'noop.js'));\n const pkgPath = requireFromApp.resolve('vite/package.json');\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as {\n bin?: string | Record<string, string>;\n };\n const binField =\n typeof pkg.bin === 'string' ? pkg.bin : (pkg.bin?.vite ?? 'bin/vite.js');\n viteEntry = path.resolve(path.dirname(pkgPath), binField);\n } catch (cause) {\n throw new Error(\n `Vite could not be resolved from ${root}.\\n` +\n ` Install it in the app workspace: pnpm add -D vite\\n` +\n ` Cause: ${cause instanceof Error ? cause.message : String(cause)}`\n );\n }\n\n if (!fs.existsSync(viteEntry)) {\n throw new Error(\n `Vite resolved to ${viteEntry}, which does not exist.\\n` +\n ` This usually means a partial install — reinstall dependencies.`\n );\n }\n\n // Generate a temp config that extends the app's config with build overrides.\n // It must sit inside the project — see createClientConfigDir().\n const tempConfigDir = createClientConfigDir(root);\n\n const tempConfigPath = path.resolve(tempConfigDir, 'client.config.mjs');\n const resolvedPath = path.resolve(tempConfigDir, 'resolved.json');\n const entryClientAbs = path.resolve(root, entryClient).replace(/\\\\/g, '/');\n const outDirAbs = outDir.replace(/\\\\/g, '/');\n\n let resolved: Pick<\n ClientBuildResult,\n 'base' | 'publicDir' | 'copyPublicDir'\n > = {};\n // Opened immediately after the directory exists, not just around the build:\n // anything that throws in between would otherwise strand the generated\n // config inside the user's project.\n try {\n // Write temp config that loads the app's config and overrides build section\n fs.writeFileSync(\n tempConfigPath,\n `\nimport { loadConfigFromFile, mergeConfig } from 'vite';\n\nimport { writeFileSync } from 'node:fs';\n\nconst root = ${JSON.stringify(root.replace(/\\\\/g, '/'))};\nconst loaded = await loadConfigFromFile(\n { command: 'build', mode: 'production' },\n undefined,\n root\n);\n\nconst appConfig = loaded?.config ?? {};\n\n// Take everything from app config, override build\nexport default mergeConfig(appConfig, {\n plugins: [\n {\n name: 'pithy-ssg:record-config',\n configResolved(config) {\n writeFileSync(${JSON.stringify(resolvedPath.replace(/\\\\/g, '/'))}, JSON.stringify({\n base: config.base,\n publicDir: config.publicDir,\n copyPublicDir: config.build.copyPublicDir,\n }));\n },\n },\n ],\n build: {\n outDir: ${JSON.stringify(outDirAbs)},\n emptyOutDir: true,\n manifest: true,\n rollupOptions: {\n input: ${JSON.stringify(entryClientAbs)},\n },\n },\n});\n`,\n 'utf-8'\n );\n\n execFileSync(\n process.execPath,\n [viteEntry, 'build', '--config', tempConfigPath.replace(/\\\\/g, '/')],\n {\n cwd: root,\n stdio: 'inherit',\n }\n );\n if (fs.existsSync(resolvedPath)) {\n resolved = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8'));\n }\n } finally {\n // Clean up the generated config and Vite's .timestamp-*.mjs sidecars\n removeClientConfigDir(tempConfigDir);\n }\n\n // Read Vite build manifest to locate entry chunk + CSS reliably,\n // regardless of custom rollup output naming in the app's vite.config.\n const manifestPath = path.resolve(outDir, '.vite', 'manifest.json');\n if (!fs.existsSync(manifestPath)) {\n throw new Error(\n 'Client build did not produce .vite/manifest.json.\\n' +\n ' Ensure build.manifest is not explicitly disabled in vite.config.'\n );\n }\n\n const manifest: Record<\n string,\n { file: string; css?: string[]; isEntry?: boolean; src?: string }\n > = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));\n\n // Vite manifest keys are typically root-relative posix paths.\n // Try absolute path first, then relative, then fall back to isEntry lookup.\n const relativeKey = entryClient.replace(/\\\\/g, '/');\n const entry =\n manifest[entryClientAbs] ??\n manifest[relativeKey] ??\n Object.values(manifest).find(e => e.isEntry);\n if (!entry) {\n throw new Error(\n `Client build succeeded but entry not found in manifest.\\n` +\n ` Tried keys: \"${entryClientAbs}\", \"${relativeKey}\", isEntry fallback\\n` +\n ` Available keys: ${Object.keys(manifest).join(', ')}`\n );\n }\n\n const result: ClientBuildResult = { ...resolved };\n\n result.script = entry.file;\n const jsSize = (\n fs.statSync(path.resolve(outDir, entry.file)).size / 1024\n ).toFixed(1);\n console.log(`\\n Client JS: ${result.script} (${jsSize} KB)`);\n\n // EVERY stylesheet the client build emitted, not only the entry's.\n //\n // `cssCodeSplit` is Vite's default, so a route's CSS lands in its own chunk\n // that `__vitePreload` fetches only AFTER the JS boots. A prerendered document\n // linking just the entry's CSS therefore paints unstyled until hydration — and\n // stays unstyled permanently with JS off, which is the exact reader the\n // prerender exists for. Static mode never had this gap because `collectCss()`\n // walked the whole module graph; switching an app to `--hydrate` silently lost\n // it, with browser checks hiding it because the chunk lands in milliseconds\n // when JS is on.\n //\n // Linking them all up front also matches what hydrate output does next: it is\n // a client-routed app after first paint, so the router would fetch these on\n // the first navigation regardless.\n //\n // Entry CSS first, so the base layer (design system, ui-kit, global styles)\n // precedes route rules in the cascade rather than depending on chunk order.\n const entryCss = entry.css ?? [];\n const routeCss = Object.values(manifest)\n .filter(chunk => chunk !== entry)\n .flatMap(chunk => chunk.css ?? []);\n const allCss = [...new Set([...entryCss, ...routeCss])];\n\n if (allCss.length > 0) {\n result.css = allCss;\n for (const cssFile of allCss) {\n const cssSize = (\n fs.statSync(path.resolve(outDir, cssFile)).size / 1024\n ).toFixed(1);\n console.log(` Client CSS: ${cssFile} (${cssSize} KB)`);\n }\n console.log('');\n } else {\n console.log(' No extracted CSS file found\\n');\n }\n\n return result;\n}\n\n// =============================================================================\n// Main SSG Build\n// =============================================================================\n\n/**\n * Layout-taint findings across the whole export, aggregated.\n *\n * Aggregated rather than reported per page: the same declaration on a component\n * used site-wide would otherwise print once per route and bury the one-off that\n * actually needs looking at.\n */\ninterface LayoutDiagnosticsAccumulator {\n dropped: Map<string, number>;\n suspicious: Map<string, string[]>;\n}\n\nconst layoutDiagnostics: LayoutDiagnosticsAccumulator = {\n dropped: new Map(),\n suspicious: new Map(),\n};\n\nfunction recordLayoutDiagnostics(\n routePath: string,\n diagnostics:\n | { droppedStyles: string[]; suspiciousGeometry: string[] }\n | undefined\n): void {\n if (!diagnostics) return;\n\n for (const declaration of diagnostics.droppedStyles) {\n layoutDiagnostics.dropped.set(\n declaration,\n (layoutDiagnostics.dropped.get(declaration) ?? 0) + 1\n );\n }\n for (const declaration of diagnostics.suspiciousGeometry) {\n const routes = layoutDiagnostics.suspicious.get(declaration) ?? [];\n routes.push(routePath);\n layoutDiagnostics.suspicious.set(declaration, routes);\n }\n}\n\n/** Print the aggregated findings once, after every page has rendered. */\nfunction reportLayoutDiagnostics(): void {\n if (layoutDiagnostics.dropped.size > 0) {\n const total = [...layoutDiagnostics.dropped.values()].reduce(\n (a, b) => a + b,\n 0\n );\n const names = [...layoutDiagnostics.dropped.keys()]\n .map(d => d.split(':')[0]?.trim())\n .filter((v, i, all) => v && all.indexOf(v) === i);\n console.log(\n ` Layout: dropped ${total} measurement-derived style declaration(s) ` +\n `(${names.join(', ')}) — no layout engine during static render.`\n );\n }\n\n for (const [declaration, routes] of layoutDiagnostics.suspicious) {\n console.warn(\n ` WARN zero-valued geometry \"${declaration}\" on ${routes.length} page(s), ` +\n `e.g. ${routes[0]}. Usually a measurement taken where there is no layout ` +\n `engine; a genuine zero is possible.`\n );\n }\n\n layoutDiagnostics.dropped.clear();\n layoutDiagnostics.suspicious.clear();\n}\n\n/**\n * Run `body` with `globalThis.__PITHY_SSR__` set, restoring it exactly.\n *\n * ## Why the flag spans the whole export\n *\n * `setupEnvironment()` sets this flag around a single `renderToString()` call,\n * which is the right scope for a live SSR server handling one request. It is\n * the wrong scope here: every app module is **evaluated** outside that window —\n * `ssrLoadModule(appPath)`, and each route's `imports.page()` in the render\n * loop — and module evaluation is exactly where a module-level reference to a\n * DOM global lives.\n *\n * `apps/playground` proved it. `class PithyDemoElement extends HTMLElement`\n * evaluates its `extends` clause the instant the module loads, so an\n * `isSSRMode()` guard on it was answering `false` during a static export and\n * the route died with `ReferenceError: HTMLElement is not defined` (BUG-027).\n * A guard that cannot be trusted at module scope is not a guard.\n *\n * ## Why the restore is exact, and why it is a `finally`\n *\n * `buildSSG()` is a library export a caller may invoke mid-process and carry on\n * afterwards, so leaving the flag set would silently put the rest of that\n * process into SSR mode. A flag that was **absent** is deleted rather than set\n * to `false`, because `'__PITHY_SSR__' in globalThis` is observable and the two\n * are not the same state. The `finally` means a throwing export restores it\n * too — the case a `--allow-partial`-less build hits routinely.\n *\n * This nests correctly with `setupEnvironment()`: the inner one saves `true`\n * and restores `true`.\n *\n * Safe for `--hydrate` even though the client bundle is built inside this\n * window: `buildClientBundle()` runs Vite in a **separate process**\n * (`execFileSync`), so a global in this one cannot reach it.\n *\n * @param body - The export to run. Its resolution or rejection is passed through.\n * @returns Whatever `body` resolves to.\n * @internal Exported for testing\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"withSsrExportFlag\",\"stability\":\"experimental\",\"signature\":\"<T>(body: () => Promise<T>) => Promise<T>\"} */\nexport async function withSsrExportFlag<T>(body: () => Promise<T>): Promise<T> {\n const host = globalThis as Record<string, unknown>;\n\n // Depth-counted, and the snapshot is taken ONCE at depth 0 — on the host, not\n // per call. Capturing `had`/`previous` per call looked equivalent and was not:\n // for two INTERLEAVED exports, the second captures `true` (the first already\n // set it), and whichever finishes last restores that mid-export snapshot, so\n // the flag stays set forever. Strict nesting happened to work either way,\n // which is exactly why the per-call version read as correct.\n const depth = (host.__PITHY_SSR_DEPTH__ as number | undefined) ?? 0;\n if (depth === 0) {\n host.__PITHY_SSR_SAVED__ = {\n had: '__PITHY_SSR__' in host,\n previous: host.__PITHY_SSR__,\n };\n }\n host.__PITHY_SSR_DEPTH__ = depth + 1;\n host.__PITHY_SSR__ = true;\n try {\n return await body();\n } finally {\n const remaining = (host.__PITHY_SSR_DEPTH__ as number) - 1;\n if (remaining > 0) {\n host.__PITHY_SSR_DEPTH__ = remaining;\n } else {\n const saved = host.__PITHY_SSR_SAVED__ as\n | { had: boolean; previous: unknown }\n | undefined;\n delete host.__PITHY_SSR_DEPTH__;\n delete host.__PITHY_SSR_SAVED__;\n if (saved?.had) host.__PITHY_SSR__ = saved.previous;\n else delete host.__PITHY_SSR__;\n }\n }\n}\n\n/**\n * Build a static site with optional client-side hydration.\n *\n * Loads the app's configuration, routes, and App component directly via Vite.\n * No entry-server.ts or entry-client.ts needed — the framework handles everything.\n *\n * A thin wrapper whose own job is to own the SSR-mode window: see\n * {@link withSsrExportFlag} for why the flag has to span the whole export\n * rather than each render, and why the restore is a `finally`.\n *\n * @param options - See {@link BuildSSGOptions}.\n * @returns Rendered route paths, the not-found entry, per-route failures and\n * export-wide {@link SSGBuildResult.buildFailures}.\n *\n * @example Static mode (no JS)\n * ```ts\n * await buildSSG();\n * ```\n *\n * @example Hydrate mode (with JS)\n * ```ts\n * await buildSSG({ hydrate: true });\n * ```\n */\nexport async function buildSSG(\n options?: BuildSSGOptions\n): Promise<SSGBuildResult> {\n return withSsrExportFlag(() => runBuildSSG(options));\n}\n\n/**\n * What a bad option VALUE is, for a warning: `typeof` alone reports `object`\n * for a `Set`, for `null` and for an array alike, which names none of them.\n */\nfunction describe(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value !== 'object') return typeof value;\n return (value as object).constructor?.name ?? 'object';\n}\n\n/**\n * Every name the dead-declaration purge must keep regardless of liveness: the\n * app's own `keepCustomProperties`, plus the design-system plugin's\n * `channelVarSafelist` read off its published `api`.\n *\n * The plugin's entries are the ones its gate could not prove used — composed at\n * runtime — so this pass cannot see a reference to them either, and without the\n * forward it drops precisely what the author asked the gate to keep.\n *\n * Read rather than imported: `@pithyjs/ssr` does not depend on\n * `@pithyjs/vite-plugin`. Shape-checked because the plugin may be absent, an\n * older version, or a user's own plugin of the same name.\n *\n * Assembled here, not at the call site: `runBuildSSG` needs a live Vite server,\n * so nothing reaches its body from a unit test and logic written inline there\n * can be gutted without reddening anything.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.vite-ssg\",\"name\":\"livePropSafelist\",\"stability\":\"experimental\",\"signature\":\"(config: { keepCustomProperties?: unknown }, plugins?: readonly { name?: string; api?: unknown }[]) => readonly (string | RegExp)[]\"} */\nexport function livePropSafelist(\n config: { keepCustomProperties?: unknown },\n plugins: readonly { name?: string; api?: unknown }[] = []\n): readonly (string | RegExp)[] {\n // Coerced before anything spreads it. The option is typed, but a JS config\n // written without `defineConfig` is not: a bare string spread into single\n // characters, and a number or object threw `is not iterable` here — outside\n // the purge's own try/catch, so the whole build failed.\n const own = asSafelistArray(config.keepCustomProperties);\n const api = plugins.find(p => p?.name === 'pithy-design-system')?.api as\n | { channelVarSafelist?: unknown }\n | undefined;\n const channel = api?.channelVarSafelist;\n if (channel !== undefined && !Array.isArray(channel)) {\n console.warn(\n `[pithy:ssg] channelVarSafelist must be an ARRAY; got ` +\n `${describe(channel)}. Its names are NOT protected from the ` +\n `dead-declaration purge — list them in keepCustomProperties.`\n );\n return own;\n }\n const usable = (channel ?? []).filter(\n (e: unknown): e is string | RegExp =>\n typeof e === 'string' || e instanceof RegExp\n );\n if (usable.length !== (channel ?? []).length) {\n const unusable = (channel ?? [])\n .filter((e: unknown) => !(typeof e === 'string' || e instanceof RegExp))\n .map(describe);\n // The plugin treats the same input as fatal and keeps every channel\n // variable, so staying silent here left the two passes disagreeing about\n // one option with nothing said. This pass cannot mirror `keepAll` — it\n // would have to guess which names are channel variables — so it says\n // plainly which entries it could not use.\n console.warn(\n `[pithy:ssg] channelVarSafelist: ignoring ` +\n `${(channel ?? []).length - usable.length} entry/entries that are ` +\n `neither a string nor a RegExp (${unusable.join(', ')}). The ` +\n `design-system plugin keeps ALL ` +\n `channel variables for this input; this pass keeps only the entries ` +\n `it can read, so the two disagree until the option is fixed.`\n );\n }\n return [...own, ...usable];\n}\n\nasync function runBuildSSG(options?: BuildSSGOptions): Promise<SSGBuildResult> {\n const root = path.resolve(options?.root ?? process.cwd());\n const outDir = path.resolve(root, options?.outDir ?? 'out');\n\n // Prevent path traversal — outDir must resolve within root to avoid\n // accidental deletion of directories outside the project\n const relativeOutDir = path.relative(root, outDir);\n if (\n !relativeOutDir ||\n relativeOutDir === '.' ||\n relativeOutDir.startsWith('..') ||\n path.isAbsolute(relativeOutDir)\n ) {\n throw new Error(\n `outDir \"${options?.outDir ?? ''}\" resolves to the project root or outside it.\\n` +\n ` Resolved: ${outDir}\\n` +\n ` Root: ${root}\\n` +\n ` Use a subdirectory path (e.g. \"out\" or \"dist/static\").`\n );\n }\n\n const hydrate = options?.hydrate ?? false;\n const configPath = options?.configPath ?? '/pithy.config';\n const entryClient = options?.entryClient ?? 'src/main.ts';\n const relativeLinks = options?.relativeLinks ?? true;\n\n const mode = hydrate ? 'interactive (with hydration)' : 'static (no JS)';\n console.log(`\\n--- SSG Build: ${mode} ---\\n`);\n\n const startTime = performance.now();\n\n // Phase 1: Build client bundle (only in hydrate mode)\n let clientBuild: ClientBuildResult = {};\n\n if (hydrate) {\n clientBuild = await buildClientBundle(root, outDir, entryClient);\n } else {\n if (fs.existsSync(outDir)) {\n fs.rmSync(outDir, { recursive: true, force: true });\n }\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Phase 2: SSG render via Vite dev server\n let createServer: (typeof import('vite'))['createServer'];\n try {\n ({ createServer } = await import('vite'));\n } catch {\n throw new Error(\n 'Vite is required for SSG builds but could not be found.\\n' +\n 'Install it with: pnpm add -D vite'\n );\n }\n\n const vite = await createServer({\n root,\n server: { middlewareMode: true },\n appType: 'custom',\n // Evaluate every @pithyjs module in Vite's runner. Externalized, a module\n // loaded here and the same file imported by the app are two instances, so\n // loadJITCompiler() below would load parse5 into the wrong one.\n ssr: { noExternal: [/^@pithyjs\\//] },\n // Force legacy sass API to avoid sass-embedded's initAsyncCompiler issue\n // in programmatic SSR context (same class of issue that buildClientBundle\n // works around by using a subprocess).\n css: {\n preprocessorOptions: {\n scss: { api: 'legacy' },\n },\n },\n });\n\n const rendered: string[] = [];\n const failed: Array<{ path: string; error: Error }> = [];\n const buildFailures: Array<{ stage: string; error: Error }> = [];\n\n try {\n // Read the shell THROUGH Vite, not off disk: `%VITE_*%` placeholders and\n // `transformIndexHtml` plugin hooks are what dev and `vite build` render,\n // so parsing the raw file would carry a literal `%VITE_APP_TITLE%` into the\n // artifact and diverge from every other way the app is built.\n const shellHead = await readShellHead(root, {\n transform: html => vite.transformIndexHtml('/', html),\n });\n if (options?.title) shellHead.title = options.title;\n\n // ── Load modules through Vite (resolves virtual modules, aliases, workspace deps) ──\n\n console.log('Loading app configuration...');\n const configMod = await vite.ssrLoadModule(configPath);\n const config = configMod.default ?? {};\n\n const shellPlan = planShellJobs(config.ssg?.shells, hydrate);\n for (const warning of shellPlan.warnings)\n console.warn(` WARN ${warning}`);\n for (const message of shellPlan.errors) {\n buildFailures.push({ stage: 'spa-shell', error: new Error(message) });\n }\n\n console.log('Loading route manifest...');\n const routesMod = await vite.ssrLoadModule('virtual:pithy/routes.gen');\n const routes = routesMod.routes;\n\n // Normalize app path to root-absolute Vite module ID (e.g. /src/App)\n const rawAppPath: string = config.app ?? '/src/App';\n const appPath = rawAppPath.replace(/^\\.\\//, '/').replace(/^(?!\\/)/, '/');\n console.log(`Loading App component from ${appPath}...`);\n const appMod = await vite.ssrLoadModule(appPath);\n const App = appMod.default;\n\n // Load framework modules through Vite too (avoids tsx resolution issues)\n const ssrServerMod = await vite.ssrLoadModule('@pithyjs/ssr/server');\n const renderToString = ssrServerMod.renderToString;\n const htmlShellFn = ssrServerMod.htmlShell;\n\n const ssrBuildMod = await vite.ssrLoadModule('@pithyjs/ssr/build');\n const collectStaticPaths = ssrBuildMod.collectStaticPaths;\n const findRootCatchAllRoute = ssrBuildMod.findRootCatchAllRoute;\n\n const routerMod = await vite.ssrLoadModule('@pithyjs/router');\n // A layout-only node shares its pattern with a route it wraps\n const findRouteByPattern =\n routerMod.findNavigableRoute ?? routerMod.findRouteByPattern;\n const findLayoutChain: (r: RouteNode[], n: RouteNode) => RouteNode[] =\n routerMod.findLayoutChain ?? (() => []);\n\n // Load JIT compiler (parse5) for runtime html`` templates.\n // Must run before any renderToString() call.\n // Imported from compile/parseHtml directly (not the barrel) to avoid\n // pulling parse5 into client bundles via the barrel re-export chain.\n // Wrapped in try/catch: parse5 is an optional peer dep — AOT-only apps may not have it.\n try {\n const parseHtmlMod = await vite.ssrLoadModule(\n '@pithyjs/core/compile/parseHtml'\n );\n await parseHtmlMod.loadJITCompiler();\n } catch (err) {\n // parse5 not installed — fine for AOT-only apps where all templates are pre-compiled.\n // Log so genuine load errors (corrupt install, version mismatch) aren't invisible.\n console.warn(\n '[pithy:ssg] Could not load JIT compiler (parse5). AOT-only apps can ignore this.',\n err\n );\n }\n\n // Initialize design system if configured — creates the ThemeManager\n // singleton so components calling getThemeManager() don't crash.\n if (config.designSystem) {\n const dsMod = await vite.ssrLoadModule('@pithyjs/design-system');\n dsMod.initDesignSystem(config.designSystem);\n }\n\n // Icon sprite. Both modes: the sprite URL these pages reference comes from\n // the *dev* `virtual:pithy-icons` module this Vite server serves, so it is\n // `/@pithy-icons-sprite.svg` — a dev-only route no build ever emits. Left\n // alone it is a 404 per icon in the prerendered document, whichever mode\n // produced it. See finalizePageHtml().\n //\n // Must run before the render loop — registration is what makes\n // `resolveIconSvg()` emit a `<use>` instead of the missing-icon placeholder.\n const sprite: SpriteBundle = await loadSpriteForSsg(vite);\n if (sprite.symbols.size > 0) {\n console.log(`Registered icon sprite (${sprite.symbols.size} symbols).`);\n }\n\n // ── Discover static routes ──\n\n const forced = new Set<string>();\n const collected: string[] = await collectStaticPaths(routes);\n if (shellPlan.jobs.length > 0) {\n for (const routePath of collected) {\n const loadConfig = findRouteByPattern(routes, routePath)?.imports\n .config;\n const routeConfig = await loadConfig?.().catch(() => undefined);\n if (routeConfig?.prerender === true) forced.add(routePath);\n }\n }\n const shellPaths = excludeShellPaths(collected, shellPlan.jobs, forced);\n for (const message of shellPaths.errors) {\n console.log(` FAIL ${message}`);\n buildFailures.push({ stage: 'spa-shell', error: new Error(message) });\n }\n if (shellPaths.skipped.length > 0) {\n console.log(`Served by an SPA shell: ${shellPaths.skipped.join(', ')}`);\n }\n const staticPaths = shellPaths.kept;\n console.log(`Found ${staticPaths.length} static paths to render.\\n`);\n\n // `collectStaticPaths()` excludes catch-all routes by design, and that stays\n // — a catch-all has no literal path of its own to be written at. The\n // site-wide not-found document is a separate emission: one extra render of\n // the TOP-LEVEL catch-all, written to the output root as `404.html`.\n // No top-level catch-all (or a nested-only one) is a complete no-op.\n // See NOT_FOUND_OUTPUT and findRootCatchAllRoute().\n const notFoundRoute: RouteNode | undefined = findRootCatchAllRoute(routes);\n if (notFoundRoute) {\n console.log(\n `Found a top-level catch-all (${notFoundRoute.pattern}); ` +\n `it will also be written to ${NOT_FOUND_OUTPUT.entry}.\\n`\n );\n }\n\n // Scripts and styles to inject (only in hydrate mode)\n const scripts = clientBuild.script ? [`/${clientBuild.script}`] : [];\n const styles = clientBuild.css ? clientBuild.css.map(f => `/${f}`) : [];\n const outletId = config.outletId ?? 'outlet';\n\n // ── Render all routes ──\n\n console.log('Rendering routes...\\n');\n\n // The JOB itself, not fields copied out of it. Copying re-opened the exact\n // seam `finalizeForOutput` was reshaped to close: with `entry` and\n // `linkBase` restated here, `linkBase: linkBase ?? '/'` was a one-token\n // edit that passed 977 tests, reverted the absolute-links fix AND the\n // noindex fix, and printed an impossible `Rendered: 3/2`. There is nothing\n // to restate now, so there is nothing to quietly restate wrongly.\n const pageResults: Array<{\n job: RenderJob;\n html: string;\n head: unknown;\n state: unknown;\n }> = [];\n\n // The not-found job renders the catch-all's page at a synthetic URL and\n // lands at the output root, so its entry and link depth differ from the\n // usual `pathToFilePath(routePath)` / `routePath` pair. See planRenderJobs().\n const renderJobs: RenderJob[] = planRenderJobs(\n staticPaths,\n notFoundRoute,\n routePath => findRouteByPattern(routes, routePath)\n );\n\n for (const job of renderJobs) {\n const { routePath, routeNode, entry, linkBase } = job;\n try {\n if (!routeNode || !routeNode.imports.page) {\n console.log(` SKIP ${routePath} -- no page component`);\n continue;\n }\n\n // The route's layout.ts files, outermost first, then the page in the\n // innermost outlet. A layout gate (auth, feature flag) redirects\n // before the page is imported or rendered, exactly as a page does.\n const loadPage = routeNode.imports.page;\n let hasDefault = true;\n const wrapped = await wrapInLayouts(\n findLayoutChain(routes, routeNode).flatMap(n =>\n n.imports.layout ? [n.imports.layout] : []\n ),\n async () => {\n const PageComponent = (await loadPage()).default;\n if (!PageComponent) {\n hasDefault = false;\n return { html: '' } as Awaited<ReturnType<typeof renderToString>>;\n }\n return renderToString({ url: routePath, App: PageComponent });\n },\n async Layout => {\n const layoutResult = await renderToString({\n url: routePath,\n App: Layout,\n });\n recordLayoutDiagnostics(routePath, layoutResult.layoutDiagnostics);\n return layoutResult;\n },\n outletId,\n '[SSG]'\n );\n if (!hasDefault) {\n console.log(` SKIP ${routePath} -- no default export`);\n continue;\n }\n if (wrapped.redirectTo || !wrapped.page) {\n console.log(` REDIRECT ${routePath} -> ${wrapped.redirectTo}`);\n continue;\n }\n const pageResult = wrapped.page;\n\n // Layout-taint findings are returned, not logged, because\n // `renderToString()` also serves live SSR requests. The static export is\n // the caller that wants them, and it aggregates rather than repeating\n // the same declaration once per page.\n recordLayoutDiagnostics(routePath, pageResult.layoutDiagnostics);\n const outletHtml = wrapped.html;\n const status = wrapped.status;\n\n // Render App shell per route so layouts reading SSR context\n // (active nav, canonical URL, route-based head) get correct values\n const shellResult = await renderToString({ url: routePath, App });\n const shellHtml = shellResult.html;\n\n // Inject page HTML into the App shell's outlet\n const finalHtml = injectIntoOutlet(\n shellHtml,\n outletHtml,\n outletId,\n '[SSG]'\n );\n\n // A 404 whose page contributed NOTHING is worse than no 404 at all.\n //\n // `buildSSG` renders the catch-all's page standalone and injects the\n // result into the shell's outlet, so a page that portals its content to\n // `document.body` and returns an empty `el` loses that content here —\n // apps/studio's not-found page does exactly this. What survives is the\n // shell alone: measured, a 554 KB copy of the editor home screen with\n // no \"Page not found\" anywhere in it, shipped as the site-wide 404 and\n // fully dead without client JS.\n //\n // The test is TEXT, not an empty string: the page returns an inert\n // `<div>` placeholder, so the injected html is `<div></div>` — not\n // blank, and carrying nothing a reader could see. Refusing to write it\n // leaves the host's own 404, which is honest.\n if (linkBase === null && !hasRenderedText(pageResult.html)) {\n console.warn(\n ` SKIP ${routePath} -- catch-all page rendered no outlet content, ` +\n `so ${entry} would ship the app shell alone. Not written. ` +\n `A page that portals its content out of the outlet cannot be prerendered.`\n );\n continue;\n }\n\n console.log(` OK(${status}) ${routePath}`);\n pageResults.push({\n job,\n html: finalHtml,\n head: resolvePageHead(shellHead, shellResult.head, pageResult.head),\n state: pageResult.state,\n });\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n console.log(` FAIL ${routePath} -- ${error.message}`);\n failed.push({ path: routePath, error });\n }\n }\n\n // ── Collect CSS from module graph (static mode only) ──\n\n let extraCss: string | undefined;\n\n if (!hydrate) {\n console.log('\\nCollecting CSS from Vite module graph...');\n // `entryClient` is passed even though SSR never executes it: its\n // side-effect stylesheet imports are most of the app's CSS, and without\n // warming it the module graph contains almost none of them.\n const collectedCss = await collectCss(vite, entryClient, {\n // The app's DECLARATION, not a probe for a registered plugin. Declared-\n // but-unserved is exactly what BUG-028 was, and a registration probe\n // answered \"false\" for it — the one case the gate exists to catch.\n designSystemDeclared: Boolean(config.designSystem),\n // Recorded, not thrown. Page writing has not started yet, so throwing\n // would trade \"a site with no design tokens\" for \"no site at all\".\n onDesignSystemFailure: error => {\n buildFailures.push({ stage: 'design-system-css', error });\n },\n });\n if (collectedCss.length > 0) {\n console.log(\n ` Collected ${collectedCss.length} chars of additional CSS`\n );\n extraCss = collectedCss;\n } else {\n console.log(' No additional CSS collected');\n }\n\n // ── Purge CSS the rendered pages never use ──\n //\n // Runs HERE, after the render loop, because the pages are what proves a\n // rule unused. `pageResults` already carries the 404 — `planRenderJobs`\n // appends its job to the same list every other page comes from — so the\n // union covers it without a second parameter. It must: a rule only the\n // 404 uses would otherwise be proven unused, dropped, and the 404 would\n // fall back to the user agent's own defaults.\n //\n // Static mode only. Hydrate mode links `clientBuild.css` files and runs\n // JS, so the rendered DOM is not the DOM the stylesheet has to cover.\n if (extraCss) {\n const before = Buffer.byteLength(extraCss, 'utf-8');\n // `p.html` is the body FRAGMENT; `htmlShellFn` wraps it in\n // `<html>`/`<body>`/`<div id=\"{appId}\">` further down, carrying these\n // attributes. An app that themes with\n // `head({ bodyAttrs: { class: 'dark' } })` has a `.dark .x` rule that\n // the fragment alone proves unused, and the same goes for any rule\n // anchored on the app root.\n extraCss = await purgeCssForPages(\n extraCss,\n pageResults.map(p => ({\n html: p.html,\n // The same `appId` handed to `htmlShellFn` below. It wraps the\n // fragment in `<div id=\"{appId}\">`, so without this every\n // `#app ...` rule is proven unused and dropped.\n appId: config.appId,\n htmlAttrs: (p.head as HeadState).htmlAttrs,\n bodyAttrs: (p.head as HeadState).bodyAttrs,\n }))\n );\n // Second pass, over what the first one left. Ordering is load-bearing:\n // a channel variable is dead only once the unused utility rule that\n // referenced it has gone, so running this first would keep the whole\n // family.\n //\n // The attribute values join the page HTML, and the asymmetry with the\n // rule purge above is the reason: a RULE in `extraCss` that no element\n // matches really is unused, but a DECLARATION can be consumed from\n // anywhere in the document — `bodyAttrs: { style: 'color:var(--x)' }`\n // included. Anything consuming it from OUTSIDE the document, such as an\n // author-supplied `<link rel=\"stylesheet\">`, needs\n // `keepCustomProperties` in `pithy.config.ts`.\n extraCss = purgeDeadCustomProps(extraCss, {\n safelist: livePropSafelist(config, vite.config.plugins),\n htmlSources: collectHtmlSources(\n pageResults.map(p => ({\n html: p.html,\n head: p.head as HeadState,\n })),\n sprite\n ),\n });\n const after = Buffer.byteLength(extraCss, 'utf-8');\n if (after < before) {\n console.log(\n ` Purged unused CSS: ${(before / 1024).toFixed(1)} KB -> ` +\n `${(after / 1024).toFixed(1)} KB`\n );\n }\n }\n }\n\n // ── Write output files ──\n\n if (!hydrate) {\n // `build.copyPublicDir: false` is an explicit opt-out that `vite build`\n // honours, so hydrate output omits these. Copying anyway would ship\n // assets the caller excluded, in the one mode they cannot check.\n const copied = vite.config.build.copyPublicDir\n ? copyPublicAssets(vite.config.publicDir, outDir)\n : [];\n if (copied.length > 0) {\n console.log(\n `\\n Copied ${copied.length} public asset(s) to the output.`\n );\n }\n }\n\n // Asked of `publicDir` itself, not of the copied output: in hydrate mode\n // Vite's own client build does the copying, so nothing here would see it.\n const publicCopy = publicCopySource(hydrate, clientBuild, {\n publicDir: vite.config.publicDir,\n copyPublicDir: vite.config.build.copyPublicDir,\n });\n const hasAuthoredNotFound = isAuthoredPublicFile(\n publicCopy,\n NOT_FOUND_OUTPUT.entry\n );\n\n let notFoundEntry: string | null = null;\n console.log('\\nWriting portable static files...');\n const entryOwners = new Map<string, EntryOwner>();\n for (const page of pageResults) {\n const { html, head, state } = page;\n const { routePath, entry } = page.job;\n const fullHtml = htmlShellFn({\n html,\n head: withNotFoundRobots(head as HeadState, page.job),\n state: hydrate ? state : undefined,\n scripts,\n styles,\n criticalCss: extraCss,\n appId: config.appId,\n });\n\n // Reject traversal segments — consistent with ssg.ts renderPage()\n const segments = routePath.replace(/^\\//, '').split('/');\n if (segments.some(s => s === '..' || s === '.')) {\n failed.push({\n path: routePath,\n error: new Error(\n `Path traversal detected: \"${routePath}\" contains \"..\" or \".\" segments`\n ),\n });\n continue;\n }\n\n const { html: finalOutput, missingIcons } = finalizeForOutput(\n fullHtml,\n page.job,\n { relativeLinks, hydrate, sprite }\n );\n\n if (missingIcons.length > 0) {\n console.warn(\n ` WARN ${routePath} -- ${missingIcons.length} icon(s) referenced but absent ` +\n `from the sprite (${missingIcons.join(', ')}); they will render empty.`\n );\n }\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 // A hand-authored `public/404.html` is an explicit not-found document;\n // the generated one is inferred from the presence of a catch-all route.\n // Explicit wins, and this is the only way to opt out of generation.\n //\n // Scoped to the 404 on purpose: every other entry comes from a route the\n // author actually created, and page-wins is the long-standing behaviour\n // there. Only the 404 is emitted without anyone asking for it, so only\n // the 404 needs a way to say no.\n if (entry === NOT_FOUND_OUTPUT.entry && hasAuthoredNotFound) {\n console.warn(\n ` SKIP ${routePath} -- public/${NOT_FOUND_OUTPUT.entry} exists, so the ` +\n `hand-authored document is kept and the generated one discarded.`\n );\n continue;\n }\n\n const owner = entryOwners.get(entryCollisionKey(entry));\n if (owner !== undefined) {\n const detail =\n owner.entry === entry\n ? `both write to \"${entry}\"`\n : `write to \"${owner.entry}\" and \"${entry}\", which are one file on a filesystem that ignores case or Unicode normalization`;\n const error = new Error(\n `Output collision: paths \"${owner.path}\" and \"${routePath}\" ${detail}`\n );\n console.log(` FAIL ${routePath} -- ${error.message}`);\n failed.push({ path: routePath, error });\n continue;\n }\n entryOwners.set(entryCollisionKey(entry), { path: routePath, entry });\n\n const absFile = path.resolve(outDir, entry);\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, finalOutput, 'utf-8');\n\n const sizeKb = (Buffer.byteLength(finalOutput, 'utf-8') / 1024).toFixed(\n 1\n );\n console.log(` ${routePath} -> ${entry} (${sizeKb} KB)`);\n // The not-found document is reported separately: it has no route path,\n // so listing it as `/404` invents a route, and an app that really does\n // define `/404` would appear twice with no way to tell the entries apart.\n if (page.job.linkBase === null) {\n notFoundEntry = entry;\n } else {\n rendered.push(routePath);\n }\n }\n\n const shells: string[] = [];\n const shellClaim = claimShellEntries(shellPlan.jobs, entryOwners, entry =>\n isAuthoredPublicFile(publicCopy, entry)\n );\n const shellBase = clientBuild.base ?? '/';\n // A relative base cannot resolve at every depth a shell answers.\n if (\n shellClaim.claimed.length > 0 &&\n !/^(?:\\/|[a-z][a-z\\d+.-]*:)/i.test(shellBase)\n ) {\n shellClaim.errors.push(\n `SPA shells need an absolute Vite \\`base\\`; the client build uses ` +\n `${JSON.stringify(shellBase)}.`\n );\n shellClaim.claimed = [];\n }\n for (const message of shellClaim.errors) {\n console.log(` FAIL ${message}`);\n buildFailures.push({ stage: 'spa-shell', error: new Error(message) });\n }\n for (const shell of shellClaim.claimed) {\n const { html: shellHtml } = renderShellDocument(htmlShellFn, {\n head: resolvePageHead(shellHead, {}, {}),\n scripts,\n styles,\n // The PRODUCTION base: the serve-mode one drops a CDN origin and\n // ignores a base that depends on the command or mode.\n base: shellBase,\n headBase: vite.config.base,\n appId: config.appId,\n sprite,\n });\n const absFile = path.resolve(outDir, shell.entry);\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, shellHtml, 'utf-8');\n console.log(` ${shell.path} -> ${shell.entry} (SPA shell)`);\n shells.push(shell.entry);\n }\n\n const totalTime = performance.now() - startTime;\n const totalTimeSec = (totalTime / 1000).toFixed(2);\n\n console.log(`\\n--- Results ---`);\n console.log(` Mode: ${mode}`);\n const pageJobCount = renderJobs.filter(j => j.linkBase !== null).length;\n // `rendered` holds route paths and `pageJobCount` counts the jobs that have\n // one, so the first can never exceed the second. It did: a one-token edit\n // that treated the 404 job as an ordinary page printed `Rendered: 3/2` and\n // nothing objected. An impossible ratio is a wiring bug, and the output is\n // already wrong by the time it prints — so say so rather than print it.\n if (rendered.length > pageJobCount) {\n throw new Error(\n `SSG internal invariant violated: wrote ${rendered.length} page(s) from ` +\n `${pageJobCount} page job(s). The not-found job is being counted as an ` +\n `ordinary page, so its entry and link base are wrong too.`\n );\n }\n console.log(` Rendered: ${rendered.length}/${pageJobCount}`);\n if (notFoundEntry) {\n console.log(` Not found: ${notFoundEntry}`);\n }\n if (shells.length > 0) {\n console.log(` Shells: ${shells.join(', ')}`);\n }\n reportLayoutDiagnostics();\n console.log(` Failed: ${failed.length}`);\n console.log(` Time: ${totalTimeSec}s`);\n console.log(` Output: ${outDir}`);\n if (clientBuild.script) {\n console.log(` Client: ${clientBuild.script}`);\n }\n console.log(`\\n Open in browser: ${path.resolve(outDir, 'index.html')}`);\n console.log(\n ` Or serve: npx serve ${path.relative(root, outDir)} -p 3939\\n`\n );\n\n if (failed.length > 0) {\n console.log('Failed routes:');\n for (const f of failed) {\n console.log(` ${f.path}: ${f.error.message}`);\n }\n // No `--allow-partial` hint here. `buildSSG()` is a library API and\n // cannot see whether the flag was passed, so an unconditional hint\n // printed even when it HAD been — directly contradicting the note\n // `endCliProcess()` prints two lines later. The CLI knows; it tells.\n console.log('');\n }\n\n if (buildFailures.length > 0) {\n // Printed after the route list so it is the last thing on screen: it\n // applies to every page above it, and --allow-partial does not waive it.\n console.error('Build failures (not waived by --allow-partial):');\n for (const f of buildFailures) {\n console.error(` ${f.stage}: ${f.error.message}`);\n }\n console.error('');\n }\n\n return {\n rendered,\n notFound: notFoundEntry,\n shells,\n failed,\n buildFailures,\n totalTime,\n };\n } finally {\n // The icon registry is module-singleton state the UI Kit documents as\n // client-only. A build-time SSG run is a legitimate exception, but leaving\n // it populated would leak into anything sharing the process — a watch-mode\n // rebuild, a test run, a second buildSSG() for a different app.\n await clearSpriteForSsg(vite).catch(() => {});\n await vite.close();\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithyjs/ssr",
|
|
3
|
-
"version": "0.2.0-beta.
|
|
3
|
+
"version": "0.2.0-beta.14",
|
|
4
4
|
"description": "Server-side rendering and static site generation for PithyJS framework",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -34,11 +34,11 @@
|
|
|
34
34
|
}
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@pithyjs/shared": "0.1.0-beta.
|
|
37
|
+
"@pithyjs/shared": "0.1.0-beta.4",
|
|
38
38
|
"@pithyjs/signals": "0.1.0-beta.2",
|
|
39
|
-
"@pithyjs/router": "0.2.0-beta.
|
|
40
|
-
"@pithyjs/core": "0.1.0-beta.
|
|
41
|
-
"@pithyjs/design-system": "0.1.0-beta.
|
|
39
|
+
"@pithyjs/router": "0.2.0-beta.14",
|
|
40
|
+
"@pithyjs/core": "0.1.0-beta.15",
|
|
41
|
+
"@pithyjs/design-system": "0.1.0-beta.9"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"happy-dom": "^20.0.3",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
},
|
|
79
79
|
"license": "MIT",
|
|
80
80
|
"scripts": {
|
|
81
|
-
"build": "tsc -p tsconfig.json && node ../../scripts/add-js-extensions.mjs dist",
|
|
81
|
+
"build": "node ../../scripts/check-dist.mjs --unstamp $$ && tsc -p tsconfig.json && node ../../scripts/add-js-extensions.mjs dist && node ../../scripts/check-dist.mjs --stamp $$",
|
|
82
82
|
"dev": "tsc --watch",
|
|
83
83
|
"test": "vitest",
|
|
84
84
|
"test:integration": "vitest run --config vitest.integration.config.ts",
|