@pithyjs/ssr 0.1.2-beta.9 → 0.2.0-beta.13
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.map +1 -1
- package/dist/build/vite-ssg.js +32 -14
- package/dist/build/vite-ssg.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/loaders.js +9 -1
- package/dist/server/loaders.js.map +1 -1
- package/dist/server/render-route.d.ts.map +1 -1
- package/dist/server/render-route.js +2 -1
- package/dist/server/render-route.js.map +1 -1
- package/dist/shared/shell-helpers.d.ts +41 -0
- package/dist/shared/shell-helpers.d.ts.map +1 -1
- package/dist/shared/shell-helpers.js +57 -0
- package/dist/shared/shell-helpers.js.map +1 -1
- package/package.json +4 -4
|
@@ -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;AASpD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;
|
|
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;AASpD,OAAO,EAAE,gBA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,CAAC,EAAE,CAyC9B"}
|
package/dist/build/vite-ssg.js
CHANGED
|
@@ -41,7 +41,7 @@ import { makeLinksRelative } from './relative-links.js';
|
|
|
41
41
|
import { NOT_FOUND_OUTPUT, hasRenderedText } from './not-found.js';
|
|
42
42
|
import { loadSpriteForSsg, clearSpriteForSsg } from './sprite-ssg.js';
|
|
43
43
|
import { readShellHead, resolvePageHead } from './shell-head.js';
|
|
44
|
-
import { injectIntoOutlet, pathToFilePath } from '../shared/shell-helpers.js';
|
|
44
|
+
import { injectIntoOutlet, pathToFilePath, wrapInLayouts, } from '../shared/shell-helpers.js';
|
|
45
45
|
import { entryCollisionKey } from '../shared/entry-path.js';
|
|
46
46
|
// Re-export pathToFilePath for test access (canonical definition in shell-helpers)
|
|
47
47
|
export { pathToFilePath } from '../shared/shell-helpers.js';
|
|
@@ -765,7 +765,9 @@ async function runBuildSSG(options) {
|
|
|
765
765
|
const collectStaticPaths = ssrBuildMod.collectStaticPaths;
|
|
766
766
|
const findRootCatchAllRoute = ssrBuildMod.findRootCatchAllRoute;
|
|
767
767
|
const routerMod = await vite.ssrLoadModule('@pithyjs/router');
|
|
768
|
-
|
|
768
|
+
// A layout-only node shares its pattern with a route it wraps
|
|
769
|
+
const findRouteByPattern = routerMod.findNavigableRoute ?? routerMod.findRouteByPattern;
|
|
770
|
+
const findLayoutChain = routerMod.findLayoutChain ?? (() => []);
|
|
769
771
|
// Load JIT compiler (parse5) for runtime html`` templates.
|
|
770
772
|
// Must run before any renderToString() call.
|
|
771
773
|
// Imported from compile/parseHtml directly (not the barrel) to avoid
|
|
@@ -836,32 +838,48 @@ async function runBuildSSG(options) {
|
|
|
836
838
|
console.log(` SKIP ${routePath} -- no page component`);
|
|
837
839
|
continue;
|
|
838
840
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
841
|
+
// The route's layout.ts files, outermost first, then the page in the
|
|
842
|
+
// innermost outlet. A layout gate (auth, feature flag) redirects
|
|
843
|
+
// before the page is imported or rendered, exactly as a page does.
|
|
844
|
+
const loadPage = routeNode.imports.page;
|
|
845
|
+
let hasDefault = true;
|
|
846
|
+
const wrapped = await wrapInLayouts(findLayoutChain(routes, routeNode).flatMap(n => n.imports.layout ? [n.imports.layout] : []), async () => {
|
|
847
|
+
const PageComponent = (await loadPage()).default;
|
|
848
|
+
if (!PageComponent) {
|
|
849
|
+
hasDefault = false;
|
|
850
|
+
return { html: '' };
|
|
851
|
+
}
|
|
852
|
+
return renderToString({ url: routePath, App: PageComponent });
|
|
853
|
+
}, async (Layout) => {
|
|
854
|
+
const layoutResult = await renderToString({
|
|
855
|
+
url: routePath,
|
|
856
|
+
App: Layout,
|
|
857
|
+
});
|
|
858
|
+
recordLayoutDiagnostics(routePath, layoutResult.layoutDiagnostics);
|
|
859
|
+
return layoutResult;
|
|
860
|
+
}, outletId, '[SSG]');
|
|
861
|
+
if (!hasDefault) {
|
|
842
862
|
console.log(` SKIP ${routePath} -- no default export`);
|
|
843
863
|
continue;
|
|
844
864
|
}
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
url: routePath,
|
|
848
|
-
App: PageComponent,
|
|
849
|
-
});
|
|
850
|
-
if (pageResult.redirectTo) {
|
|
851
|
-
console.log(` REDIRECT ${routePath} -> ${pageResult.redirectTo}`);
|
|
865
|
+
if (wrapped.redirectTo || !wrapped.page) {
|
|
866
|
+
console.log(` REDIRECT ${routePath} -> ${wrapped.redirectTo}`);
|
|
852
867
|
continue;
|
|
853
868
|
}
|
|
869
|
+
const pageResult = wrapped.page;
|
|
854
870
|
// Layout-taint findings are returned, not logged, because
|
|
855
871
|
// `renderToString()` also serves live SSR requests. The static export is
|
|
856
872
|
// the caller that wants them, and it aggregates rather than repeating
|
|
857
873
|
// the same declaration once per page.
|
|
858
874
|
recordLayoutDiagnostics(routePath, pageResult.layoutDiagnostics);
|
|
875
|
+
const outletHtml = wrapped.html;
|
|
876
|
+
const status = wrapped.status;
|
|
859
877
|
// Render App shell per route so layouts reading SSR context
|
|
860
878
|
// (active nav, canonical URL, route-based head) get correct values
|
|
861
879
|
const shellResult = await renderToString({ url: routePath, App });
|
|
862
880
|
const shellHtml = shellResult.html;
|
|
863
881
|
// Inject page HTML into the App shell's outlet
|
|
864
|
-
const finalHtml = injectIntoOutlet(shellHtml,
|
|
882
|
+
const finalHtml = injectIntoOutlet(shellHtml, outletHtml, outletId, '[SSG]');
|
|
865
883
|
// A 404 whose page contributed NOTHING is worse than no 404 at all.
|
|
866
884
|
//
|
|
867
885
|
// `buildSSG` renders the catch-all's page standalone and injects the
|
|
@@ -882,7 +900,7 @@ async function runBuildSSG(options) {
|
|
|
882
900
|
`A page that portals its content out of the outlet cannot be prerendered.`);
|
|
883
901
|
continue;
|
|
884
902
|
}
|
|
885
|
-
console.log(` OK(${
|
|
903
|
+
console.log(` OK(${status}) ${routePath}`);
|
|
886
904
|
pageResults.push({
|
|
887
905
|
job,
|
|
888
906
|
html: finalHtml,
|
|
@@ -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,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,EAClB,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,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;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 { injectIntoOutlet, pathToFilePath } 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 const findRouteByPattern = routerMod.findRouteByPattern;\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 const pageMod = await routeNode.imports.page();\n const PageComponent = pageMod.default;\n\n if (!PageComponent) {\n console.log(` SKIP ${routePath} -- no default export`);\n continue;\n }\n\n // Render the page component\n const pageResult = await renderToString({\n url: routePath,\n App: PageComponent,\n });\n\n if (pageResult.redirectTo) {\n console.log(` REDIRECT ${routePath} -> ${pageResult.redirectTo}`);\n continue;\n }\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\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 pageResult.html,\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(${pageResult.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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,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"]}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -21,6 +21,6 @@ export { renderToString, type RenderToStringOptions } from './render.js';
|
|
|
21
21
|
export { renderRoute, type RenderRouteOptions, type RenderRouteResult, } from './render-route.js';
|
|
22
22
|
export { createSSRWorkerPool, SSRWorkerPool, type SSRWorkerPoolOptions, type WorkerRenderOptions, } from './worker-pool.js';
|
|
23
23
|
export { PithyApp, createApp, type PithyAppOptions, type PithyMiddleware, } from './app.js';
|
|
24
|
-
export { mergeHead, findOutletMatch, injectIntoOutlet, } from '../shared/shell-helpers.js';
|
|
24
|
+
export { mergeHead, findOutletMatch, injectIntoOutlet, wrapInLayouts, type LayoutsResult, type RenderedView, } from '../shared/shell-helpers.js';
|
|
25
25
|
export { generateStaticSite, type GenerateStaticSiteOptions, } from '../build/ssg.js';
|
|
26
26
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;GAIG;AAGH,YAAY,EACV,YAAY,EACZ,UAAU,EACV,cAAc,EACd,YAAY,EACZ,SAAS,EACT,UAAU,EACV,eAAe,EACf,SAAS,GACV,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGjD,OAAO,EACL,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,sBAAsB,EACtB,KAAK,EACL,KAAK,uBAAuB,GAC7B,MAAM,cAAc,CAAC;AAStB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,KAAK,uBAAuB,GAC7B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,iBAAiB,EACjB,KAAK,wBAAwB,EAC7B,KAAK,WAAW,GACjB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,EAC1B,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,oBAAoB,GAC1B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAGzE,OAAO,EACL,WAAW,EACX,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,GACvB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,QAAQ,EACR,SAAS,EACT,KAAK,eAAe,EACpB,KAAK,eAAe,GACrB,MAAM,UAAU,CAAC;AAGlB,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;GAIG;AAGH,YAAY,EACV,YAAY,EACZ,UAAU,EACV,cAAc,EACd,YAAY,EACZ,SAAS,EACT,UAAU,EACV,eAAe,EACf,SAAS,GACV,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGjD,OAAO,EACL,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,sBAAsB,EACtB,KAAK,EACL,KAAK,uBAAuB,GAC7B,MAAM,cAAc,CAAC;AAStB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,KAAK,uBAAuB,GAC7B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,iBAAiB,EACjB,KAAK,wBAAwB,EAC7B,KAAK,WAAW,GACjB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,EAC1B,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,oBAAoB,GAC1B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAGzE,OAAO,EACL,WAAW,EACX,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,GACvB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,QAAQ,EACR,SAAS,EACT,KAAK,eAAe,EACpB,KAAK,eAAe,GACrB,MAAM,UAAU,CAAC;AAGlB,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,YAAY,GAClB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EACL,kBAAkB,EAClB,KAAK,yBAAyB,GAC/B,MAAM,iBAAiB,CAAC"}
|
package/dist/server/index.js
CHANGED
|
@@ -31,7 +31,7 @@ export { createSSRWorkerPool, SSRWorkerPool, } from './worker-pool.js';
|
|
|
31
31
|
// PithyApp API (Task 15 - Request → Response boundary)
|
|
32
32
|
export { PithyApp, createApp, } from './app.js';
|
|
33
33
|
// Shell helpers (shared between SSR dev plugin and SSG build)
|
|
34
|
-
export { mergeHead, findOutletMatch, injectIntoOutlet, } from '../shared/shell-helpers.js';
|
|
34
|
+
export { mergeHead, findOutletMatch, injectIntoOutlet, wrapInLayouts, } from '../shared/shell-helpers.js';
|
|
35
35
|
// SSG Build API (Task 10)
|
|
36
36
|
export { generateStaticSite, } from '../build/ssg.js';
|
|
37
37
|
//# sourceMappingURL=index.js.map
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAoBF,YAAY;AACZ,OAAO,EAAE,WAAW,EAAE,M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,EACjB,sBAAsB,EACtB,KAAK,GAEN,MAAM,cAAc,CAAC;AAEtB,mDAAmD;AACnD,0DAA0D;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,gBAAgB,CAAC,aAAa,CAAC,CAAC;AAEhC,kBAAkB;AAClB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,oBAAoB,GAErB,MAAM,kBAAkB,CAAC;AAE1B,qBAAqB;AACrB,OAAO,EACL,iBAAiB,GAGlB,MAAM,qBAAqB,CAAC;AAE7B,aAAa;AACb,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,GAM3B,MAAM,cAAc,CAAC;AAEtB,0BAA0B;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,oCAAoC;AACpC,OAAO,EAAE,cAAc,EAA8B,MAAM,aAAa,CAAC;AAEzE,iDAAiD;AACjD,OAAO,EACL,WAAW,GAGZ,MAAM,mBAAmB,CAAC;AAE3B,kBAAkB;AAClB,OAAO,EACL,mBAAmB,EACnB,aAAa,GAGd,MAAM,kBAAkB,CAAC;AAE1B,uDAAuD;AACvD,OAAO,EACL,QAAQ,EACR,SAAS,GAGV,MAAM,UAAU,CAAC;AAElB,8DAA8D;AAC9D,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,aAAa,GAGd,MAAM,4BAA4B,CAAC;AAEpC,0BAA0B;AAC1B,OAAO,EACL,kBAAkB,GAEnB,MAAM,iBAAiB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server\",\n \"title\": \"SSR Server Runtime\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr/server - Server-side rendering exports\n *\n * Import from '@pithyjs/ssr/server' for server-side code.\n */\n\n// Types\nexport type {\n RenderResult,\n SSRContext,\n SSREnvironment,\n ShellOptions,\n HeadState,\n HeadConfig,\n SerializedState,\n SSGResult,\n} from '../shared/types.js';\n\n// Constants\nexport { SSR_VERSION } from '../shared/types.js';\n\n// Context API\nexport {\n createSSRContext,\n getSSRContext,\n runWithSSRContext,\n runWithSSRContextAsync,\n isSSR,\n type CreateSSRContextOptions,\n} from './context.js';\n\n// Initialize head API context getter (side effect)\n// This wires up the head() function to access SSR context\nimport { setContextGetter } from '../shared/head.js';\nimport { getSSRContext } from './context.js';\nsetContextGetter(getSSRContext);\n\n// Environment API\nexport {\n setupEnvironment,\n withEnvironment,\n withEnvironmentAsync,\n type SetupEnvironmentOptions,\n} from './environment.js';\n\n// Router Adapter API\nexport {\n SSRHistoryAdapter,\n type SSRHistoryAdapterOptions,\n type SSRRedirect,\n} from './router-adapter.js';\n\n// Loader API\nexport {\n executeSSRLoaders,\n extractLoadersFromRouteTree,\n createSSRLoaderContext,\n serializeLoaderData,\n deserializeLoaderData,\n generateCacheControlHeader,\n type SSRRouteSegment,\n type ExecuteLoadersOptions,\n type ExecuteLoadersResult,\n type SSRCacheHints,\n type SerializedLoaderData,\n} from './loaders.js';\n\n// HTML Shell API (Task 8)\nexport { htmlShell } from './html-shell.js';\n\n// Render API (Task 7 - Implemented)\nexport { renderToString, type RenderToStringOptions } from './render.js';\n\n// Route Render API (Task 12 - Full SSR pipeline)\nexport {\n renderRoute,\n type RenderRouteOptions,\n type RenderRouteResult,\n} from './render-route.js';\n\n// Worker Pool API\nexport {\n createSSRWorkerPool,\n SSRWorkerPool,\n type SSRWorkerPoolOptions,\n type WorkerRenderOptions,\n} from './worker-pool.js';\n\n// PithyApp API (Task 15 - Request → Response boundary)\nexport {\n PithyApp,\n createApp,\n type PithyAppOptions,\n type PithyMiddleware,\n} from './app.js';\n\n// Shell helpers (shared between SSR dev plugin and SSG build)\nexport {\n mergeHead,\n findOutletMatch,\n injectIntoOutlet,\n wrapInLayouts,\n type LayoutsResult,\n type RenderedView,\n} from '../shared/shell-helpers.js';\n\n// SSG Build API (Task 10)\nexport {\n generateStaticSite,\n type GenerateStaticSiteOptions,\n} from '../build/ssg.js';\n"]}
|
package/dist/server/loaders.js
CHANGED
|
@@ -436,7 +436,15 @@ function findMatchingNodeByPattern(nodes, urlPath) {
|
|
|
436
436
|
const nodeByPattern = new Map();
|
|
437
437
|
const patterns = [];
|
|
438
438
|
for (const node of nodes) {
|
|
439
|
-
|
|
439
|
+
// A layout-only directory (a route group's `layout.ts`) is not a route:
|
|
440
|
+
// its loader never runs, so it must not stand in for a URL — least of all
|
|
441
|
+
// one served by an unrelated sibling group that has no page at its own
|
|
442
|
+
// pattern. A route group's layout also shares the pattern of the page it
|
|
443
|
+
// wraps, which then owns that pattern.
|
|
444
|
+
if (node.imports.layout && !node.imports.page)
|
|
445
|
+
continue;
|
|
446
|
+
if (!nodeByPattern.has(node.pattern))
|
|
447
|
+
patterns.push(node.pattern);
|
|
440
448
|
nodeByPattern.set(node.pattern, node);
|
|
441
449
|
}
|
|
442
450
|
// First, check for an exact pattern match (highest priority for SSR loaders)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loaders.js","sourceRoot":"","sources":["../../src/server/loaders.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EACL,mBAAmB,EACnB,aAAa,GAKd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,yDAAyD;AACzD,qFAAqF;AACrF,MAAM,sBAAsB,GAAG,GAAgB,EAAE,CAAC,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAE/E,oCAAoC;AACpC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAEtB,MAAM,oBAAoB,CAAC;AAgH5B,gFAAgF;AAChF,mBAAmB;AACnB,gFAAgF;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,IAAI;YAChB,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;YACxC,SAAS;YACT,SAAS;SACV,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC;QACtB,IAAI,EAAE,OAAO;QACb,SAAS;QACT,SAAS;KACV,CAAC;AACJ,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.loaders\",\n \"title\": \"SSR Loader Execution\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - SSR Loader Execution\n *\n * Executes route loaders during server-side rendering and serializes\n * loader data for client hydration.\n */\n\nimport {\n combineAbortSignals,\n findBestMatch,\n type LoaderFunction,\n type LoaderContext,\n type RouteNode,\n type CacheOptions,\n} from '@pithyjs/router';\nimport { getSSRContext, setLoaderData, setStatus } from './context.js';\nimport { isDev } from './utils.js';\n\n// Create a fresh signal when no AbortSignal is provided.\n// Avoid sharing a singleton to prevent accumulating abort listeners across requests.\nconst createNeverAbortSignal = (): AbortSignal => new AbortController().signal;\n\n// Re-export serialization utilities\nexport {\n serializeLoaderData,\n deserializeLoaderData,\n type SerializedLoaderData,\n} from './serialization.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Route segment with loader information for SSR execution\n */\nexport interface SSRRouteSegment {\n /** Unique route segment ID */\n id: string;\n /** Loader function (if present) */\n loader?: LoaderFunction;\n /** Cache options for this loader */\n cacheOptions?: SSRLoaderCacheOptions;\n}\n\n/**\n * Cache options for SSR loaders (extends router CacheOptions with HTTP-specific fields)\n */\nexport interface SSRLoaderCacheOptions extends CacheOptions {\n /** Whether response can be cached by CDN (public vs private) */\n public?: boolean;\n /** Stale-while-revalidate window in seconds (for HTTP header) */\n swr?: number;\n}\n\n/**\n * Options for SSR loader execution\n */\nexport interface ExecuteLoadersOptions {\n /** Route segments to execute loaders for */\n segments: SSRRouteSegment[];\n /** Route parameters */\n params: Record<string, string>;\n /** Query parameters */\n query: Record<string, string>;\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Whether to continue on loader error (default: false) */\n continueOnError?: boolean;\n}\n\n/**\n * Result from executing a single loader\n */\nexport interface SSRLoaderResult<T = unknown> {\n /** Route segment ID */\n id: string;\n /** Whether loader succeeded */\n success: boolean;\n /** Loader data (if successful) */\n data?: T;\n /** Error (if failed) */\n error?: SSRLoaderError;\n /** Execution time in milliseconds */\n timing: number;\n /** Cache hints from loader config */\n cacheHints?: SSRCacheHints;\n}\n\n/**\n * Loader error details\n */\nexport interface SSRLoaderError {\n /** Error message */\n message: string;\n /** Error name/type */\n name: string;\n /** Stack trace (in development) */\n stack?: string;\n /** Whether this was a timeout */\n isTimeout: boolean;\n /** Whether this was an abort */\n isAborted: boolean;\n}\n\n/**\n * Cache hints for HTTP headers\n */\nexport interface SSRCacheHints {\n /** Cache-Control: public or private */\n public: boolean;\n /** Max-age in seconds */\n maxAge: number;\n /** Stale-while-revalidate in seconds */\n swr?: number;\n /** Whether to skip cache entirely */\n noStore: boolean;\n}\n\n/**\n * Result from executeSSRLoaders\n */\nexport interface ExecuteLoadersResult {\n /** All loader results */\n results: SSRLoaderResult[];\n /** Combined loader data (keyed by segment ID) */\n loaderData: Record<string, unknown>;\n /** Whether all loaders succeeded */\n success: boolean;\n /** First error encountered (if any) */\n firstError?: SSRLoaderError;\n /** Total execution time in milliseconds */\n totalTiming: number;\n /** Aggregated cache hints (most restrictive wins) */\n cacheHints: SSRCacheHints;\n}\n\n// =============================================================================\n// Loader Execution\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"executeSSRLoaders\",\"stability\":\"stable\",\"signature\":\"(options: ExecuteLoadersOptions) => Promise<ExecuteLoadersResult>\"} */\n/**\n * Execute loaders for route segments during SSR\n *\n * Loaders are executed in sequence (parent to child) to allow parent\n * loader data to potentially inform child loaders.\n *\n * @param options - Loader execution options\n * @returns Result containing loader data and status\n *\n * @example\n * ```ts\n * const result = await executeSSRLoaders({\n * segments: [\n * { id: 'root', loader: rootLoader },\n * { id: 'dashboard', loader: dashboardLoader }\n * ],\n * params: { id: '123' },\n * query: { tab: 'settings' }\n * });\n *\n * if (result.success) {\n * console.log('All loaders succeeded:', result.loaderData);\n * }\n * ```\n */\nexport async function executeSSRLoaders(\n options: ExecuteLoadersOptions\n): Promise<ExecuteLoadersResult> {\n const {\n segments,\n params,\n query,\n timeout = 30000,\n signal: externalSignal,\n continueOnError = false,\n } = options;\n\n const startTime = performance.now();\n const results: SSRLoaderResult[] = [];\n const loaderData: Record<string, unknown> = {};\n let firstError: SSRLoaderError | undefined;\n\n // Track timeout state externally (since combineAbortSignals doesn't preserve reason)\n let didTimeout = false;\n\n // Create timeout abort controller\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(() => {\n didTimeout = true;\n timeoutController.abort();\n }, timeout);\n\n // Combine external signal with timeout (only if external signal exists)\n const signal = externalSignal\n ? combineAbortSignals([externalSignal, timeoutController.signal])\n : timeoutController.signal;\n\n // Helper to check if abort was timeout\n const isTimeoutAbort = () => didTimeout && signal.aborted;\n\n try {\n // Execute loaders sequentially (parent to child)\n for (const segment of segments) {\n // Skip segments without loaders\n if (!segment.loader) {\n continue;\n }\n\n // Check if already aborted\n if (signal.aborted) {\n const abortResult = createAbortedResult(segment.id, isTimeoutAbort());\n results.push(abortResult);\n if (!firstError) firstError = abortResult.error;\n break;\n }\n\n // Execute single loader\n const result = await executeSingleLoader(segment, {\n params,\n query,\n signal,\n isTimeoutAbort,\n });\n\n results.push(result);\n\n if (result.success && result.data !== undefined) {\n loaderData[segment.id] = result.data;\n\n // Store in SSR context if available\n const ctx = getSSRContext();\n if (ctx) {\n setLoaderData(segment.id, result.data);\n } else if (isDev()) {\n console.warn(\n `[SSR] Loader data for \"${segment.id}\" was not stored because no SSR context is active. ` +\n 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper hydration.'\n );\n }\n } else if (result.error) {\n if (!firstError) firstError = result.error;\n\n // Stop execution unless continueOnError is true\n if (!continueOnError) {\n break;\n }\n }\n }\n } finally {\n clearTimeout(timeoutId);\n }\n\n const totalTiming = performance.now() - startTime;\n const success = !firstError;\n\n // Set error status in SSR context if any loader failed\n if (!success) {\n const ctx = getSSRContext();\n if (ctx) {\n setStatus(500);\n } else if (isDev()) {\n console.warn(\n '[SSR] Loader error status (500) was not set because executeSSRLoaders() ran without an active SSR context. ' +\n 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper error handling.'\n );\n }\n }\n\n // Calculate aggregated cache hints\n const cacheHints = aggregateCacheHints(results);\n\n return {\n results,\n loaderData,\n success,\n firstError,\n totalTiming,\n cacheHints,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"createSSRLoaderContext\",\"stability\":\"stable\",\"signature\":\"(options: { params: Record<string, string>; query: Record<string, string>; signal?: AbortSignal }) => LoaderContext\"} */\n/**\n * Create a LoaderContext for SSR execution\n *\n * @param options - Context options\n * @returns LoaderContext compatible with router loaders\n *\n * @example\n * ```ts\n * const context = createSSRLoaderContext({\n * params: { id: '123' },\n * query: { filter: 'active' }\n * });\n * const data = await myLoader(context);\n * ```\n */\nexport function createSSRLoaderContext(options: {\n params: Record<string, string>;\n query: Record<string, string>;\n signal?: AbortSignal;\n}): LoaderContext {\n const { params, query, signal } = options;\n\n return {\n params,\n query,\n signal: signal ?? createNeverAbortSignal(),\n // Use 0 as navId for SSR (single request, no navigation tracking)\n navId: 0,\n };\n}\n\n// =============================================================================\n// Single Loader Execution\n// =============================================================================\n\n/**\n * Execute a single loader with error handling\n */\nasync function executeSingleLoader(\n segment: SSRRouteSegment,\n contextOptions: {\n params: Record<string, string>;\n query: Record<string, string>;\n signal: AbortSignal;\n isTimeoutAbort: () => boolean;\n }\n): Promise<SSRLoaderResult> {\n const startTime = performance.now();\n\n // Create loader context\n const context = createSSRLoaderContext(contextOptions);\n\n try {\n // Execute loader (may be sync or async)\n const data = await Promise.resolve(segment.loader!(context));\n\n const timing = performance.now() - startTime;\n\n return {\n id: segment.id,\n success: true,\n data,\n timing,\n cacheHints: deriveCacheHints(segment.cacheOptions),\n };\n } catch (error) {\n const timing = performance.now() - startTime;\n\n return {\n id: segment.id,\n success: false,\n error: normalizeLoaderError(\n error,\n contextOptions.signal,\n contextOptions.isTimeoutAbort\n ),\n timing,\n cacheHints: { public: false, maxAge: 0, noStore: true },\n };\n }\n}\n\n/**\n * Create a result for an aborted loader\n */\nfunction createAbortedResult(id: string, isTimeout: boolean): SSRLoaderResult {\n return {\n id,\n success: false,\n error: {\n message: isTimeout\n ? 'Loader execution timeout'\n : 'Loader execution aborted',\n name: isTimeout ? 'TimeoutError' : 'AbortError',\n isTimeout,\n isAborted: true,\n },\n timing: 0,\n cacheHints: { public: false, maxAge: 0, noStore: true },\n };\n}\n\n// =============================================================================\n// Cache Hints\n// =============================================================================\n\n/**\n * Derive cache hints from loader cache options\n */\nfunction deriveCacheHints(options?: SSRLoaderCacheOptions): SSRCacheHints {\n if (!options) {\n // Default: private, cache for 5 minutes\n return {\n public: false,\n maxAge: 300,\n noStore: false,\n };\n }\n\n if (options.strategy === 'no-store') {\n return {\n public: false,\n maxAge: 0,\n noStore: true,\n };\n }\n\n return {\n public: options.public ?? false,\n maxAge: options.ttl ? Math.floor(options.ttl / 1000) : 300,\n swr: options.swr,\n noStore: false,\n };\n}\n\n/**\n * Aggregate cache hints from multiple loaders (most restrictive wins)\n *\n * Rules:\n * - public/private: Only public if ALL loaders explicitly allow public\n * - maxAge: Shortest wins\n * - swr: Shortest wins\n * - noStore: Any noStore makes result noStore\n */\nfunction aggregateCacheHints(results: SSRLoaderResult[]): SSRCacheHints {\n // Track if ALL loaders allow public caching (most restrictive wins)\n // Starts true, becomes false permanently if ANY loader is private\n let allAllowPublic = true;\n let maxAge = Infinity;\n let swr: number | undefined;\n let noStore = false;\n let hasAnyHints = false;\n\n for (const result of results) {\n const hints = result.cacheHints;\n if (!hints) continue;\n\n hasAnyHints = true;\n\n // no-store is most restrictive - short circuit\n if (hints.noStore) {\n noStore = true;\n continue;\n }\n\n // If ANY loader requires private, result must be private\n // (public only if ALL loaders allow it)\n if (!hints.public) {\n allAllowPublic = false;\n }\n\n // Shortest max-age wins\n if (hints.maxAge < maxAge) {\n maxAge = hints.maxAge;\n }\n\n // Shortest swr wins\n if (hints.swr !== undefined) {\n swr = swr === undefined ? hints.swr : Math.min(swr, hints.swr);\n }\n }\n\n // If no loaders had cache hints, use restrictive defaults\n if (!hasAnyHints || maxAge === Infinity) {\n maxAge = 300;\n }\n\n // Final public status: must have hints, all must allow public, and no noStore\n const isPublic = hasAnyHints && allAllowPublic && !noStore;\n\n return {\n public: isPublic,\n maxAge: noStore ? 0 : maxAge,\n swr: noStore ? undefined : swr,\n noStore,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"generateCacheControlHeader\",\"stability\":\"stable\",\"signature\":\"(hints: SSRCacheHints) => string\"} */\n/**\n * Generate Cache-Control header value from cache hints\n *\n * @param hints - Aggregated cache hints\n * @returns Cache-Control header value\n *\n * @example\n * ```ts\n * const cacheControl = generateCacheControlHeader(result.cacheHints);\n * res.setHeader('Cache-Control', cacheControl);\n * ```\n */\nexport function generateCacheControlHeader(hints: SSRCacheHints): string {\n if (hints.noStore) {\n return 'no-store, no-cache, must-revalidate';\n }\n\n const directives: string[] = [];\n\n directives.push(hints.public ? 'public' : 'private');\n directives.push(`max-age=${hints.maxAge}`);\n\n if (hints.swr !== undefined) {\n directives.push(`stale-while-revalidate=${hints.swr}`);\n }\n\n return directives.join(', ');\n}\n\n// =============================================================================\n// Route Segment Extraction\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"extractLoadersFromRouteTree\",\"stability\":\"stable\",\"signature\":\"(nodes: RouteNode[], matchedPath: string[]) => Promise<SSRRouteSegment[]>\"} */\n/**\n * Extract loader segments from matched route nodes\n *\n * Handles both nested route trees AND flat manifests (where all routes are\n * at the top level with full path patterns like `/dashboard/settings`).\n *\n * @param nodes - Route nodes (may be flat or nested)\n * @param matchedPath - Matched path segments (e.g., ['dashboard', 'settings'])\n * @returns Array of route segments with loaders (parent to child order)\n *\n * @example\n * ```ts\n * const segments = await extractLoadersFromRouteTree(routes, ['dashboard', 'settings']);\n * ```\n */\nexport async function extractLoadersFromRouteTree(\n nodes: RouteNode[],\n matchedPath: string[]\n): Promise<SSRRouteSegment[]> {\n const segments: SSRRouteSegment[] = [];\n\n // Build all URL prefixes from matched path segments\n // e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']\n const prefixes = buildUrlPrefixes(matchedPath);\n\n // Track which route IDs we've already processed to avoid duplicates\n const processedIds = new Set<string>();\n\n // Collect all route nodes (flatten if nested)\n const allNodes = collectAllNodes(nodes);\n\n // For each URL prefix, find matching routes and collect their loaders\n for (const prefix of prefixes) {\n const node = findMatchingNodeByPattern(allNodes, prefix);\n if (!node || processedIds.has(node.id)) continue;\n\n processedIds.add(node.id);\n\n // Load loader if present\n if (node.imports.loader) {\n try {\n const loaderModule = await node.imports.loader();\n const loaderExport = loaderModule.default ?? loaderModule.loader;\n const loader =\n typeof loaderExport === 'function'\n ? (loaderExport as LoaderFunction)\n : undefined;\n\n // Load config for cache options\n let cacheOptions: SSRLoaderCacheOptions | undefined;\n if (node.imports.config) {\n const configModule = await node.imports.config();\n const cache = configModule.cache;\n if (cache && typeof cache === 'object') {\n const { strategy, ttl } = cache as CacheOptions;\n cacheOptions = { strategy, ttl };\n }\n }\n\n segments.push({\n id: node.id,\n loader,\n cacheOptions,\n });\n } catch (error) {\n // Warn in development about failed loader imports\n if (isDev()) {\n console.warn(\n `[SSR] Failed to import loader for route \"${node.id}\":`,\n error instanceof Error ? error.message : error\n );\n }\n }\n }\n }\n\n return segments;\n}\n\n/**\n * Build URL prefixes from path segments\n * e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']\n */\nfunction buildUrlPrefixes(pathSegments: string[]): string[] {\n const prefixes: string[] = ['/'];\n\n let currentPath = '';\n for (const segment of pathSegments) {\n currentPath += '/' + segment;\n prefixes.push(currentPath);\n }\n\n return prefixes;\n}\n\n/**\n * Collect all route nodes (flattens nested tree structure)\n * This ensures we can match routes regardless of whether manifest is flat or nested\n */\nfunction collectAllNodes(nodes: RouteNode[]): RouteNode[] {\n const result: RouteNode[] = [];\n\n for (const node of nodes) {\n result.push(node);\n if (node.children.length > 0) {\n result.push(...collectAllNodes(node.children));\n }\n }\n\n return result;\n}\n\n/**\n * Find a matching node using pattern matching\n *\n * For SSR loader extraction, we prioritize exact pattern matches over catch-all\n * patterns. This ensures parent routes' loaders run even when a child catch-all\n * also matches the URL.\n *\n * Example: For URL prefix '/docs', we want to match pattern '/docs' exactly,\n * not '/docs/*' which would also match but is a child route.\n */\nfunction findMatchingNodeByPattern(\n nodes: RouteNode[],\n urlPath: string\n): RouteNode | undefined {\n // Build pattern-to-node map\n const nodeByPattern = new Map<string, RouteNode>();\n const patterns: string[] = [];\n\n for (const node of nodes) {\n patterns.push(node.pattern);\n nodeByPattern.set(node.pattern, node);\n }\n\n // First, check for an exact pattern match (highest priority for SSR loaders)\n // This ensures parent routes like '/docs' are matched before catch-all '/docs/*'\n if (nodeByPattern.has(urlPath)) {\n return nodeByPattern.get(urlPath);\n }\n\n // Fall back to findBestMatch for dynamic/catch-all patterns\n const match = findBestMatch(urlPath, patterns);\n if (!match) {\n return undefined;\n }\n\n return nodeByPattern.get(match.pattern);\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\n/**\n * Normalize an error into SSRLoaderError format\n */\nfunction normalizeLoaderError(\n error: unknown,\n signal: AbortSignal,\n isTimeoutAbort: () => boolean\n): SSRLoaderError {\n const isAborted = signal.aborted;\n const isTimeout = isTimeoutAbort();\n\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: isDev() ? error.stack : undefined,\n isTimeout,\n isAborted,\n };\n }\n\n return {\n message: String(error),\n name: 'Error',\n isTimeout,\n isAborted,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loaders.js","sourceRoot":"","sources":["../../src/server/loaders.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EACL,mBAAmB,EACnB,aAAa,GAKd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,yDAAyD;AACzD,qFAAqF;AACrF,MAAM,sBAAsB,GAAG,GAAgB,EAAE,CAAC,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAE/E,oCAAoC;AACpC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAEtB,MAAM,oBAAoB,CAAC;AAgH5B,gFAAgF;AAChF,mBAAmB;AACnB,gFAAgF;AAEhF,sLAAsL;AACtL;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAA8B;IAE9B,MAAM,EACJ,QAAQ,EACR,MAAM,EACN,KAAK,EACL,OAAO,GAAG,KAAK,EACf,MAAM,EAAE,cAAc,EACtB,eAAe,GAAG,KAAK,GACxB,GAAG,OAAO,CAAC;IAEZ,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACpC,MAAM,OAAO,GAAsB,EAAE,CAAC;IACtC,MAAM,UAAU,GAA4B,EAAE,CAAC;IAC/C,IAAI,UAAsC,CAAC;IAE3C,qFAAqF;IACrF,IAAI,UAAU,GAAG,KAAK,CAAC;IAEvB,kCAAkC;IAClC,MAAM,iBAAiB,GAAG,IAAI,eAAe,EAAE,CAAC;IAChD,MAAM,SAAS,GAAG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\n \"title\": \"SSR Loader Execution\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - SSR Loader Execution\n *\n * Executes route loaders during server-side rendering and serializes\n * loader data for client hydration.\n */\n\nimport {\n combineAbortSignals,\n findBestMatch,\n type LoaderFunction,\n type LoaderContext,\n type RouteNode,\n type CacheOptions,\n} from '@pithyjs/router';\nimport { getSSRContext, setLoaderData, setStatus } from './context.js';\nimport { isDev } from './utils.js';\n\n// Create a fresh signal when no AbortSignal is provided.\n// Avoid sharing a singleton to prevent accumulating abort listeners across requests.\nconst createNeverAbortSignal = (): AbortSignal => new AbortController().signal;\n\n// Re-export serialization utilities\nexport {\n serializeLoaderData,\n deserializeLoaderData,\n type SerializedLoaderData,\n} from './serialization.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Route segment with loader information for SSR execution\n */\nexport interface SSRRouteSegment {\n /** Unique route segment ID */\n id: string;\n /** Loader function (if present) */\n loader?: LoaderFunction;\n /** Cache options for this loader */\n cacheOptions?: SSRLoaderCacheOptions;\n}\n\n/**\n * Cache options for SSR loaders (extends router CacheOptions with HTTP-specific fields)\n */\nexport interface SSRLoaderCacheOptions extends CacheOptions {\n /** Whether response can be cached by CDN (public vs private) */\n public?: boolean;\n /** Stale-while-revalidate window in seconds (for HTTP header) */\n swr?: number;\n}\n\n/**\n * Options for SSR loader execution\n */\nexport interface ExecuteLoadersOptions {\n /** Route segments to execute loaders for */\n segments: SSRRouteSegment[];\n /** Route parameters */\n params: Record<string, string>;\n /** Query parameters */\n query: Record<string, string>;\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Whether to continue on loader error (default: false) */\n continueOnError?: boolean;\n}\n\n/**\n * Result from executing a single loader\n */\nexport interface SSRLoaderResult<T = unknown> {\n /** Route segment ID */\n id: string;\n /** Whether loader succeeded */\n success: boolean;\n /** Loader data (if successful) */\n data?: T;\n /** Error (if failed) */\n error?: SSRLoaderError;\n /** Execution time in milliseconds */\n timing: number;\n /** Cache hints from loader config */\n cacheHints?: SSRCacheHints;\n}\n\n/**\n * Loader error details\n */\nexport interface SSRLoaderError {\n /** Error message */\n message: string;\n /** Error name/type */\n name: string;\n /** Stack trace (in development) */\n stack?: string;\n /** Whether this was a timeout */\n isTimeout: boolean;\n /** Whether this was an abort */\n isAborted: boolean;\n}\n\n/**\n * Cache hints for HTTP headers\n */\nexport interface SSRCacheHints {\n /** Cache-Control: public or private */\n public: boolean;\n /** Max-age in seconds */\n maxAge: number;\n /** Stale-while-revalidate in seconds */\n swr?: number;\n /** Whether to skip cache entirely */\n noStore: boolean;\n}\n\n/**\n * Result from executeSSRLoaders\n */\nexport interface ExecuteLoadersResult {\n /** All loader results */\n results: SSRLoaderResult[];\n /** Combined loader data (keyed by segment ID) */\n loaderData: Record<string, unknown>;\n /** Whether all loaders succeeded */\n success: boolean;\n /** First error encountered (if any) */\n firstError?: SSRLoaderError;\n /** Total execution time in milliseconds */\n totalTiming: number;\n /** Aggregated cache hints (most restrictive wins) */\n cacheHints: SSRCacheHints;\n}\n\n// =============================================================================\n// Loader Execution\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"executeSSRLoaders\",\"stability\":\"stable\",\"signature\":\"(options: ExecuteLoadersOptions) => Promise<ExecuteLoadersResult>\"} */\n/**\n * Execute loaders for route segments during SSR\n *\n * Loaders are executed in sequence (parent to child) to allow parent\n * loader data to potentially inform child loaders.\n *\n * @param options - Loader execution options\n * @returns Result containing loader data and status\n *\n * @example\n * ```ts\n * const result = await executeSSRLoaders({\n * segments: [\n * { id: 'root', loader: rootLoader },\n * { id: 'dashboard', loader: dashboardLoader }\n * ],\n * params: { id: '123' },\n * query: { tab: 'settings' }\n * });\n *\n * if (result.success) {\n * console.log('All loaders succeeded:', result.loaderData);\n * }\n * ```\n */\nexport async function executeSSRLoaders(\n options: ExecuteLoadersOptions\n): Promise<ExecuteLoadersResult> {\n const {\n segments,\n params,\n query,\n timeout = 30000,\n signal: externalSignal,\n continueOnError = false,\n } = options;\n\n const startTime = performance.now();\n const results: SSRLoaderResult[] = [];\n const loaderData: Record<string, unknown> = {};\n let firstError: SSRLoaderError | undefined;\n\n // Track timeout state externally (since combineAbortSignals doesn't preserve reason)\n let didTimeout = false;\n\n // Create timeout abort controller\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(() => {\n didTimeout = true;\n timeoutController.abort();\n }, timeout);\n\n // Combine external signal with timeout (only if external signal exists)\n const signal = externalSignal\n ? combineAbortSignals([externalSignal, timeoutController.signal])\n : timeoutController.signal;\n\n // Helper to check if abort was timeout\n const isTimeoutAbort = () => didTimeout && signal.aborted;\n\n try {\n // Execute loaders sequentially (parent to child)\n for (const segment of segments) {\n // Skip segments without loaders\n if (!segment.loader) {\n continue;\n }\n\n // Check if already aborted\n if (signal.aborted) {\n const abortResult = createAbortedResult(segment.id, isTimeoutAbort());\n results.push(abortResult);\n if (!firstError) firstError = abortResult.error;\n break;\n }\n\n // Execute single loader\n const result = await executeSingleLoader(segment, {\n params,\n query,\n signal,\n isTimeoutAbort,\n });\n\n results.push(result);\n\n if (result.success && result.data !== undefined) {\n loaderData[segment.id] = result.data;\n\n // Store in SSR context if available\n const ctx = getSSRContext();\n if (ctx) {\n setLoaderData(segment.id, result.data);\n } else if (isDev()) {\n console.warn(\n `[SSR] Loader data for \"${segment.id}\" was not stored because no SSR context is active. ` +\n 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper hydration.'\n );\n }\n } else if (result.error) {\n if (!firstError) firstError = result.error;\n\n // Stop execution unless continueOnError is true\n if (!continueOnError) {\n break;\n }\n }\n }\n } finally {\n clearTimeout(timeoutId);\n }\n\n const totalTiming = performance.now() - startTime;\n const success = !firstError;\n\n // Set error status in SSR context if any loader failed\n if (!success) {\n const ctx = getSSRContext();\n if (ctx) {\n setStatus(500);\n } else if (isDev()) {\n console.warn(\n '[SSR] Loader error status (500) was not set because executeSSRLoaders() ran without an active SSR context. ' +\n 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper error handling.'\n );\n }\n }\n\n // Calculate aggregated cache hints\n const cacheHints = aggregateCacheHints(results);\n\n return {\n results,\n loaderData,\n success,\n firstError,\n totalTiming,\n cacheHints,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"createSSRLoaderContext\",\"stability\":\"stable\",\"signature\":\"(options: { params: Record<string, string>; query: Record<string, string>; signal?: AbortSignal }) => LoaderContext\"} */\n/**\n * Create a LoaderContext for SSR execution\n *\n * @param options - Context options\n * @returns LoaderContext compatible with router loaders\n *\n * @example\n * ```ts\n * const context = createSSRLoaderContext({\n * params: { id: '123' },\n * query: { filter: 'active' }\n * });\n * const data = await myLoader(context);\n * ```\n */\nexport function createSSRLoaderContext(options: {\n params: Record<string, string>;\n query: Record<string, string>;\n signal?: AbortSignal;\n}): LoaderContext {\n const { params, query, signal } = options;\n\n return {\n params,\n query,\n signal: signal ?? createNeverAbortSignal(),\n // Use 0 as navId for SSR (single request, no navigation tracking)\n navId: 0,\n };\n}\n\n// =============================================================================\n// Single Loader Execution\n// =============================================================================\n\n/**\n * Execute a single loader with error handling\n */\nasync function executeSingleLoader(\n segment: SSRRouteSegment,\n contextOptions: {\n params: Record<string, string>;\n query: Record<string, string>;\n signal: AbortSignal;\n isTimeoutAbort: () => boolean;\n }\n): Promise<SSRLoaderResult> {\n const startTime = performance.now();\n\n // Create loader context\n const context = createSSRLoaderContext(contextOptions);\n\n try {\n // Execute loader (may be sync or async)\n const data = await Promise.resolve(segment.loader!(context));\n\n const timing = performance.now() - startTime;\n\n return {\n id: segment.id,\n success: true,\n data,\n timing,\n cacheHints: deriveCacheHints(segment.cacheOptions),\n };\n } catch (error) {\n const timing = performance.now() - startTime;\n\n return {\n id: segment.id,\n success: false,\n error: normalizeLoaderError(\n error,\n contextOptions.signal,\n contextOptions.isTimeoutAbort\n ),\n timing,\n cacheHints: { public: false, maxAge: 0, noStore: true },\n };\n }\n}\n\n/**\n * Create a result for an aborted loader\n */\nfunction createAbortedResult(id: string, isTimeout: boolean): SSRLoaderResult {\n return {\n id,\n success: false,\n error: {\n message: isTimeout\n ? 'Loader execution timeout'\n : 'Loader execution aborted',\n name: isTimeout ? 'TimeoutError' : 'AbortError',\n isTimeout,\n isAborted: true,\n },\n timing: 0,\n cacheHints: { public: false, maxAge: 0, noStore: true },\n };\n}\n\n// =============================================================================\n// Cache Hints\n// =============================================================================\n\n/**\n * Derive cache hints from loader cache options\n */\nfunction deriveCacheHints(options?: SSRLoaderCacheOptions): SSRCacheHints {\n if (!options) {\n // Default: private, cache for 5 minutes\n return {\n public: false,\n maxAge: 300,\n noStore: false,\n };\n }\n\n if (options.strategy === 'no-store') {\n return {\n public: false,\n maxAge: 0,\n noStore: true,\n };\n }\n\n return {\n public: options.public ?? false,\n maxAge: options.ttl ? Math.floor(options.ttl / 1000) : 300,\n swr: options.swr,\n noStore: false,\n };\n}\n\n/**\n * Aggregate cache hints from multiple loaders (most restrictive wins)\n *\n * Rules:\n * - public/private: Only public if ALL loaders explicitly allow public\n * - maxAge: Shortest wins\n * - swr: Shortest wins\n * - noStore: Any noStore makes result noStore\n */\nfunction aggregateCacheHints(results: SSRLoaderResult[]): SSRCacheHints {\n // Track if ALL loaders allow public caching (most restrictive wins)\n // Starts true, becomes false permanently if ANY loader is private\n let allAllowPublic = true;\n let maxAge = Infinity;\n let swr: number | undefined;\n let noStore = false;\n let hasAnyHints = false;\n\n for (const result of results) {\n const hints = result.cacheHints;\n if (!hints) continue;\n\n hasAnyHints = true;\n\n // no-store is most restrictive - short circuit\n if (hints.noStore) {\n noStore = true;\n continue;\n }\n\n // If ANY loader requires private, result must be private\n // (public only if ALL loaders allow it)\n if (!hints.public) {\n allAllowPublic = false;\n }\n\n // Shortest max-age wins\n if (hints.maxAge < maxAge) {\n maxAge = hints.maxAge;\n }\n\n // Shortest swr wins\n if (hints.swr !== undefined) {\n swr = swr === undefined ? hints.swr : Math.min(swr, hints.swr);\n }\n }\n\n // If no loaders had cache hints, use restrictive defaults\n if (!hasAnyHints || maxAge === Infinity) {\n maxAge = 300;\n }\n\n // Final public status: must have hints, all must allow public, and no noStore\n const isPublic = hasAnyHints && allAllowPublic && !noStore;\n\n return {\n public: isPublic,\n maxAge: noStore ? 0 : maxAge,\n swr: noStore ? undefined : swr,\n noStore,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"generateCacheControlHeader\",\"stability\":\"stable\",\"signature\":\"(hints: SSRCacheHints) => string\"} */\n/**\n * Generate Cache-Control header value from cache hints\n *\n * @param hints - Aggregated cache hints\n * @returns Cache-Control header value\n *\n * @example\n * ```ts\n * const cacheControl = generateCacheControlHeader(result.cacheHints);\n * res.setHeader('Cache-Control', cacheControl);\n * ```\n */\nexport function generateCacheControlHeader(hints: SSRCacheHints): string {\n if (hints.noStore) {\n return 'no-store, no-cache, must-revalidate';\n }\n\n const directives: string[] = [];\n\n directives.push(hints.public ? 'public' : 'private');\n directives.push(`max-age=${hints.maxAge}`);\n\n if (hints.swr !== undefined) {\n directives.push(`stale-while-revalidate=${hints.swr}`);\n }\n\n return directives.join(', ');\n}\n\n// =============================================================================\n// Route Segment Extraction\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"extractLoadersFromRouteTree\",\"stability\":\"stable\",\"signature\":\"(nodes: RouteNode[], matchedPath: string[]) => Promise<SSRRouteSegment[]>\"} */\n/**\n * Extract loader segments from matched route nodes\n *\n * Handles both nested route trees AND flat manifests (where all routes are\n * at the top level with full path patterns like `/dashboard/settings`).\n *\n * @param nodes - Route nodes (may be flat or nested)\n * @param matchedPath - Matched path segments (e.g., ['dashboard', 'settings'])\n * @returns Array of route segments with loaders (parent to child order)\n *\n * @example\n * ```ts\n * const segments = await extractLoadersFromRouteTree(routes, ['dashboard', 'settings']);\n * ```\n */\nexport async function extractLoadersFromRouteTree(\n nodes: RouteNode[],\n matchedPath: string[]\n): Promise<SSRRouteSegment[]> {\n const segments: SSRRouteSegment[] = [];\n\n // Build all URL prefixes from matched path segments\n // e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']\n const prefixes = buildUrlPrefixes(matchedPath);\n\n // Track which route IDs we've already processed to avoid duplicates\n const processedIds = new Set<string>();\n\n // Collect all route nodes (flatten if nested)\n const allNodes = collectAllNodes(nodes);\n\n // For each URL prefix, find matching routes and collect their loaders\n for (const prefix of prefixes) {\n const node = findMatchingNodeByPattern(allNodes, prefix);\n if (!node || processedIds.has(node.id)) continue;\n\n processedIds.add(node.id);\n\n // Load loader if present\n if (node.imports.loader) {\n try {\n const loaderModule = await node.imports.loader();\n const loaderExport = loaderModule.default ?? loaderModule.loader;\n const loader =\n typeof loaderExport === 'function'\n ? (loaderExport as LoaderFunction)\n : undefined;\n\n // Load config for cache options\n let cacheOptions: SSRLoaderCacheOptions | undefined;\n if (node.imports.config) {\n const configModule = await node.imports.config();\n const cache = configModule.cache;\n if (cache && typeof cache === 'object') {\n const { strategy, ttl } = cache as CacheOptions;\n cacheOptions = { strategy, ttl };\n }\n }\n\n segments.push({\n id: node.id,\n loader,\n cacheOptions,\n });\n } catch (error) {\n // Warn in development about failed loader imports\n if (isDev()) {\n console.warn(\n `[SSR] Failed to import loader for route \"${node.id}\":`,\n error instanceof Error ? error.message : error\n );\n }\n }\n }\n }\n\n return segments;\n}\n\n/**\n * Build URL prefixes from path segments\n * e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']\n */\nfunction buildUrlPrefixes(pathSegments: string[]): string[] {\n const prefixes: string[] = ['/'];\n\n let currentPath = '';\n for (const segment of pathSegments) {\n currentPath += '/' + segment;\n prefixes.push(currentPath);\n }\n\n return prefixes;\n}\n\n/**\n * Collect all route nodes (flattens nested tree structure)\n * This ensures we can match routes regardless of whether manifest is flat or nested\n */\nfunction collectAllNodes(nodes: RouteNode[]): RouteNode[] {\n const result: RouteNode[] = [];\n\n for (const node of nodes) {\n result.push(node);\n if (node.children.length > 0) {\n result.push(...collectAllNodes(node.children));\n }\n }\n\n return result;\n}\n\n/**\n * Find a matching node using pattern matching\n *\n * For SSR loader extraction, we prioritize exact pattern matches over catch-all\n * patterns. This ensures parent routes' loaders run even when a child catch-all\n * also matches the URL.\n *\n * Example: For URL prefix '/docs', we want to match pattern '/docs' exactly,\n * not '/docs/*' which would also match but is a child route.\n */\nfunction findMatchingNodeByPattern(\n nodes: RouteNode[],\n urlPath: string\n): RouteNode | undefined {\n // Build pattern-to-node map\n const nodeByPattern = new Map<string, RouteNode>();\n const patterns: string[] = [];\n\n for (const node of nodes) {\n // A layout-only directory (a route group's `layout.ts`) is not a route:\n // its loader never runs, so it must not stand in for a URL — least of all\n // one served by an unrelated sibling group that has no page at its own\n // pattern. A route group's layout also shares the pattern of the page it\n // wraps, which then owns that pattern.\n if (node.imports.layout && !node.imports.page) continue;\n if (!nodeByPattern.has(node.pattern)) patterns.push(node.pattern);\n nodeByPattern.set(node.pattern, node);\n }\n\n // First, check for an exact pattern match (highest priority for SSR loaders)\n // This ensures parent routes like '/docs' are matched before catch-all '/docs/*'\n if (nodeByPattern.has(urlPath)) {\n return nodeByPattern.get(urlPath);\n }\n\n // Fall back to findBestMatch for dynamic/catch-all patterns\n const match = findBestMatch(urlPath, patterns);\n if (!match) {\n return undefined;\n }\n\n return nodeByPattern.get(match.pattern);\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\n/**\n * Normalize an error into SSRLoaderError format\n */\nfunction normalizeLoaderError(\n error: unknown,\n signal: AbortSignal,\n isTimeoutAbort: () => boolean\n): SSRLoaderError {\n const isAborted = signal.aborted;\n const isTimeout = isTimeoutAbort();\n\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: isDev() ? error.stack : undefined,\n isTimeout,\n isAborted,\n };\n }\n\n return {\n message: String(error),\n name: 'Error',\n isTimeout,\n isAborted,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-route.d.ts","sourceRoot":"","sources":["../../src/server/render-route.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,UAAU,EAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAElE,OAAO,EAIL,KAAK,oBAAoB,EAC1B,MAAM,cAAc,CAAC;AAMtB;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,sDAAsD;IACtD,GAAG,EAAE,MAAM,CAAC;IACZ,mCAAmC;IACnC,GAAG,EAAE,SAAS,CAAC;IACf,0CAA0C;IAC1C,MAAM,EAAE,SAAS,EAAE,CAAC;IACpB,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,wCAAwC;IACxC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yBAAyB;IACzB,IAAI,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1B,0IAA0I;IAC1I,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,oCAAoC;IACpC,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAkB,SAAQ,YAAY;IACrD,qFAAqF;IACrF,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,4DAA4D;IAC5D,YAAY,CAAC,EAAE,oBAAoB,CAAC;IACpC,mEAAmE;IACnE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAMD,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;IAC5D,YAAY,CAAC,EAAE,oBAAoB,CAAC;IACpC,mEAAmE;IACnE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAMD,qLAAqL;AACrL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,iBAAiB,CAAC,CA0J5B"}
|
|
@@ -67,7 +67,8 @@ export async function renderRoute(options) {
|
|
|
67
67
|
query[key] = value;
|
|
68
68
|
});
|
|
69
69
|
// 2. Match URL against route tree
|
|
70
|
-
|
|
70
|
+
// A layout-only node wraps routes; it is never a destination itself
|
|
71
|
+
const flatRoutes = flattenRouteTree(routes).filter(e => e.node.imports.page || !e.node.imports.layout);
|
|
71
72
|
const entry = findMatchingEntry(urlPath, flatRoutes);
|
|
72
73
|
if (!entry) {
|
|
73
74
|
// No matching route — render with 404 status
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-route.js","sourceRoot":"","sources":["../../src/server/render-route.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAYF,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,GAGX,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,GAE3B,MAAM,cAAc,CAAC;AA4CtB,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF,qLAAqL;AACrL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,OAA2B;IAE3B,MAAM,EACJ,GAAG,EACH,GAAG,EACH,MAAM,EACN,OAAO,EACP,KAAK,EACL,IAAI,EACJ,MAAM,EACN,aAAa,EACb,eAAe,GAAG,KAAK,EACvB,MAAM,GACP,GAAG,O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eline\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - Full SSR Route Pipeline\n *\n * High-level `renderRoute()` function that orchestrates the complete SSR pipeline:\n * URL → route match → loader execution → component render → HTML output.\n *\n * For manual orchestration, use `renderToString()` directly.\n */\n\nimport type { Component } from '@pithyjs/core';\nimport {\n flattenRouteTree,\n findMatchingEntry,\n matchRoute,\n type RouteNode,\n type RouteMatch,\n} from '@pithyjs/router';\nimport type { RenderResult, HeadState } from '../shared/types.js';\nimport { renderToString } from './render.js';\nimport {\n executeSSRLoaders,\n extractLoadersFromRouteTree,\n generateCacheControlHeader,\n type ExecuteLoadersResult,\n} from './loaders.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for renderRoute()\n */\nexport interface RenderRouteOptions {\n /** URL to render (e.g., '/dashboard?tab=settings') */\n url: string;\n /** The root component to render */\n App: Component;\n /** Route tree from the router manifest */\n routes: RouteNode[];\n /** Additional context to pass to components */\n context?: Record<string, unknown>;\n /** App container ID (default: 'app') */\n appId?: string;\n /** Initial head state */\n head?: Partial<HeadState>;\n /** Initial HTTP status code (default: 200; preserved when set, otherwise falls back to 404 if no route matches or 500 on loader error) */\n status?: number;\n /** Loader execution timeout in milliseconds (default: 30000) */\n loaderTimeout?: number;\n /** Whether to continue rendering after a loader error (default: false) */\n continueOnError?: boolean;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Result from renderRoute(), extends RenderResult with route-specific data\n */\nexport interface RenderRouteResult extends RenderResult {\n /** The route match result with params and pattern (undefined if no route matched) */\n routeMatch?: RouteMatch;\n /** Loader execution result (undefined if no loaders ran) */\n loaderResult?: ExecuteLoadersResult;\n /** Generated Cache-Control header value from loader cache hints */\n cacheControl?: string;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.render-route\",\"name\":\"renderRoute\",\"stability\":\"experimental\",\"signature\":\"(options: RenderRouteOptions) => Promise<RenderRouteResult>\"} */\n/**\n * Render a route to HTML with automatic route matching and loader execution.\n *\n * This is the high-level SSR entry point that handles the complete pipeline:\n * 1. Parse URL into path and query\n * 2. Match URL against route tree\n * 3. Extract route parameters\n * 4. Execute route loaders\n * 5. Render the component with all data\n * 6. Return HTML with cache hints\n *\n * For manual control over each step, use `renderToString()` directly.\n *\n * @param options - Route render options\n * @returns Rendered HTML with route-specific metadata\n *\n * @example Basic usage\n * ```ts\n * const result = await renderRoute({\n * url: '/dashboard',\n * App,\n * routes,\n * });\n *\n * if (result.redirectTo) {\n * res.redirect(result.status, result.redirectTo);\n * } else {\n * res.status(result.status).send(htmlShell({\n * html: result.html,\n * head: result.head,\n * state: result.state,\n * scripts: ['/entry-client.js'],\n * }));\n * }\n * ```\n *\n * @example With cache headers\n * ```ts\n * const result = await renderRoute({ url: '/blog/123', App, routes });\n * if (result.cacheControl) {\n * res.setHeader('Cache-Control', result.cacheControl);\n * }\n * ```\n */\nexport async function renderRoute(\n options: RenderRouteOptions\n): Promise<RenderRouteResult> {\n const {\n url,\n App,\n routes,\n context,\n appId,\n head,\n status,\n loaderTimeout,\n continueOnError = false,\n signal,\n } = options;\n\n // 1. Parse URL into path and query\n const routeMatchStart = performance.now();\n const urlObj = new URL(url, 'http://localhost');\n const urlPath = urlObj.pathname;\n const query: Record<string, string> = {};\n urlObj.searchParams.forEach((value, key) => {\n query[key] = value;\n });\n\n // 2. Match URL against route tree\n const flatRoutes = flattenRouteTree(routes);\n const entry = findMatchingEntry(urlPath, flatRoutes);\n\n if (!entry) {\n // No matching route — render with 404 status\n const routeMatchTime = performance.now() - routeMatchStart;\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n head,\n query,\n status: status ?? 404,\n });\n\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.total += routeMatchTime;\n }\n\n return {\n ...result,\n routeMatch: undefined,\n loaderResult: undefined,\n cacheControl: undefined,\n };\n }\n\n // 3. Extract params from matched route\n const routeMatchResult = matchRoute(urlPath, entry.node.pattern);\n const routeMatchTime = performance.now() - routeMatchStart;\n\n // Defensive: matchRoute returned null despite findMatchingEntry succeeding.\n // This shouldn't happen in practice, but guard against edge cases.\n if (!routeMatchResult) {\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n head,\n query,\n status: status ?? 404,\n });\n\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.total += routeMatchTime;\n }\n\n return {\n ...result,\n routeMatch: undefined,\n loaderResult: undefined,\n cacheControl: undefined,\n };\n }\n\n const params: Record<string, string> = {};\n if (routeMatchResult.params) {\n // Flatten params (RouteParams may have string | string[] values)\n for (const [key, value] of Object.entries(routeMatchResult.params)) {\n params[key] = Array.isArray(value) ? value.join('/') : String(value);\n }\n }\n\n // 4. Extract loaders from ancestor chain + matched route\n const matchedSegments = routeMatchResult.segments ?? [];\n const segments = await extractLoadersFromRouteTree(routes, matchedSegments);\n\n // 5. Execute loaders (outside SSR environment — loaders are pure data fetching)\n let loaderResult: ExecuteLoadersResult | undefined;\n let loaderData: Record<string, unknown> = {};\n\n if (segments.length > 0) {\n loaderResult = await executeSSRLoaders({\n segments,\n params,\n query,\n timeout: loaderTimeout,\n signal,\n continueOnError,\n });\n loaderData = loaderResult.loaderData;\n }\n\n // 6. Determine status code\n let resolvedStatus = status ?? 200;\n if (loaderResult && !loaderResult.success && resolvedStatus === 200) {\n resolvedStatus = 500;\n }\n\n // 7. Render the component with all collected data\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n params,\n query,\n loaderData,\n head,\n status: resolvedStatus,\n });\n\n // 8. Overlay route matching and loader timing onto the render timing.\n // renderToString reports routeMatch=0 and loaders=0 since it doesn't\n // orchestrate those phases — renderRoute does.\n const loaderTime = loaderResult?.totalTiming ?? 0;\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.loaders = loaderTime;\n result.timing.total += routeMatchTime + loaderTime;\n }\n\n // 9. Generate cache control header\n const cacheControl = loaderResult\n ? generateCacheControlHeader(loaderResult.cacheHints)\n : undefined;\n\n return {\n ...result,\n routeMatch: routeMatchResult,\n loaderResult,\n cacheControl,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"render-route.js","sourceRoot":"","sources":["../../src/server/render-route.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAYF,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,GAGX,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,GAE3B,MAAM,cAAc,CAAC;AA4CtB,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF,qLAAqL;AACrL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,OAA2B;IAE3B,MAAM,EACJ,GAAG,EACH,GAAG,EACH,MAAM,EACN,OAAO,EACP,KAAK,EACL,IAAI,EACJ,MAAM,EACN,aAAa,EACb,eAAe,GAAG,KAAK,EACvB,MAAM,GACP,GAAG,OAAO,CAAC;IAEZ,mCAAmC;IACnC,MAAM,eAAe,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,kBAAkB,CAAC,CAAC;IAChD,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC;IAChC,MAAM,KAAK,GAA2B,EAAE,CAAC;IACzC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACzC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,kCAAkC;IAClC,oEAAoE;IACpE,MAAM,UAAU,GAAG,gBAAgB,CAAC,MAAM,CAAC,CAAC,MAAM,CAChD,CAAC,CAAC,EAAE,CAAC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CAAC;QACpE,cAAc,GAAG,GAAG,CAAC;IACvB,CAAC;IAED,kDAAkD;IAClD,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC;QAClC,GAAG;QACH,GAAG;QACH,OAAO;QACP,KAAK;QACL,MAAM;QACN,KAAK;QACL,UAAU;QACV,IAAI;QACJ,MAAM,EAAE,cAAc;KACvB,CAAC,CAAC;IAEH,sEAAsE;IACtE,qEAAqE;IACrE,+CAA+C;IAC/C,MAAM,UAAU,GAAG,YAAY,EAAE,WAAW,IAAI,CAAC,CAAC;IAClD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAClB,MAAM,CAAC,MAAM,CAAC,UAAU,GAAG,cAAc,CAAC;QAC1C,MAAM,CAAC,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC;QACnC,MAAM,CAAC,MAAM,CAAC,KAAK,IAAI,cAAc,GAAG,UAAU,CAAC;IACrD,CAAC;IAED,mCAAmC;IACnC,MAAM,YAAY,GAAG,YAAY;QAC/B,CAAC,CAAC,0BAA0B,CAAC,YAAY,CAAC,UAAU,CAAC;QACrD,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO;QACL,GAAG,MAAM;QACT,UAAU,EAAE,gBAAgB;QAC5B,YAAY;QACZ,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.render-route\",\n \"title\": \"SSR Route Rendering Pipeline\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - Full SSR Route Pipeline\n *\n * High-level `renderRoute()` function that orchestrates the complete SSR pipeline:\n * URL → route match → loader execution → component render → HTML output.\n *\n * For manual orchestration, use `renderToString()` directly.\n */\n\nimport type { Component } from '@pithyjs/core';\nimport {\n flattenRouteTree,\n findMatchingEntry,\n matchRoute,\n type RouteNode,\n type RouteMatch,\n} from '@pithyjs/router';\nimport type { RenderResult, HeadState } from '../shared/types.js';\nimport { renderToString } from './render.js';\nimport {\n executeSSRLoaders,\n extractLoadersFromRouteTree,\n generateCacheControlHeader,\n type ExecuteLoadersResult,\n} from './loaders.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for renderRoute()\n */\nexport interface RenderRouteOptions {\n /** URL to render (e.g., '/dashboard?tab=settings') */\n url: string;\n /** The root component to render */\n App: Component;\n /** Route tree from the router manifest */\n routes: RouteNode[];\n /** Additional context to pass to components */\n context?: Record<string, unknown>;\n /** App container ID (default: 'app') */\n appId?: string;\n /** Initial head state */\n head?: Partial<HeadState>;\n /** Initial HTTP status code (default: 200; preserved when set, otherwise falls back to 404 if no route matches or 500 on loader error) */\n status?: number;\n /** Loader execution timeout in milliseconds (default: 30000) */\n loaderTimeout?: number;\n /** Whether to continue rendering after a loader error (default: false) */\n continueOnError?: boolean;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Result from renderRoute(), extends RenderResult with route-specific data\n */\nexport interface RenderRouteResult extends RenderResult {\n /** The route match result with params and pattern (undefined if no route matched) */\n routeMatch?: RouteMatch;\n /** Loader execution result (undefined if no loaders ran) */\n loaderResult?: ExecuteLoadersResult;\n /** Generated Cache-Control header value from loader cache hints */\n cacheControl?: string;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.render-route\",\"name\":\"renderRoute\",\"stability\":\"experimental\",\"signature\":\"(options: RenderRouteOptions) => Promise<RenderRouteResult>\"} */\n/**\n * Render a route to HTML with automatic route matching and loader execution.\n *\n * This is the high-level SSR entry point that handles the complete pipeline:\n * 1. Parse URL into path and query\n * 2. Match URL against route tree\n * 3. Extract route parameters\n * 4. Execute route loaders\n * 5. Render the component with all data\n * 6. Return HTML with cache hints\n *\n * For manual control over each step, use `renderToString()` directly.\n *\n * @param options - Route render options\n * @returns Rendered HTML with route-specific metadata\n *\n * @example Basic usage\n * ```ts\n * const result = await renderRoute({\n * url: '/dashboard',\n * App,\n * routes,\n * });\n *\n * if (result.redirectTo) {\n * res.redirect(result.status, result.redirectTo);\n * } else {\n * res.status(result.status).send(htmlShell({\n * html: result.html,\n * head: result.head,\n * state: result.state,\n * scripts: ['/entry-client.js'],\n * }));\n * }\n * ```\n *\n * @example With cache headers\n * ```ts\n * const result = await renderRoute({ url: '/blog/123', App, routes });\n * if (result.cacheControl) {\n * res.setHeader('Cache-Control', result.cacheControl);\n * }\n * ```\n */\nexport async function renderRoute(\n options: RenderRouteOptions\n): Promise<RenderRouteResult> {\n const {\n url,\n App,\n routes,\n context,\n appId,\n head,\n status,\n loaderTimeout,\n continueOnError = false,\n signal,\n } = options;\n\n // 1. Parse URL into path and query\n const routeMatchStart = performance.now();\n const urlObj = new URL(url, 'http://localhost');\n const urlPath = urlObj.pathname;\n const query: Record<string, string> = {};\n urlObj.searchParams.forEach((value, key) => {\n query[key] = value;\n });\n\n // 2. Match URL against route tree\n // A layout-only node wraps routes; it is never a destination itself\n const flatRoutes = flattenRouteTree(routes).filter(\n e => e.node.imports.page || !e.node.imports.layout\n );\n const entry = findMatchingEntry(urlPath, flatRoutes);\n\n if (!entry) {\n // No matching route — render with 404 status\n const routeMatchTime = performance.now() - routeMatchStart;\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n head,\n query,\n status: status ?? 404,\n });\n\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.total += routeMatchTime;\n }\n\n return {\n ...result,\n routeMatch: undefined,\n loaderResult: undefined,\n cacheControl: undefined,\n };\n }\n\n // 3. Extract params from matched route\n const routeMatchResult = matchRoute(urlPath, entry.node.pattern);\n const routeMatchTime = performance.now() - routeMatchStart;\n\n // Defensive: matchRoute returned null despite findMatchingEntry succeeding.\n // This shouldn't happen in practice, but guard against edge cases.\n if (!routeMatchResult) {\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n head,\n query,\n status: status ?? 404,\n });\n\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.total += routeMatchTime;\n }\n\n return {\n ...result,\n routeMatch: undefined,\n loaderResult: undefined,\n cacheControl: undefined,\n };\n }\n\n const params: Record<string, string> = {};\n if (routeMatchResult.params) {\n // Flatten params (RouteParams may have string | string[] values)\n for (const [key, value] of Object.entries(routeMatchResult.params)) {\n params[key] = Array.isArray(value) ? value.join('/') : String(value);\n }\n }\n\n // 4. Extract loaders from ancestor chain + matched route\n const matchedSegments = routeMatchResult.segments ?? [];\n const segments = await extractLoadersFromRouteTree(routes, matchedSegments);\n\n // 5. Execute loaders (outside SSR environment — loaders are pure data fetching)\n let loaderResult: ExecuteLoadersResult | undefined;\n let loaderData: Record<string, unknown> = {};\n\n if (segments.length > 0) {\n loaderResult = await executeSSRLoaders({\n segments,\n params,\n query,\n timeout: loaderTimeout,\n signal,\n continueOnError,\n });\n loaderData = loaderResult.loaderData;\n }\n\n // 6. Determine status code\n let resolvedStatus = status ?? 200;\n if (loaderResult && !loaderResult.success && resolvedStatus === 200) {\n resolvedStatus = 500;\n }\n\n // 7. Render the component with all collected data\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n params,\n query,\n loaderData,\n head,\n status: resolvedStatus,\n });\n\n // 8. Overlay route matching and loader timing onto the render timing.\n // renderToString reports routeMatch=0 and loaders=0 since it doesn't\n // orchestrate those phases — renderRoute does.\n const loaderTime = loaderResult?.totalTiming ?? 0;\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.loaders = loaderTime;\n result.timing.total += routeMatchTime + loaderTime;\n }\n\n // 9. Generate cache control header\n const cacheControl = loaderResult\n ? generateCacheControlHeader(loaderResult.cacheHints)\n : undefined;\n\n return {\n ...result,\n routeMatch: routeMatchResult,\n loaderResult,\n cacheControl,\n };\n}\n"]}
|
|
@@ -66,4 +66,45 @@ export declare function findOutletMatch(shellHtml: string, outletId: string): Re
|
|
|
66
66
|
* @param logPrefix - Prefix for warning messages (e.g. '[SSG]' or '[pithy-ssr]')
|
|
67
67
|
*/
|
|
68
68
|
export declare function injectIntoOutlet(shellHtml: string, pageHtml: string, outletId: string, logPrefix?: string): string;
|
|
69
|
+
/** One rendered view: a layout or a page. */
|
|
70
|
+
export interface RenderedView {
|
|
71
|
+
html: string;
|
|
72
|
+
redirectTo?: string | undefined;
|
|
73
|
+
status?: number | undefined;
|
|
74
|
+
}
|
|
75
|
+
/** What rendering a route's layouts and page decided. */
|
|
76
|
+
export interface LayoutsResult<Page extends RenderedView = RenderedView> {
|
|
77
|
+
/** The page inside its layouts; empty on a redirect. */
|
|
78
|
+
html: string;
|
|
79
|
+
/**
|
|
80
|
+
* Set when a layout or the page called `setRedirect()`: the outermost one
|
|
81
|
+
* wins, and nothing inside it renders.
|
|
82
|
+
*/
|
|
83
|
+
redirectTo?: string;
|
|
84
|
+
/**
|
|
85
|
+
* The response status. A redirect's is always a 3xx (302 unless it set
|
|
86
|
+
* another). Otherwise the outermost layout's non-200 status, else the
|
|
87
|
+
* page's own.
|
|
88
|
+
*/
|
|
89
|
+
status?: number;
|
|
90
|
+
/** The page's render result; absent when a layout redirected. */
|
|
91
|
+
page?: Page;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Render a route: its layouts outermost first, then the page in the
|
|
95
|
+
* innermost outlet — the DOM the client router builds for the same route, so
|
|
96
|
+
* its first mount replaces it one for one.
|
|
97
|
+
*
|
|
98
|
+
* Each layout renders before anything inside it: one that redirects (an auth
|
|
99
|
+
* gate) decides for everything it wraps, so neither an inner layout nor the
|
|
100
|
+
* page is rendered or imported. A layout without an outlet is rejected, as
|
|
101
|
+
* the client router renders an error for it rather than dropping the page.
|
|
102
|
+
*
|
|
103
|
+
* @param layouts - The route's layout imports, outermost first.
|
|
104
|
+
* @param renderPage - Renders the page, once every layout let it through.
|
|
105
|
+
* @param render - Renders one layout component.
|
|
106
|
+
* @param outletId - Outlet id fallback for a layout without `@routerOutlet`.
|
|
107
|
+
* @param logPrefix - Prefix for warning and error messages.
|
|
108
|
+
*/
|
|
109
|
+
export declare function wrapInLayouts<Page extends RenderedView>(layouts: Array<() => Promise<Record<string, unknown>>>, renderPage: () => Promise<Page>, render: (layout: unknown) => Promise<RenderedView>, outletId: string, logPrefix?: string): Promise<LayoutsResult<Page>>;
|
|
69
110
|
//# sourceMappingURL=shell-helpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-helpers.d.ts","sourceRoot":"","sources":["../../src/shared/shell-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAW,MAAM,YAAY,CAAC;AAOrD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAgBtD;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,EACzB,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC,GACvB,SAAS,CAeX;AAMD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,GACf,gBAAgB,GAAG,IAAI,CAczB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,SAAS,SAAU,GAClB,MAAM,CAwDR"}
|
|
1
|
+
{"version":3,"file":"shell-helpers.d.ts","sourceRoot":"","sources":["../../src/shared/shell-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAW,MAAM,YAAY,CAAC;AAOrD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAgBtD;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,EACzB,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC,G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} Could not find matching </${tagName}> for outlet. Using page HTML only.`);
|
|
158
158
|
return pageHtml;
|
|
159
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Render a route: its layouts outermost first, then the page in the
|
|
162
|
+
* innermost outlet — the DOM the client router builds for the same route, so
|
|
163
|
+
* its first mount replaces it one for one.
|
|
164
|
+
*
|
|
165
|
+
* Each layout renders before anything inside it: one that redirects (an auth
|
|
166
|
+
* gate) decides for everything it wraps, so neither an inner layout nor the
|
|
167
|
+
* page is rendered or imported. A layout without an outlet is rejected, as
|
|
168
|
+
* the client router renders an error for it rather than dropping the page.
|
|
169
|
+
*
|
|
170
|
+
* @param layouts - The route's layout imports, outermost first.
|
|
171
|
+
* @param renderPage - Renders the page, once every layout let it through.
|
|
172
|
+
* @param render - Renders one layout component.
|
|
173
|
+
* @param outletId - Outlet id fallback for a layout without `@routerOutlet`.
|
|
174
|
+
* @param logPrefix - Prefix for warning and error messages.
|
|
175
|
+
*/
|
|
176
|
+
export async function wrapInLayouts(layouts, renderPage, render, outletId, logPrefix = '[SSR]') {
|
|
177
|
+
const rendered = [];
|
|
178
|
+
let status;
|
|
179
|
+
for (const load of layouts) {
|
|
180
|
+
const mod = await load();
|
|
181
|
+
const Layout = mod.default ?? mod;
|
|
182
|
+
if (typeof Layout !== 'function') {
|
|
183
|
+
throw new Error(`${logPrefix} Layout module does not export a component`);
|
|
184
|
+
}
|
|
185
|
+
const result = await render(Layout);
|
|
186
|
+
if (result.redirectTo) {
|
|
187
|
+
return redirect(result.redirectTo, result.status);
|
|
188
|
+
}
|
|
189
|
+
// Every render reports a status (200 by default): only a layout that
|
|
190
|
+
// changed it has a say.
|
|
191
|
+
if (status === undefined && result.status !== undefined) {
|
|
192
|
+
if (result.status !== 200)
|
|
193
|
+
status = result.status;
|
|
194
|
+
}
|
|
195
|
+
if (!findOutletMatch(result.html, outletId)) {
|
|
196
|
+
throw new Error(`${logPrefix} Layout has no outlet. Add @routerOutlet to the element its pages render into.`);
|
|
197
|
+
}
|
|
198
|
+
rendered.push(result.html);
|
|
199
|
+
}
|
|
200
|
+
const page = await renderPage();
|
|
201
|
+
if (page.redirectTo) {
|
|
202
|
+
return { ...redirect(page.redirectTo, page.status), page };
|
|
203
|
+
}
|
|
204
|
+
let html = page.html;
|
|
205
|
+
for (const layoutHtml of rendered.reverse()) {
|
|
206
|
+
html = injectIntoOutlet(layoutHtml, html, outletId, logPrefix);
|
|
207
|
+
}
|
|
208
|
+
status ?? (status = page.status);
|
|
209
|
+
return status === undefined ? { html, page } : { html, status, page };
|
|
210
|
+
}
|
|
211
|
+
// A redirect answers with a 3xx even when an outer layout set an error
|
|
212
|
+
// status: a 403 carrying a Location is not followed by browsers.
|
|
213
|
+
function redirect(redirectTo, status) {
|
|
214
|
+
const is3xx = status !== undefined && status >= 300 && status < 400;
|
|
215
|
+
return { html: '', redirectTo, status: is3xx ? status : 302 };
|
|
216
|
+
}
|
|
160
217
|
//# sourceMappingURL=shell-helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-helpers.js","sourceRoot":"","sources":["../../src/shared/shell-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe;IAC5C,2EAA2E;IAC3E,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3C,uEAAuE;IACvE,kEAAkE;IAClE,MAAM,UAAU,GAAG,SAAS;SACzB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;SAClB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;SAClB,KAAK,CAAC,GAAG,CAAC;SACV,MAAM,CAAC,GAA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G,SAAS,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC9C,CAAC;IACH,CAAC;IAED,OAAO,CAAC,IAAI,CACV,GAAG,SAAS,8BAA8B,OAAO,qCAAqC,CACvF,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Shared helpers for SSR shell assembly.\n *\n * Used by both the Vite SSR dev plugin (via ssrLoadModule) and the SSG\n * build pipeline (direct import). Keeping a single source of truth avoids\n * behavioral drift between dev and production rendering.\n */\n\nimport type { HeadState, MetaTag } from './types.js';\nimport { getMetaKey } from './head.js';\n\n// =============================================================================\n// Path utilities\n// =============================================================================\n\n/**\n * Convert a URL path to a file path for the output directory.\n *\n * Segment text passes through VERBATIM, by design — no slugifying, no\n * escaping. Naming an entry and rewriting the links that point at it are one\n * policy: `pithy-ssg` pairs a raw name with raw links (`makeLinksRelative`\n * only adds a `../` prefix; `generateStaticSite` does not rebase at all), so\n * renaming here alone emits pages whose links resolve to nothing. Exception:\n * `makeLinksRelative` skips a final `/\\.\\w+$/` segment as an asset, so `/v1.0`\n * lands here with links pointing at `v1.0` — Bug 10 / BACKLOG #61. Escaping was\n * added (`f1b6ea5b`) and reverted 13 minutes later (`a5d77f40`) for exactly\n * that. Pinned by `build/tests/ssg-helpers.test.ts`; rationale in\n * `docs/ssg/static-export-unification.md`.\n *\n * Examples:\n * - '/' → 'index.html'\n * - '/about' → 'about/index.html'\n * - '/blog/post-1' → 'blog/post-1/index.html'\n *\n * @param urlPath - URL path (e.g., '/about')\n * @returns Relative file path (e.g., 'about/index.html')\n */\nexport function pathToFilePath(urlPath: string): string {\n // Strip query string and hash fragment — these are not valid in file paths\n const cleanPath = urlPath.split(/[?#]/)[0];\n\n // Normalize: remove leading/trailing slashes, collapse double slashes,\n // and reject traversal segments to prevent writing outside outDir\n const normalized = cleanPath\n .replace(/\\/+/g, '/')\n .replace(/^\\//, '')\n .replace(/\\/$/, '')\n .split('/')\n .filter(seg => seg !== '.' && seg !== '..')\n .join('/');\n\n if (!normalized) return 'index.html';\n return `${normalized}/index.html`;\n}\n\n// =============================================================================\n// Head merging\n// =============================================================================\n\n/**\n * Merge shell head with page head. Page values take priority:\n * - title: page wins if non-empty\n * - meta: page replaces a shell tag of the same identity, otherwise appended\n * - link/script arrays: concatenated (page after shell)\n * - htmlAttrs/bodyAttrs: merged (page wins on conflict)\n *\n * Meta is keyed the way `head()` already keys its own merge, so a description\n * replaced across shell and page and one replaced across two `head()` calls\n * agree. Concatenating instead shipped two `<meta name=\"description\">`, which\n * is undefined for crawlers.\n */\nexport function mergeHead(\n shell: Partial<HeadState>,\n page: Partial<HeadState>\n): HeadState {\n const meta = new Map<string, MetaTag>();\n for (const tag of [...(shell.meta ?? []), ...(page.meta ?? [])]) {\n meta.set(getMetaKey(tag), tag);\n }\n\n return {\n title: page.title || shell.title || '',\n meta: [...meta.values()],\n link: [...(shell.link ?? []), ...(page.link ?? [])],\n script: [...(shell.script ?? []), ...(page.script ?? [])],\n base: page.base ?? shell.base,\n htmlAttrs: { ...(shell.htmlAttrs ?? {}), ...(page.htmlAttrs ?? {}) },\n bodyAttrs: { ...(shell.bodyAttrs ?? {}), ...(page.bodyAttrs ?? {}) },\n };\n}\n\n// =============================================================================\n// Outlet injection\n// =============================================================================\n\n/**\n * Find the router outlet element in the shell HTML.\n *\n * Detection order:\n * 1. `data-router-outlet` attribute (auto-generated by @routerOutlet directive)\n * 2. `id=\"{outletId}\"` attribute (explicit fallback via config.outletId)\n *\n * This means users only need `@routerOutlet` on their outlet element —\n * no extra `id` attribute required.\n */\nexport function findOutletMatch(\n shellHtml: string,\n outletId: string\n): RegExpMatchArray | null {\n // 1. Try data-router-outlet (from @routerOutlet directive)\n const directiveRe = /(<[a-z][a-z0-9-]*[^>]*\\bdata-router-outlet\\b[^>]*>)/i;\n const directiveMatch = shellHtml.match(directiveRe);\n if (directiveMatch && directiveMatch.index !== undefined)\n return directiveMatch;\n\n // 2. Fall back to id=\"{outletId}\" (escape for safe regex interpolation)\n const escaped = outletId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRe = new RegExp(\n `(<[a-z][a-z0-9-]*[^>]*\\\\bid=\"${escaped}\"[^>]*>)`,\n 'i'\n );\n return shellHtml.match(idRe);\n}\n\n/**\n * Inject page HTML into the App shell's outlet element.\n *\n * Auto-detects the outlet via `@routerOutlet` (data-router-outlet attribute),\n * falling back to `id=\"{outletId}\"` from config.\n * Uses depth-counting to handle nested elements of the same tag correctly.\n *\n * @param shellHtml - Full shell HTML string\n * @param pageHtml - Rendered page content to inject\n * @param outletId - Outlet element ID (default: 'outlet')\n * @param logPrefix - Prefix for warning messages (e.g. '[SSG]' or '[pithy-ssr]')\n */\nexport function injectIntoOutlet(\n shellHtml: string,\n pageHtml: string,\n outletId: string,\n logPrefix = '[SSR]'\n): string {\n const match = findOutletMatch(shellHtml, outletId);\n\n if (!match || match.index === undefined) {\n console.warn(\n `${logPrefix} Router outlet not found in App shell. ` +\n `Add @routerOutlet to your outlet element, or set outletId in pithy.config.ts. ` +\n `Using page HTML only.`\n );\n return pageHtml;\n }\n\n // Extract the tag name for depth tracking\n const tagMatch = match[1].match(/^<([a-z][a-z0-9-]*)/i);\n if (!tagMatch) return pageHtml;\n const tagName = tagMatch[1].toLowerCase();\n\n const openTagEnd = match.index + match[0].length;\n\n // Find the matching closing tag by counting depth\n const openRe = new RegExp(`<${tagName}[\\\\s>]`, 'gi');\n const closeRe = new RegExp(`</${tagName}>`, 'gi');\n\n let depth = 1;\n let pos = openTagEnd;\n\n while (depth > 0 && pos < shellHtml.length) {\n openRe.lastIndex = pos;\n closeRe.lastIndex = pos;\n\n const nextOpen = openRe.exec(shellHtml);\n const nextClose = closeRe.exec(shellHtml);\n\n if (!nextClose) break;\n\n if (nextOpen && nextOpen.index < nextClose.index) {\n depth++;\n pos = nextOpen.index + nextOpen[0].length;\n } else {\n depth--;\n if (depth === 0) {\n // Replace content between open tag end and this closing tag\n return (\n shellHtml.slice(0, openTagEnd) +\n pageHtml +\n shellHtml.slice(nextClose.index)\n );\n }\n pos = nextClose.index + nextClose[0].length;\n }\n }\n\n console.warn(\n `${logPrefix} Could not find matching </${tagName}> for outlet. Using page HTML only.`\n );\n return pageHtml;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shell-helpers.js","sourceRoot":"","sources":["../../src/shared/shell-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe;IAC5C,2EAA2E;IAC3E,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3C,uEAAuE;IACvE,kEAAkE;IAClE,MAAM,UAAU,GAAG,SAAS;SACzB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;SAClB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;SAClB,KAAK,CAAC,GAAG,CAAC;SACV,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,IAAI,GAAG,KAAK,IAAI,CAAC;SAC1C,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,IAAI,CAAC,UAAU;QAAE,OAAO,YAAY,CAAC;IACrC,OAAO,GAAG,UAAU,aAAa,CAAC;AACpC,CAAC;AAED,gFAAgF;AAChF,eAAe;AACf,gFAAgF;AAEhF;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,SAAS,CACvB,KAAyB,EACzB,IAAwB;IAExB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAmB,CAAC;IACxC,KAAK,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,EAAE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AC,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;IACjE,CAAC;IACD,MAAM,KAAN,MAAM,GAAK,IAAI,CAAC,MAAM,EAAC;IACvB,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AACxE,CAAC;AAED,uEAAuE;AACvE,iEAAiE;AACjE,SAAS,QAAQ,CACf,UAAkB,EAClB,MAA0B;IAE1B,MAAM,KAAK,GAAG,MAAM,KAAK,SAAS,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;IACpE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Shared helpers for SSR shell assembly.\n *\n * Used by both the Vite SSR dev plugin (via ssrLoadModule) and the SSG\n * build pipeline (direct import). Keeping a single source of truth avoids\n * behavioral drift between dev and production rendering.\n */\n\nimport type { HeadState, MetaTag } from './types.js';\nimport { getMetaKey } from './head.js';\n\n// =============================================================================\n// Path utilities\n// =============================================================================\n\n/**\n * Convert a URL path to a file path for the output directory.\n *\n * Segment text passes through VERBATIM, by design — no slugifying, no\n * escaping. Naming an entry and rewriting the links that point at it are one\n * policy: `pithy-ssg` pairs a raw name with raw links (`makeLinksRelative`\n * only adds a `../` prefix; `generateStaticSite` does not rebase at all), so\n * renaming here alone emits pages whose links resolve to nothing. Exception:\n * `makeLinksRelative` skips a final `/\\.\\w+$/` segment as an asset, so `/v1.0`\n * lands here with links pointing at `v1.0` — Bug 10 / BACKLOG #61. Escaping was\n * added (`f1b6ea5b`) and reverted 13 minutes later (`a5d77f40`) for exactly\n * that. Pinned by `build/tests/ssg-helpers.test.ts`; rationale in\n * `docs/ssg/static-export-unification.md`.\n *\n * Examples:\n * - '/' → 'index.html'\n * - '/about' → 'about/index.html'\n * - '/blog/post-1' → 'blog/post-1/index.html'\n *\n * @param urlPath - URL path (e.g., '/about')\n * @returns Relative file path (e.g., 'about/index.html')\n */\nexport function pathToFilePath(urlPath: string): string {\n // Strip query string and hash fragment — these are not valid in file paths\n const cleanPath = urlPath.split(/[?#]/)[0];\n\n // Normalize: remove leading/trailing slashes, collapse double slashes,\n // and reject traversal segments to prevent writing outside outDir\n const normalized = cleanPath\n .replace(/\\/+/g, '/')\n .replace(/^\\//, '')\n .replace(/\\/$/, '')\n .split('/')\n .filter(seg => seg !== '.' && seg !== '..')\n .join('/');\n\n if (!normalized) return 'index.html';\n return `${normalized}/index.html`;\n}\n\n// =============================================================================\n// Head merging\n// =============================================================================\n\n/**\n * Merge shell head with page head. Page values take priority:\n * - title: page wins if non-empty\n * - meta: page replaces a shell tag of the same identity, otherwise appended\n * - link/script arrays: concatenated (page after shell)\n * - htmlAttrs/bodyAttrs: merged (page wins on conflict)\n *\n * Meta is keyed the way `head()` already keys its own merge, so a description\n * replaced across shell and page and one replaced across two `head()` calls\n * agree. Concatenating instead shipped two `<meta name=\"description\">`, which\n * is undefined for crawlers.\n */\nexport function mergeHead(\n shell: Partial<HeadState>,\n page: Partial<HeadState>\n): HeadState {\n const meta = new Map<string, MetaTag>();\n for (const tag of [...(shell.meta ?? []), ...(page.meta ?? [])]) {\n meta.set(getMetaKey(tag), tag);\n }\n\n return {\n title: page.title || shell.title || '',\n meta: [...meta.values()],\n link: [...(shell.link ?? []), ...(page.link ?? [])],\n script: [...(shell.script ?? []), ...(page.script ?? [])],\n base: page.base ?? shell.base,\n htmlAttrs: { ...(shell.htmlAttrs ?? {}), ...(page.htmlAttrs ?? {}) },\n bodyAttrs: { ...(shell.bodyAttrs ?? {}), ...(page.bodyAttrs ?? {}) },\n };\n}\n\n// =============================================================================\n// Outlet injection\n// =============================================================================\n\n/**\n * Find the router outlet element in the shell HTML.\n *\n * Detection order:\n * 1. `data-router-outlet` attribute (auto-generated by @routerOutlet directive)\n * 2. `id=\"{outletId}\"` attribute (explicit fallback via config.outletId)\n *\n * This means users only need `@routerOutlet` on their outlet element —\n * no extra `id` attribute required.\n */\nexport function findOutletMatch(\n shellHtml: string,\n outletId: string\n): RegExpMatchArray | null {\n // 1. Try data-router-outlet (from @routerOutlet directive)\n const directiveRe = /(<[a-z][a-z0-9-]*[^>]*\\bdata-router-outlet\\b[^>]*>)/i;\n const directiveMatch = shellHtml.match(directiveRe);\n if (directiveMatch && directiveMatch.index !== undefined)\n return directiveMatch;\n\n // 2. Fall back to id=\"{outletId}\" (escape for safe regex interpolation)\n const escaped = outletId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRe = new RegExp(\n `(<[a-z][a-z0-9-]*[^>]*\\\\bid=\"${escaped}\"[^>]*>)`,\n 'i'\n );\n return shellHtml.match(idRe);\n}\n\n/**\n * Inject page HTML into the App shell's outlet element.\n *\n * Auto-detects the outlet via `@routerOutlet` (data-router-outlet attribute),\n * falling back to `id=\"{outletId}\"` from config.\n * Uses depth-counting to handle nested elements of the same tag correctly.\n *\n * @param shellHtml - Full shell HTML string\n * @param pageHtml - Rendered page content to inject\n * @param outletId - Outlet element ID (default: 'outlet')\n * @param logPrefix - Prefix for warning messages (e.g. '[SSG]' or '[pithy-ssr]')\n */\nexport function injectIntoOutlet(\n shellHtml: string,\n pageHtml: string,\n outletId: string,\n logPrefix = '[SSR]'\n): string {\n const match = findOutletMatch(shellHtml, outletId);\n\n if (!match || match.index === undefined) {\n console.warn(\n `${logPrefix} Router outlet not found in App shell. ` +\n `Add @routerOutlet to your outlet element, or set outletId in pithy.config.ts. ` +\n `Using page HTML only.`\n );\n return pageHtml;\n }\n\n // Extract the tag name for depth tracking\n const tagMatch = match[1].match(/^<([a-z][a-z0-9-]*)/i);\n if (!tagMatch) return pageHtml;\n const tagName = tagMatch[1].toLowerCase();\n\n const openTagEnd = match.index + match[0].length;\n\n // Find the matching closing tag by counting depth\n const openRe = new RegExp(`<${tagName}[\\\\s>]`, 'gi');\n const closeRe = new RegExp(`</${tagName}>`, 'gi');\n\n let depth = 1;\n let pos = openTagEnd;\n\n while (depth > 0 && pos < shellHtml.length) {\n openRe.lastIndex = pos;\n closeRe.lastIndex = pos;\n\n const nextOpen = openRe.exec(shellHtml);\n const nextClose = closeRe.exec(shellHtml);\n\n if (!nextClose) break;\n\n if (nextOpen && nextOpen.index < nextClose.index) {\n depth++;\n pos = nextOpen.index + nextOpen[0].length;\n } else {\n depth--;\n if (depth === 0) {\n // Replace content between open tag end and this closing tag\n return (\n shellHtml.slice(0, openTagEnd) +\n pageHtml +\n shellHtml.slice(nextClose.index)\n );\n }\n pos = nextClose.index + nextClose[0].length;\n }\n }\n\n console.warn(\n `${logPrefix} Could not find matching </${tagName}> for outlet. Using page HTML only.`\n );\n return pageHtml;\n}\n\n/** One rendered view: a layout or a page. */\nexport interface RenderedView {\n html: string;\n redirectTo?: string | undefined;\n status?: number | undefined;\n}\n\n/** What rendering a route's layouts and page decided. */\nexport interface LayoutsResult<Page extends RenderedView = RenderedView> {\n /** The page inside its layouts; empty on a redirect. */\n html: string;\n /**\n * Set when a layout or the page called `setRedirect()`: the outermost one\n * wins, and nothing inside it renders.\n */\n redirectTo?: string;\n /**\n * The response status. A redirect's is always a 3xx (302 unless it set\n * another). Otherwise the outermost layout's non-200 status, else the\n * page's own.\n */\n status?: number;\n /** The page's render result; absent when a layout redirected. */\n page?: Page;\n}\n\n/**\n * Render a route: its layouts outermost first, then the page in the\n * innermost outlet — the DOM the client router builds for the same route, so\n * its first mount replaces it one for one.\n *\n * Each layout renders before anything inside it: one that redirects (an auth\n * gate) decides for everything it wraps, so neither an inner layout nor the\n * page is rendered or imported. A layout without an outlet is rejected, as\n * the client router renders an error for it rather than dropping the page.\n *\n * @param layouts - The route's layout imports, outermost first.\n * @param renderPage - Renders the page, once every layout let it through.\n * @param render - Renders one layout component.\n * @param outletId - Outlet id fallback for a layout without `@routerOutlet`.\n * @param logPrefix - Prefix for warning and error messages.\n */\nexport async function wrapInLayouts<Page extends RenderedView>(\n layouts: Array<() => Promise<Record<string, unknown>>>,\n renderPage: () => Promise<Page>,\n render: (layout: unknown) => Promise<RenderedView>,\n outletId: string,\n logPrefix = '[SSR]'\n): Promise<LayoutsResult<Page>> {\n const rendered: string[] = [];\n let status: number | undefined;\n for (const load of layouts) {\n const mod = await load();\n const Layout = mod.default ?? mod;\n if (typeof Layout !== 'function') {\n throw new Error(`${logPrefix} Layout module does not export a component`);\n }\n const result = await render(Layout);\n if (result.redirectTo) {\n return redirect(result.redirectTo, result.status);\n }\n // Every render reports a status (200 by default): only a layout that\n // changed it has a say.\n if (status === undefined && result.status !== undefined) {\n if (result.status !== 200) status = result.status;\n }\n if (!findOutletMatch(result.html, outletId)) {\n throw new Error(\n `${logPrefix} Layout has no outlet. Add @routerOutlet to the element its pages render into.`\n );\n }\n rendered.push(result.html);\n }\n\n const page = await renderPage();\n if (page.redirectTo) {\n return { ...redirect(page.redirectTo, page.status), page };\n }\n let html = page.html;\n for (const layoutHtml of rendered.reverse()) {\n html = injectIntoOutlet(layoutHtml, html, outletId, logPrefix);\n }\n status ??= page.status;\n return status === undefined ? { html, page } : { html, status, page };\n}\n\n// A redirect answers with a 3xx even when an outer layout set an error\n// status: a 403 carrying a Location is not followed by browsers.\nfunction redirect(\n redirectTo: string,\n status: number | undefined\n): { html: string; redirectTo: string; status: number } {\n const is3xx = status !== undefined && status >= 300 && status < 400;\n return { html: '', redirectTo, status: is3xx ? status : 302 };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithyjs/ssr",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-beta.13",
|
|
4
4
|
"description": "Server-side rendering and static site generation for PithyJS framework",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -36,9 +36,9 @@
|
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"@pithyjs/shared": "0.1.0-beta.3",
|
|
38
38
|
"@pithyjs/signals": "0.1.0-beta.2",
|
|
39
|
-
"@pithyjs/router": "0.
|
|
40
|
-
"@pithyjs/core": "0.1.0-beta.
|
|
41
|
-
"@pithyjs/design-system": "0.1.0-beta.
|
|
39
|
+
"@pithyjs/router": "0.2.0-beta.13",
|
|
40
|
+
"@pithyjs/core": "0.1.0-beta.14",
|
|
41
|
+
"@pithyjs/design-system": "0.1.0-beta.8"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"happy-dom": "^20.0.3",
|