@pithyjs/ssr 0.1.2-beta.9 → 0.2.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/vite-ssg.d.ts +140 -1
- package/dist/build/vite-ssg.d.ts.map +1 -1
- package/dist/build/vite-ssg.js +342 -25
- 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 +6 -6
package/dist/build/vite-ssg.js
CHANGED
|
@@ -41,8 +41,32 @@ 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
|
+
/**
|
|
47
|
+
* The `public/` settings that produced the output. In hydrate mode the
|
|
48
|
+
* production client build copied it, under its own config, which can differ
|
|
49
|
+
* from the serve-mode config the prerender server resolved.
|
|
50
|
+
*
|
|
51
|
+
* @param hydrate - Whether a client build ran.
|
|
52
|
+
* @param clientBuild - What it recorded.
|
|
53
|
+
* @param serve - The prerender server's `publicDir` and `build.copyPublicDir`.
|
|
54
|
+
*/
|
|
55
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"publicCopySource","stability":"experimental","signature":"(hydrate: boolean, clientBuild: ClientBuildResult, serve: PublicCopy) => PublicCopy"} */
|
|
56
|
+
export function publicCopySource(hydrate, clientBuild, serve) {
|
|
57
|
+
if (!hydrate)
|
|
58
|
+
return serve;
|
|
59
|
+
return {
|
|
60
|
+
publicDir: clientBuild.publicDir || false,
|
|
61
|
+
copyPublicDir: clientBuild.copyPublicDir ?? false,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Whether `public/` supplied a file at `entry` in the output. */
|
|
65
|
+
function isAuthoredPublicFile(source, entry) {
|
|
66
|
+
return (source.copyPublicDir &&
|
|
67
|
+
typeof source.publicDir === 'string' &&
|
|
68
|
+
fs.existsSync(path.join(source.publicDir, entry)));
|
|
69
|
+
}
|
|
46
70
|
// Re-export pathToFilePath for test access (canonical definition in shell-helpers)
|
|
47
71
|
export { pathToFilePath } from '../shared/shell-helpers.js';
|
|
48
72
|
// Canonical in `./not-found.js`, so `generateStaticSite()` and `buildSSG()`
|
|
@@ -89,6 +113,204 @@ export function planRenderJobs(staticPaths, notFoundRoute, findRouteByPattern) {
|
|
|
89
113
|
}
|
|
90
114
|
return renderJobs;
|
|
91
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Plan the SPA shells listed in `pithy.config` `ssg.shells`.
|
|
118
|
+
*
|
|
119
|
+
* Each path must be a literal URL path: no parameter, wildcard, query, hash,
|
|
120
|
+
* percent-escape, dot or empty segment, and no segment ending in `.` or a
|
|
121
|
+
* space (Win32 trims those from file names). One trailing slash is dropped. A shell is only useful with a client bundle, so static
|
|
122
|
+
* mode plans none and warns instead.
|
|
123
|
+
*
|
|
124
|
+
* @param shells - The raw `ssg.shells` value; not trusted to be well-typed.
|
|
125
|
+
* @param hydrate - Whether the build emits a client bundle.
|
|
126
|
+
* @returns The jobs to write plus any errors and warnings.
|
|
127
|
+
*/
|
|
128
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"planShellJobs","stability":"experimental","signature":"(shells: unknown, hydrate: boolean) => ShellPlan"} */
|
|
129
|
+
export function planShellJobs(shells, hydrate) {
|
|
130
|
+
const plan = { jobs: [], errors: [], warnings: [] };
|
|
131
|
+
if (shells === undefined)
|
|
132
|
+
return plan;
|
|
133
|
+
if (!Array.isArray(shells)) {
|
|
134
|
+
plan.errors.push(`ssg.shells must be an array of URL paths; got ${describe(shells)}.`);
|
|
135
|
+
return plan;
|
|
136
|
+
}
|
|
137
|
+
const seen = new Map();
|
|
138
|
+
for (const raw of shells) {
|
|
139
|
+
// Strip ONE trailing slash, so `//` stays invalid rather than becoming `/`.
|
|
140
|
+
const urlPath = typeof raw === 'string' && raw.length > 1 ? raw.replace(/\/$/, '') : raw;
|
|
141
|
+
const segments = typeof urlPath === 'string' ? urlPath.split('/').slice(1) : [];
|
|
142
|
+
const valid = typeof urlPath === 'string' &&
|
|
143
|
+
urlPath.startsWith('/') &&
|
|
144
|
+
!/[?#:*%\\]/.test(urlPath) &&
|
|
145
|
+
(raw === '/' || segments.every(s => s !== '' && !/[. ]$/.test(s)));
|
|
146
|
+
if (!valid) {
|
|
147
|
+
plan.errors.push(`ssg.shells entry ${JSON.stringify(raw)} is not a literal URL path ` +
|
|
148
|
+
`such as "/app".`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
// `/app` and `/App` are one file on a case-insensitive filesystem.
|
|
152
|
+
const key = entryCollisionKey(pathToFilePath(urlPath));
|
|
153
|
+
const twin = seen.get(key);
|
|
154
|
+
if (twin === urlPath)
|
|
155
|
+
continue;
|
|
156
|
+
if (twin !== undefined) {
|
|
157
|
+
plan.errors.push(`ssg.shells entries "${twin}" and "${urlPath}" write the same file.`);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
seen.set(key, urlPath);
|
|
161
|
+
plan.jobs.push({ path: urlPath, entry: pathToFilePath(urlPath) });
|
|
162
|
+
}
|
|
163
|
+
if (!hydrate && plan.jobs.length > 0) {
|
|
164
|
+
plan.warnings.push(`ssg.shells (${plan.jobs.map(j => j.path).join(', ')}) ignored: a shell ` +
|
|
165
|
+
`is empty until JavaScript runs, so it is written only with --hydrate.`);
|
|
166
|
+
plan.jobs = [];
|
|
167
|
+
}
|
|
168
|
+
return plan;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Render one SPA shell: head, every stylesheet, the module script, an empty
|
|
172
|
+
* app root and no hydration state, so `bootstrap()` mounts fresh.
|
|
173
|
+
*
|
|
174
|
+
* Links stay absolute (`linkBase: null`, as for the 404): one shell answers
|
|
175
|
+
* every URL under its path, at any depth. Relative `href`/`src` in the head's
|
|
176
|
+
* links and scripts are resolved against `base`, as the root `index.html` they
|
|
177
|
+
* came from would; with a `<base>` in the head they are left alone, with a
|
|
178
|
+
* warning. The head gets `robots: noindex` unless it sets robots itself: a
|
|
179
|
+
* shell has no content and answers arbitrary URLs.
|
|
180
|
+
*
|
|
181
|
+
* @param htmlShellFn - `htmlShell` from `@pithyjs/ssr/server`.
|
|
182
|
+
* @param options - See {@link ShellDocumentOptions}.
|
|
183
|
+
* @returns The document as it will be written.
|
|
184
|
+
*/
|
|
185
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"renderShellDocument","stability":"experimental","signature":"(htmlShellFn: (options: ShellOptions) => string, options: ShellDocumentOptions) => FinalizePageResult"} */
|
|
186
|
+
export function renderShellDocument(htmlShellFn, options) {
|
|
187
|
+
// A shell answers at any depth, so its URLs cannot be depth-relative like a
|
|
188
|
+
// page's; they carry the deployment prefix instead.
|
|
189
|
+
const base = options.base || '/';
|
|
190
|
+
const underBase = (u) => base + u.replace(/^\//, '');
|
|
191
|
+
const html = htmlShellFn({
|
|
192
|
+
html: '',
|
|
193
|
+
head: withRobotsNoindex(absolutiseHeadUrls(options.head, base, options.headBase || '/')),
|
|
194
|
+
state: undefined,
|
|
195
|
+
scripts: options.scripts.map(underBase),
|
|
196
|
+
styles: options.styles.map(underBase),
|
|
197
|
+
appId: options.appId,
|
|
198
|
+
});
|
|
199
|
+
return finalizeForOutput(html, { linkBase: null }, { relativeLinks: false, hydrate: true, sprite: options.sprite });
|
|
200
|
+
}
|
|
201
|
+
/** A URL a browser would resolve against the request rather than the origin. */
|
|
202
|
+
function isRelativeUrl(url) {
|
|
203
|
+
return !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url);
|
|
204
|
+
}
|
|
205
|
+
function resolveAgainstBase(url, base) {
|
|
206
|
+
// A CDN base (`https://cdn.example/`) keeps its origin; a path base does not.
|
|
207
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(base))
|
|
208
|
+
return new URL(url, base).href;
|
|
209
|
+
const resolved = new URL(url, new URL(base, 'http://shell.invalid/'));
|
|
210
|
+
return resolved.pathname + resolved.search + resolved.hash;
|
|
211
|
+
}
|
|
212
|
+
/** Resolve the head's relative link/script URLs against `base`. */
|
|
213
|
+
function absolutiseHeadUrls(head, base, headBase) {
|
|
214
|
+
const relative = [
|
|
215
|
+
...head.link.map(l => l.href),
|
|
216
|
+
...head.script.flatMap(sc => (sc.src ? [sc.src] : [])),
|
|
217
|
+
].filter(u => u !== '' && isRelativeUrl(u));
|
|
218
|
+
const keepRelative = relative.length > 0 && head.base !== undefined;
|
|
219
|
+
if (keepRelative) {
|
|
220
|
+
console.warn(` WARN SPA shell: the head sets <base>, so relative URLs ` +
|
|
221
|
+
`(${relative.join(', ')}) are left as written and resolve against it.`);
|
|
222
|
+
}
|
|
223
|
+
// Root-absolute URLs already carry `headBase`; move them onto `base`.
|
|
224
|
+
const fix = (u) => {
|
|
225
|
+
if (!u)
|
|
226
|
+
return u;
|
|
227
|
+
if (isRelativeUrl(u))
|
|
228
|
+
return keepRelative ? u : resolveAgainstBase(u, base);
|
|
229
|
+
if (u.startsWith(headBase) && !u.startsWith('//'))
|
|
230
|
+
return base + u.slice(headBase.length);
|
|
231
|
+
return u;
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
...head,
|
|
235
|
+
link: head.link.map(l => ({ ...l, href: fix(l.href) })),
|
|
236
|
+
script: head.script.map(sc => (sc.src ? { ...sc, src: fix(sc.src) } : sc)),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function withRobotsNoindex(head) {
|
|
240
|
+
if (head.meta.some(m => m.name?.toLowerCase() === 'robots'))
|
|
241
|
+
return head;
|
|
242
|
+
return {
|
|
243
|
+
...head,
|
|
244
|
+
meta: [...head.meta, { name: 'robots', content: 'noindex' }],
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Drop the static paths a shell serves: its own path and, unless it is the
|
|
249
|
+
* root shell, every URL path below it, compared as written (one trailing slash
|
|
250
|
+
* ignored). Such routes need no `prerender = false` of their own. A path that
|
|
251
|
+
* only folds onto the shell's file (`/App`) is kept, and the entry check in
|
|
252
|
+
* {@link claimShellEntries} reports it.
|
|
253
|
+
* A path whose config says `prerender = true` contradicts the shell and is an
|
|
254
|
+
* error.
|
|
255
|
+
*
|
|
256
|
+
* @param staticPaths - Every literal path `collectStaticPaths()` found.
|
|
257
|
+
* @param shells - Planned shells, see {@link planShellJobs}.
|
|
258
|
+
* @param forced - Paths whose route config sets `prerender = true`.
|
|
259
|
+
*/
|
|
260
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"excludeShellPaths","stability":"experimental","signature":"(staticPaths: readonly string[], shells: readonly ShellJob[], forced: ReadonlySet<string>) => ShellExclusion"} */
|
|
261
|
+
export function excludeShellPaths(staticPaths, shells, forced) {
|
|
262
|
+
const result = { kept: [], skipped: [], errors: [] };
|
|
263
|
+
const covers = (urlPath, shell) => urlPath === shell.path ||
|
|
264
|
+
(shell.path !== '/' && urlPath.startsWith(`${shell.path}/`));
|
|
265
|
+
for (const routePath of staticPaths) {
|
|
266
|
+
const urlPath = routePath.length > 1 ? routePath.replace(/\/$/, '') : routePath;
|
|
267
|
+
const cover = shells.find(shell => covers(urlPath, shell));
|
|
268
|
+
if (!cover) {
|
|
269
|
+
result.kept.push(routePath);
|
|
270
|
+
}
|
|
271
|
+
else if (forced.has(routePath)) {
|
|
272
|
+
result.errors.push(`Page "${routePath}" sets \`prerender = true\` but SPA shell ` +
|
|
273
|
+
`"${cover.path}" serves it. Drop one of the two.`);
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
result.skipped.push(routePath);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return result;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Decide which shells may be written, given the entries the pages already
|
|
283
|
+
* wrote (keyed by `entryCollisionKey`). A shell is refused when a page owns its
|
|
284
|
+
* file (`/App` against `/app` on a case-insensitive filesystem) or when the app
|
|
285
|
+
* ships that file in `public/`, which the shell would overwrite. Claimed shells
|
|
286
|
+
* are registered in `owners`, which this mutates.
|
|
287
|
+
*
|
|
288
|
+
* @param shells - Planned shells, see {@link planShellJobs}.
|
|
289
|
+
* @param owners - Entries written so far.
|
|
290
|
+
* @param isAuthored - Whether `public/` holds a file at an entry.
|
|
291
|
+
*/
|
|
292
|
+
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"claimShellEntries","stability":"experimental","signature":"(shells: readonly ShellJob[], owners: Map<string, EntryOwner>, isAuthored: (entry: string) => boolean) => { claimed: ShellJob[]; errors: string[] }"} */
|
|
293
|
+
export function claimShellEntries(shells, owners, isAuthored) {
|
|
294
|
+
const claimed = [];
|
|
295
|
+
const errors = [];
|
|
296
|
+
for (const shell of shells) {
|
|
297
|
+
const key = entryCollisionKey(shell.entry);
|
|
298
|
+
const owner = owners.get(key);
|
|
299
|
+
if (owner !== undefined) {
|
|
300
|
+
errors.push(`SPA shell "${shell.path}" and page "${owner.path}" both write to ` +
|
|
301
|
+
`"${owner.entry}".`);
|
|
302
|
+
}
|
|
303
|
+
else if (isAuthored(shell.entry)) {
|
|
304
|
+
errors.push(`SPA shell "${shell.path}" would overwrite ${shell.entry}, which ` +
|
|
305
|
+
`the client build copied from publicDir. Remove the file or drop the shell.`);
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
owners.set(key, { path: shell.path, entry: shell.entry });
|
|
309
|
+
claimed.push(shell);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return { claimed, errors };
|
|
313
|
+
}
|
|
92
314
|
/** @codexApi {"parent":"pithy.ssr.build.vite-ssg","name":"copyPublicAssets","stability":"experimental","signature":"(publicDir: string | false | undefined, outDir: string) => string[]"} */
|
|
93
315
|
/**
|
|
94
316
|
* Copy the app's public directory into the output.
|
|
@@ -163,12 +385,7 @@ export function copyPublicAssets(publicDir, outDir) {
|
|
|
163
385
|
export function withNotFoundRobots(head, job) {
|
|
164
386
|
if (job.linkBase !== null)
|
|
165
387
|
return head;
|
|
166
|
-
|
|
167
|
-
return head;
|
|
168
|
-
return {
|
|
169
|
-
...head,
|
|
170
|
-
meta: [...head.meta, { name: 'robots', content: 'noindex' }],
|
|
171
|
-
};
|
|
388
|
+
return withRobotsNoindex(head);
|
|
172
389
|
}
|
|
173
390
|
/**
|
|
174
391
|
* Finalize a rendered page for the URL(s) it will be SERVED at.
|
|
@@ -374,8 +591,10 @@ export async function buildClientBundle(root, outDir, entryClient) {
|
|
|
374
591
|
// It must sit inside the project — see createClientConfigDir().
|
|
375
592
|
const tempConfigDir = createClientConfigDir(root);
|
|
376
593
|
const tempConfigPath = path.resolve(tempConfigDir, 'client.config.mjs');
|
|
594
|
+
const resolvedPath = path.resolve(tempConfigDir, 'resolved.json');
|
|
377
595
|
const entryClientAbs = path.resolve(root, entryClient).replace(/\\/g, '/');
|
|
378
596
|
const outDirAbs = outDir.replace(/\\/g, '/');
|
|
597
|
+
let resolved = {};
|
|
379
598
|
// Opened immediately after the directory exists, not just around the build:
|
|
380
599
|
// anything that throws in between would otherwise strand the generated
|
|
381
600
|
// config inside the user's project.
|
|
@@ -384,6 +603,8 @@ export async function buildClientBundle(root, outDir, entryClient) {
|
|
|
384
603
|
fs.writeFileSync(tempConfigPath, `
|
|
385
604
|
import { loadConfigFromFile, mergeConfig } from 'vite';
|
|
386
605
|
|
|
606
|
+
import { writeFileSync } from 'node:fs';
|
|
607
|
+
|
|
387
608
|
const root = ${JSON.stringify(root.replace(/\\/g, '/'))};
|
|
388
609
|
const loaded = await loadConfigFromFile(
|
|
389
610
|
{ command: 'build', mode: 'production' },
|
|
@@ -395,6 +616,18 @@ const appConfig = loaded?.config ?? {};
|
|
|
395
616
|
|
|
396
617
|
// Take everything from app config, override build
|
|
397
618
|
export default mergeConfig(appConfig, {
|
|
619
|
+
plugins: [
|
|
620
|
+
{
|
|
621
|
+
name: 'pithy-ssg:record-config',
|
|
622
|
+
configResolved(config) {
|
|
623
|
+
writeFileSync(${JSON.stringify(resolvedPath.replace(/\\/g, '/'))}, JSON.stringify({
|
|
624
|
+
base: config.base,
|
|
625
|
+
publicDir: config.publicDir,
|
|
626
|
+
copyPublicDir: config.build.copyPublicDir,
|
|
627
|
+
}));
|
|
628
|
+
},
|
|
629
|
+
},
|
|
630
|
+
],
|
|
398
631
|
build: {
|
|
399
632
|
outDir: ${JSON.stringify(outDirAbs)},
|
|
400
633
|
emptyOutDir: true,
|
|
@@ -409,6 +642,9 @@ export default mergeConfig(appConfig, {
|
|
|
409
642
|
cwd: root,
|
|
410
643
|
stdio: 'inherit',
|
|
411
644
|
});
|
|
645
|
+
if (fs.existsSync(resolvedPath)) {
|
|
646
|
+
resolved = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8'));
|
|
647
|
+
}
|
|
412
648
|
}
|
|
413
649
|
finally {
|
|
414
650
|
// Clean up the generated config and Vite's .timestamp-*.mjs sidecars
|
|
@@ -433,7 +669,7 @@ export default mergeConfig(appConfig, {
|
|
|
433
669
|
` Tried keys: "${entryClientAbs}", "${relativeKey}", isEntry fallback\n` +
|
|
434
670
|
` Available keys: ${Object.keys(manifest).join(', ')}`);
|
|
435
671
|
}
|
|
436
|
-
const result = {};
|
|
672
|
+
const result = { ...resolved };
|
|
437
673
|
result.script = entry.file;
|
|
438
674
|
const jsSize = (fs.statSync(path.resolve(outDir, entry.file)).size / 1024).toFixed(1);
|
|
439
675
|
console.log(`\n Client JS: ${result.script} (${jsSize} KB)`);
|
|
@@ -748,6 +984,12 @@ async function runBuildSSG(options) {
|
|
|
748
984
|
console.log('Loading app configuration...');
|
|
749
985
|
const configMod = await vite.ssrLoadModule(configPath);
|
|
750
986
|
const config = configMod.default ?? {};
|
|
987
|
+
const shellPlan = planShellJobs(config.ssg?.shells, hydrate);
|
|
988
|
+
for (const warning of shellPlan.warnings)
|
|
989
|
+
console.warn(` WARN ${warning}`);
|
|
990
|
+
for (const message of shellPlan.errors) {
|
|
991
|
+
buildFailures.push({ stage: 'spa-shell', error: new Error(message) });
|
|
992
|
+
}
|
|
751
993
|
console.log('Loading route manifest...');
|
|
752
994
|
const routesMod = await vite.ssrLoadModule('virtual:pithy/routes.gen');
|
|
753
995
|
const routes = routesMod.routes;
|
|
@@ -765,7 +1007,9 @@ async function runBuildSSG(options) {
|
|
|
765
1007
|
const collectStaticPaths = ssrBuildMod.collectStaticPaths;
|
|
766
1008
|
const findRootCatchAllRoute = ssrBuildMod.findRootCatchAllRoute;
|
|
767
1009
|
const routerMod = await vite.ssrLoadModule('@pithyjs/router');
|
|
768
|
-
|
|
1010
|
+
// A layout-only node shares its pattern with a route it wraps
|
|
1011
|
+
const findRouteByPattern = routerMod.findNavigableRoute ?? routerMod.findRouteByPattern;
|
|
1012
|
+
const findLayoutChain = routerMod.findLayoutChain ?? (() => []);
|
|
769
1013
|
// Load JIT compiler (parse5) for runtime html`` templates.
|
|
770
1014
|
// Must run before any renderToString() call.
|
|
771
1015
|
// Imported from compile/parseHtml directly (not the barrel) to avoid
|
|
@@ -799,7 +1043,26 @@ async function runBuildSSG(options) {
|
|
|
799
1043
|
console.log(`Registered icon sprite (${sprite.symbols.size} symbols).`);
|
|
800
1044
|
}
|
|
801
1045
|
// ── Discover static routes ──
|
|
802
|
-
const
|
|
1046
|
+
const forced = new Set();
|
|
1047
|
+
const collected = await collectStaticPaths(routes);
|
|
1048
|
+
if (shellPlan.jobs.length > 0) {
|
|
1049
|
+
for (const routePath of collected) {
|
|
1050
|
+
const loadConfig = findRouteByPattern(routes, routePath)?.imports
|
|
1051
|
+
.config;
|
|
1052
|
+
const routeConfig = await loadConfig?.().catch(() => undefined);
|
|
1053
|
+
if (routeConfig?.prerender === true)
|
|
1054
|
+
forced.add(routePath);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
const shellPaths = excludeShellPaths(collected, shellPlan.jobs, forced);
|
|
1058
|
+
for (const message of shellPaths.errors) {
|
|
1059
|
+
console.log(` FAIL ${message}`);
|
|
1060
|
+
buildFailures.push({ stage: 'spa-shell', error: new Error(message) });
|
|
1061
|
+
}
|
|
1062
|
+
if (shellPaths.skipped.length > 0) {
|
|
1063
|
+
console.log(`Served by an SPA shell: ${shellPaths.skipped.join(', ')}`);
|
|
1064
|
+
}
|
|
1065
|
+
const staticPaths = shellPaths.kept;
|
|
803
1066
|
console.log(`Found ${staticPaths.length} static paths to render.\n`);
|
|
804
1067
|
// `collectStaticPaths()` excludes catch-all routes by design, and that stays
|
|
805
1068
|
// — a catch-all has no literal path of its own to be written at. The
|
|
@@ -836,32 +1099,48 @@ async function runBuildSSG(options) {
|
|
|
836
1099
|
console.log(` SKIP ${routePath} -- no page component`);
|
|
837
1100
|
continue;
|
|
838
1101
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
1102
|
+
// The route's layout.ts files, outermost first, then the page in the
|
|
1103
|
+
// innermost outlet. A layout gate (auth, feature flag) redirects
|
|
1104
|
+
// before the page is imported or rendered, exactly as a page does.
|
|
1105
|
+
const loadPage = routeNode.imports.page;
|
|
1106
|
+
let hasDefault = true;
|
|
1107
|
+
const wrapped = await wrapInLayouts(findLayoutChain(routes, routeNode).flatMap(n => n.imports.layout ? [n.imports.layout] : []), async () => {
|
|
1108
|
+
const PageComponent = (await loadPage()).default;
|
|
1109
|
+
if (!PageComponent) {
|
|
1110
|
+
hasDefault = false;
|
|
1111
|
+
return { html: '' };
|
|
1112
|
+
}
|
|
1113
|
+
return renderToString({ url: routePath, App: PageComponent });
|
|
1114
|
+
}, async (Layout) => {
|
|
1115
|
+
const layoutResult = await renderToString({
|
|
1116
|
+
url: routePath,
|
|
1117
|
+
App: Layout,
|
|
1118
|
+
});
|
|
1119
|
+
recordLayoutDiagnostics(routePath, layoutResult.layoutDiagnostics);
|
|
1120
|
+
return layoutResult;
|
|
1121
|
+
}, outletId, '[SSG]');
|
|
1122
|
+
if (!hasDefault) {
|
|
842
1123
|
console.log(` SKIP ${routePath} -- no default export`);
|
|
843
1124
|
continue;
|
|
844
1125
|
}
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
url: routePath,
|
|
848
|
-
App: PageComponent,
|
|
849
|
-
});
|
|
850
|
-
if (pageResult.redirectTo) {
|
|
851
|
-
console.log(` REDIRECT ${routePath} -> ${pageResult.redirectTo}`);
|
|
1126
|
+
if (wrapped.redirectTo || !wrapped.page) {
|
|
1127
|
+
console.log(` REDIRECT ${routePath} -> ${wrapped.redirectTo}`);
|
|
852
1128
|
continue;
|
|
853
1129
|
}
|
|
1130
|
+
const pageResult = wrapped.page;
|
|
854
1131
|
// Layout-taint findings are returned, not logged, because
|
|
855
1132
|
// `renderToString()` also serves live SSR requests. The static export is
|
|
856
1133
|
// the caller that wants them, and it aggregates rather than repeating
|
|
857
1134
|
// the same declaration once per page.
|
|
858
1135
|
recordLayoutDiagnostics(routePath, pageResult.layoutDiagnostics);
|
|
1136
|
+
const outletHtml = wrapped.html;
|
|
1137
|
+
const status = wrapped.status;
|
|
859
1138
|
// Render App shell per route so layouts reading SSR context
|
|
860
1139
|
// (active nav, canonical URL, route-based head) get correct values
|
|
861
1140
|
const shellResult = await renderToString({ url: routePath, App });
|
|
862
1141
|
const shellHtml = shellResult.html;
|
|
863
1142
|
// Inject page HTML into the App shell's outlet
|
|
864
|
-
const finalHtml = injectIntoOutlet(shellHtml,
|
|
1143
|
+
const finalHtml = injectIntoOutlet(shellHtml, outletHtml, outletId, '[SSG]');
|
|
865
1144
|
// A 404 whose page contributed NOTHING is worse than no 404 at all.
|
|
866
1145
|
//
|
|
867
1146
|
// `buildSSG` renders the catch-all's page standalone and injects the
|
|
@@ -882,7 +1161,7 @@ async function runBuildSSG(options) {
|
|
|
882
1161
|
`A page that portals its content out of the outlet cannot be prerendered.`);
|
|
883
1162
|
continue;
|
|
884
1163
|
}
|
|
885
|
-
console.log(` OK(${
|
|
1164
|
+
console.log(` OK(${status}) ${routePath}`);
|
|
886
1165
|
pageResults.push({
|
|
887
1166
|
job,
|
|
888
1167
|
html: finalHtml,
|
|
@@ -989,9 +1268,11 @@ async function runBuildSSG(options) {
|
|
|
989
1268
|
}
|
|
990
1269
|
// Asked of `publicDir` itself, not of the copied output: in hydrate mode
|
|
991
1270
|
// Vite's own client build does the copying, so nothing here would see it.
|
|
992
|
-
const
|
|
993
|
-
|
|
994
|
-
|
|
1271
|
+
const publicCopy = publicCopySource(hydrate, clientBuild, {
|
|
1272
|
+
publicDir: vite.config.publicDir,
|
|
1273
|
+
copyPublicDir: vite.config.build.copyPublicDir,
|
|
1274
|
+
});
|
|
1275
|
+
const hasAuthoredNotFound = isAuthoredPublicFile(publicCopy, NOT_FOUND_OUTPUT.entry);
|
|
995
1276
|
let notFoundEntry = null;
|
|
996
1277
|
console.log('\nWriting portable static files...');
|
|
997
1278
|
const entryOwners = new Map();
|
|
@@ -1062,6 +1343,38 @@ async function runBuildSSG(options) {
|
|
|
1062
1343
|
rendered.push(routePath);
|
|
1063
1344
|
}
|
|
1064
1345
|
}
|
|
1346
|
+
const shells = [];
|
|
1347
|
+
const shellClaim = claimShellEntries(shellPlan.jobs, entryOwners, entry => isAuthoredPublicFile(publicCopy, entry));
|
|
1348
|
+
const shellBase = clientBuild.base ?? '/';
|
|
1349
|
+
// A relative base cannot resolve at every depth a shell answers.
|
|
1350
|
+
if (shellClaim.claimed.length > 0 &&
|
|
1351
|
+
!/^(?:\/|[a-z][a-z\d+.-]*:)/i.test(shellBase)) {
|
|
1352
|
+
shellClaim.errors.push(`SPA shells need an absolute Vite \`base\`; the client build uses ` +
|
|
1353
|
+
`${JSON.stringify(shellBase)}.`);
|
|
1354
|
+
shellClaim.claimed = [];
|
|
1355
|
+
}
|
|
1356
|
+
for (const message of shellClaim.errors) {
|
|
1357
|
+
console.log(` FAIL ${message}`);
|
|
1358
|
+
buildFailures.push({ stage: 'spa-shell', error: new Error(message) });
|
|
1359
|
+
}
|
|
1360
|
+
for (const shell of shellClaim.claimed) {
|
|
1361
|
+
const { html: shellHtml } = renderShellDocument(htmlShellFn, {
|
|
1362
|
+
head: resolvePageHead(shellHead, {}, {}),
|
|
1363
|
+
scripts,
|
|
1364
|
+
styles,
|
|
1365
|
+
// The PRODUCTION base: the serve-mode one drops a CDN origin and
|
|
1366
|
+
// ignores a base that depends on the command or mode.
|
|
1367
|
+
base: shellBase,
|
|
1368
|
+
headBase: vite.config.base,
|
|
1369
|
+
appId: config.appId,
|
|
1370
|
+
sprite,
|
|
1371
|
+
});
|
|
1372
|
+
const absFile = path.resolve(outDir, shell.entry);
|
|
1373
|
+
fs.mkdirSync(path.dirname(absFile), { recursive: true });
|
|
1374
|
+
fs.writeFileSync(absFile, shellHtml, 'utf-8');
|
|
1375
|
+
console.log(` ${shell.path} -> ${shell.entry} (SPA shell)`);
|
|
1376
|
+
shells.push(shell.entry);
|
|
1377
|
+
}
|
|
1065
1378
|
const totalTime = performance.now() - startTime;
|
|
1066
1379
|
const totalTimeSec = (totalTime / 1000).toFixed(2);
|
|
1067
1380
|
console.log(`\n--- Results ---`);
|
|
@@ -1081,6 +1394,9 @@ async function runBuildSSG(options) {
|
|
|
1081
1394
|
if (notFoundEntry) {
|
|
1082
1395
|
console.log(` Not found: ${notFoundEntry}`);
|
|
1083
1396
|
}
|
|
1397
|
+
if (shells.length > 0) {
|
|
1398
|
+
console.log(` Shells: ${shells.join(', ')}`);
|
|
1399
|
+
}
|
|
1084
1400
|
reportLayoutDiagnostics();
|
|
1085
1401
|
console.log(` Failed: ${failed.length}`);
|
|
1086
1402
|
console.log(` Time: ${totalTimeSec}s`);
|
|
@@ -1113,6 +1429,7 @@ async function runBuildSSG(options) {
|
|
|
1113
1429
|
return {
|
|
1114
1430
|
rendered,
|
|
1115
1431
|
notFound: notFoundEntry,
|
|
1432
|
+
shells,
|
|
1116
1433
|
failed,
|
|
1117
1434
|
buildFailures,
|
|
1118
1435
|
totalTime,
|