@k8ordo/framework 2.3.1 → 4.0.0
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/README.md +28 -13
- package/dist/cli.mjs +3 -3
- package/dist/generated.d.mts +13 -13
- package/dist/headers-BxB_jJVk.mjs +73 -0
- package/dist/index.d.mts +3 -2
- package/dist/index.mjs +1 -1
- package/dist/paths-type-DXpmjaOr.d.mts +43 -0
- package/dist/runtime/app-router.mjs +21 -8
- package/dist/runtime/browser-payloads.mjs +1 -1
- package/dist/runtime/client-files.d.mts +6 -5
- package/dist/runtime/client-files.mjs +17 -9
- package/dist/runtime/client-ready.d.mts +7 -1
- package/dist/runtime/client-ready.mjs +2 -1
- package/dist/runtime/cookies.d.mts +2 -0
- package/dist/runtime/cookies.mjs +2 -1
- package/dist/runtime/ended.d.mts +7 -0
- package/dist/runtime/ended.mjs +14 -0
- package/dist/runtime/entry.browser.mjs +1 -1
- package/dist/runtime/entry.rsc.d.mts +38 -2
- package/dist/runtime/entry.rsc.mjs +97 -31
- package/dist/runtime/entry.ssr.d.mts +7 -1
- package/dist/runtime/entry.ssr.mjs +12 -6
- package/dist/runtime/guard.d.mts +15 -10
- package/dist/runtime/guard.mjs +8 -2
- package/dist/runtime/mount.mjs +1 -1
- package/dist/runtime/page-boundary.mjs +2 -2
- package/dist/runtime/params.d.mts +5 -4
- package/dist/runtime/params.mjs +2 -2
- package/dist/runtime/payload.d.mts +19 -4
- package/dist/runtime/payload.mjs +20 -5
- package/dist/runtime/prefetch.d.mts +29 -8
- package/dist/runtime/prefetch.mjs +95 -24
- package/dist/runtime/redirect.d.mts +13 -7
- package/dist/runtime/redirect.mjs +25 -9
- package/dist/runtime/request-scope.d.mts +37 -2
- package/dist/runtime/request-scope.mjs +60 -3
- package/dist/runtime/request.d.mts +6 -1
- package/dist/runtime/request.mjs +7 -2
- package/dist/runtime/route.d.mts +4 -2
- package/dist/runtime/route.mjs +13 -5
- package/dist/runtime/server.d.mts +5 -5
- package/dist/runtime/server.mjs +2 -2
- package/dist/runtime/shell.d.mts +2 -1
- package/dist/serve.d.mts +4 -0
- package/dist/serve.mjs +29 -14
- package/dist/static-Be3xIqd8.d.mts +62 -0
- package/dist/{static-file-BAjwBMMl.mjs → static-file-BS-WEiwu.mjs} +311 -134
- package/dist/{static-host-B-1fAfAw.mjs → static-host-tIDLqV8c.mjs} +1 -1
- package/dist/vercel.d.mts +18 -1
- package/dist/vercel.mjs +131 -19
- package/dist/vite.d.mts +6 -3
- package/dist/vite.mjs +366 -156
- package/docs/GUIDE.md +173 -46
- package/docs/llms.txt +129 -65
- package/docs/references/actions.md +14 -5
- package/docs/references/boundaries.md +23 -2
- package/docs/references/csp.md +91 -2
- package/docs/references/deploy.md +154 -25
- package/docs/references/errors.md +57 -12
- package/docs/references/guards.md +100 -29
- package/docs/references/params.md +234 -126
- package/docs/references/routing.md +358 -75
- package/package.json +18 -13
- package/dist/shared-dir-CNXFRZgP.mjs +0 -9
- package/dist/static-DnbgGIoy.d.mts +0 -61
package/dist/vite.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import {
|
|
3
|
-
import { _ as isPayloadPath, a as cloudflareCounts, c as rewriteFor, d as shellRules, f as ENCODINGS, i as builtRules, l as rewritesAfterFiles, m as isCompressible, n as resolveStatic, o as cloudflareMatches, p as SUFFIX, r as PLACEHOLDER, s as formatRedirects, t as readRules, u as rulesOf, v as pagePathFor, y as payloadPathFor } from "./static-host-
|
|
1
|
+
import { A as emitRegisterModule, C as SHELL_HEADER, D as decodePathname, E as FALLBACK_SEGMENT, F as fallbackShapes, I as parseRouteTree, L as restDirOf, M as unreachableRoutes, N as ROUTE_METHODS, O as LOCALES_MODULE, P as FRAMEWORK, R as slotOf, S as SERVER_STYLESHEETS_HEADER, T as readServerStylesheets, _ as suppliedFrom, a as answersOf, b as NONCE_HEADER, c as dirFor, f as patternsNeedingPaths, g as shadowedShells, h as routeFileRefusals, i as answeringPatterns, j as emitRoutesModule, k as ROUTES_DIR, l as fileAt, m as planRefusals, o as catchAllPath, p as planPaths, r as SITEMAP_PATHNAME, s as catchAllRefusals, u as isConcrete, v as CLIENT_DEPS_HEADER, w as readClientDeps, x as NOT_FOUND_HEADER, y as CLIENT_FILES_PATH } from "./static-file-BS-WEiwu.mjs";
|
|
2
|
+
import { a as sharedDir, i as headersRefusal, n as formatHeaders, r as headersPlugin } from "./headers-BxB_jJVk.mjs";
|
|
3
|
+
import { _ as isPayloadPath, a as cloudflareCounts, c as rewriteFor, d as shellRules, f as ENCODINGS, i as builtRules, l as rewritesAfterFiles, m as isCompressible, n as resolveStatic, o as cloudflareMatches, p as SUFFIX, r as PLACEHOLDER, s as formatRedirects, t as readRules, u as rulesOf, v as pagePathFor, y as payloadPathFor } from "./static-host-tIDLqV8c.mjs";
|
|
4
4
|
import { findPackageJSON } from "node:module";
|
|
5
5
|
import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
7
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
8
8
|
import path from "node:path";
|
|
9
|
-
import { build, parseSync } from "vite";
|
|
9
|
+
import { build, isCSSRequest, parseSync } from "vite";
|
|
10
|
+
import { transformRscCssExport } from "@vitejs/plugin-rsc/plugin";
|
|
11
|
+
import { getCompatibleVersions } from "baseline-browser-mapping";
|
|
10
12
|
import { existsSync } from "node:fs";
|
|
11
13
|
import react from "@vitejs/plugin-react";
|
|
12
14
|
import rsc, { getPluginApi } from "@vitejs/plugin-rsc";
|
|
@@ -36,8 +38,9 @@ const scanRoutes = async (dir) => {
|
|
|
36
38
|
};
|
|
37
39
|
try {
|
|
38
40
|
return (await walk("")).toSorted();
|
|
39
|
-
} catch {
|
|
40
|
-
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code === "ENOENT" && error.path === dir) throw new Error(`the route files live in ${ROUTES_DIR}/, and ${dir} does not exist`, { cause: error });
|
|
43
|
+
throw error;
|
|
41
44
|
}
|
|
42
45
|
};
|
|
43
46
|
/**
|
|
@@ -63,17 +66,8 @@ const READS_EXPORTS = /* @__PURE__ */ new Set([
|
|
|
63
66
|
"layout",
|
|
64
67
|
"route"
|
|
65
68
|
]);
|
|
66
|
-
/**
|
|
67
|
-
|
|
68
|
-
* read exports nothing.
|
|
69
|
-
*/
|
|
70
|
-
const readExports = async (routesDir, files) => new Map(await Promise.all(files.filter((file) => READS_EXPORTS.has(slotOf(file) ?? "")).map(async (file) => {
|
|
71
|
-
try {
|
|
72
|
-
return [file, exportsOf(await readFile(path.join(routesDir, file), "utf8"), file)];
|
|
73
|
-
} catch {
|
|
74
|
-
return [file, /* @__PURE__ */ new Set()];
|
|
75
|
-
}
|
|
76
|
-
})));
|
|
69
|
+
/** What each page, layout and route.ts exports, by file. */
|
|
70
|
+
const readExports = async (routesDir, files) => new Map(await Promise.all(files.filter((file) => READS_EXPORTS.has(slotOf(file) ?? "")).map(async (file) => [file, exportsOf(await readFile(path.join(routesDir, file), "utf8"), file)])));
|
|
77
71
|
/**
|
|
78
72
|
* The pages that export `search` — a url schema of `@k8ordo/state` saying
|
|
79
73
|
* what of the search they read. Only a page: a layout renders under pages
|
|
@@ -95,12 +89,20 @@ const silentRoutes = (exported) => [...exported].filter(([file, names]) => slotO
|
|
|
95
89
|
}));
|
|
96
90
|
/** Whether the application's manifest lists `name`. */
|
|
97
91
|
const dependsOn = async (root, name) => {
|
|
92
|
+
let text;
|
|
98
93
|
try {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
94
|
+
text = await readFile(path.join(root, "package.json"), "utf8");
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error.code === "ENOENT") return false;
|
|
97
|
+
throw error;
|
|
103
98
|
}
|
|
99
|
+
let manifest;
|
|
100
|
+
try {
|
|
101
|
+
manifest = JSON.parse(text);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw new Error(`${path.join(root, "package.json")} is not JSON, so which packages the application depends on cannot be read`, { cause: error });
|
|
104
|
+
}
|
|
105
|
+
return name in (manifest.dependencies ?? {}) || name in (manifest.devDependencies ?? {});
|
|
104
106
|
};
|
|
105
107
|
/**
|
|
106
108
|
* Where the application declares its locale set: `null` when it does not
|
|
@@ -160,7 +162,6 @@ const generate = async (options) => {
|
|
|
160
162
|
});
|
|
161
163
|
const registerSource = emitRegisterModule({
|
|
162
164
|
routesModule: "./routes.gen",
|
|
163
|
-
stateModule: withState ? "@k8ordo/state" : null,
|
|
164
165
|
localesModule: localeSet?.exportsLocales === true ? importPath(options.outDir, localeSet.module.replace(/\.ts$/u, "")) : null,
|
|
165
166
|
mode: options.mode
|
|
166
167
|
});
|
|
@@ -187,6 +188,85 @@ const writeIfChanged = async (file, content) => {
|
|
|
187
188
|
} catch {}
|
|
188
189
|
await writeFile(file, content, "utf8");
|
|
189
190
|
};
|
|
191
|
+
// ../framework-engine/dist/plugin/mdx-css.mjs
|
|
192
|
+
const MDX = /\.mdx?$/u;
|
|
193
|
+
/**
|
|
194
|
+
* The RSC plugin gives a Server Component the stylesheets its module imports
|
|
195
|
+
* by wrapping the module's exported components, and it wraps only modules
|
|
196
|
+
* whose file is `.js`, `.jsx`, `.ts` or `.tsx`: an `.mdx` compiled by the
|
|
197
|
+
* application's own plugin is JavaScript by then and passed over for its
|
|
198
|
+
* name, so the CSS an MDX file imports never reached the page — unless every
|
|
199
|
+
* import of it carried `?vite-rsc-css-export=default`, the plugin's query for
|
|
200
|
+
* naming the exports to wrap, and one forgotten was a page without its styles
|
|
201
|
+
* and no word of it.
|
|
202
|
+
*
|
|
203
|
+
* This applies the plugin's own transform to such a module, under its rule
|
|
204
|
+
* for a default export: a component, by its capitalised name (`MDXContent`,
|
|
205
|
+
* which every MDX compiler emits). It has to run before the RSC plugin's
|
|
206
|
+
* transforms — the wrapper it writes calls `import.meta.viteRsc.loadCss()`,
|
|
207
|
+
* which one of those replaces — and after the application's MDX plugin, which
|
|
208
|
+
* is `enforce: 'pre'` where the framework documents it.
|
|
209
|
+
*/
|
|
210
|
+
const mdxCss = () => ({
|
|
211
|
+
name: "k8ordo:mdx-css",
|
|
212
|
+
async transform(code, id) {
|
|
213
|
+
if (this.environment.name !== "rsc") return null;
|
|
214
|
+
const [filename = "", query = ""] = id.split("?");
|
|
215
|
+
if (!MDX.test(filename) || query.includes("vite-rsc-css-export")) return null;
|
|
216
|
+
const { program: ast, errors } = parseSync(filename, code, {
|
|
217
|
+
sourceType: "module",
|
|
218
|
+
lang: "js"
|
|
219
|
+
});
|
|
220
|
+
if (errors.length > 0) return null;
|
|
221
|
+
if (!ast.body.some((node) => node.type === "ImportDeclaration" && typeof node.source.value === "string" && isCSSRequest(node.source.value))) return null;
|
|
222
|
+
const result = await transformRscCssExport({
|
|
223
|
+
ast,
|
|
224
|
+
code,
|
|
225
|
+
filter: (_name, meta) => [meta.isFunction === true ? meta.declName : void 0, meta.defaultExportIdentifierName].some((name) => name !== void 0 && /^[A-Z]/u.test(name))
|
|
226
|
+
});
|
|
227
|
+
if (result === void 0) return null;
|
|
228
|
+
return {
|
|
229
|
+
code: result.output.toString(),
|
|
230
|
+
map: result.output.generateMap({ hires: "boundary" })
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
// ../framework-engine/dist/plugin/targets.mjs
|
|
235
|
+
const NAMES = {
|
|
236
|
+
chrome: ["chrome", "chrome"],
|
|
237
|
+
edge: ["edge", "edge"],
|
|
238
|
+
firefox: ["firefox", "firefox"],
|
|
239
|
+
safari: ["safari", "safari"],
|
|
240
|
+
safari_ios: ["ios", "ios_saf"]
|
|
241
|
+
};
|
|
242
|
+
/** `versions`, as baseline-browser-mapping lists them, in Vite's two forms. */
|
|
243
|
+
const targetsOf = (versions) => {
|
|
244
|
+
const build = [];
|
|
245
|
+
const lightningcss = {};
|
|
246
|
+
for (const { browser, version } of versions) {
|
|
247
|
+
const names = NAMES[browser];
|
|
248
|
+
if (names === void 0) continue;
|
|
249
|
+
const [major = 0, minor = 0, patch = 0] = version.split(".").map(Number);
|
|
250
|
+
build.push(`${names[0]}${version}`);
|
|
251
|
+
lightningcss[names[1]] = major << 16 | minor << 8 | patch;
|
|
252
|
+
}
|
|
253
|
+
return {
|
|
254
|
+
build,
|
|
255
|
+
lightningcss
|
|
256
|
+
};
|
|
257
|
+
};
|
|
258
|
+
/**
|
|
259
|
+
* The browsers that ship every feature Baseline has newly available: the
|
|
260
|
+
* ones the family is written for.
|
|
261
|
+
*/
|
|
262
|
+
const newlyAvailableTargets = () => {
|
|
263
|
+
const date = /* @__PURE__ */ new Date();
|
|
264
|
+
date.setMonth(date.getMonth() + 30);
|
|
265
|
+
return targetsOf(getCompatibleVersions({
|
|
266
|
+
widelyAvailableOnDate: date.getTime(),
|
|
267
|
+
suppressWarnings: true
|
|
268
|
+
}));
|
|
269
|
+
};
|
|
190
270
|
// ../framework-engine/dist/plugin/core.mjs
|
|
191
271
|
const VIRTUAL_ROUTES = "virtual:k8ordo/routes";
|
|
192
272
|
const VIRTUAL_LOCALES = "virtual:k8ordo/locales";
|
|
@@ -270,6 +350,7 @@ const engine = (options, host) => {
|
|
|
270
350
|
let devServer;
|
|
271
351
|
let generating = Promise.resolve();
|
|
272
352
|
const frame = /* @__PURE__ */ new Set();
|
|
353
|
+
const targets = newlyAvailableTargets();
|
|
273
354
|
const runtime = (name) => path.join(host.runtimeDir, `${name}.mjs`);
|
|
274
355
|
const routesModule = () => path.join(outDir, "routes.gen.ts");
|
|
275
356
|
const generateOptions = () => ({
|
|
@@ -286,11 +367,14 @@ const engine = (options, host) => {
|
|
|
286
367
|
const plugin = {
|
|
287
368
|
name: "k8ordo:engine",
|
|
288
369
|
enforce: "pre",
|
|
289
|
-
config(
|
|
370
|
+
config(config, env) {
|
|
290
371
|
return {
|
|
372
|
+
...config.build?.target === void 0 && config.build?.cssTarget === void 0 ? { build: { cssTarget: targets.build } } : {},
|
|
373
|
+
...config.css?.lightningcss?.targets === void 0 ? { css: { lightningcss: { targets: targets.lightningcss } } } : {},
|
|
291
374
|
define: {
|
|
292
375
|
"process.env.NODE_ENV": JSON.stringify(isProduction(env.mode) ? "production" : "development"),
|
|
293
|
-
"import.meta.env.K8ORDO_MODE": JSON.stringify(host.mode)
|
|
376
|
+
"import.meta.env.K8ORDO_MODE": JSON.stringify(host.mode),
|
|
377
|
+
"import.meta.env.K8ORDO_HEADERS": JSON.stringify(options.headers ?? {})
|
|
294
378
|
},
|
|
295
379
|
resolve: { dedupe: ["react", "react-dom"] },
|
|
296
380
|
environments: {
|
|
@@ -333,17 +417,21 @@ const engine = (options, host) => {
|
|
|
333
417
|
}
|
|
334
418
|
};
|
|
335
419
|
},
|
|
336
|
-
configEnvironment(
|
|
420
|
+
configEnvironment(name, config) {
|
|
337
421
|
const include = config.optimizeDeps?.include;
|
|
338
422
|
if (include !== void 0) config.optimizeDeps = {
|
|
339
423
|
...config.optimizeDeps,
|
|
340
424
|
include: include.map((entry) => entry.startsWith("@vitejs/plugin-rsc") ? `${FRAMEWORK} > ${entry}` : entry)
|
|
341
425
|
};
|
|
426
|
+
if ((config.consumer ?? (name === "client" ? "client" : "server")) === "client" && config.build?.target === void 0) config.build = {
|
|
427
|
+
...config.build,
|
|
428
|
+
target: targets.build
|
|
429
|
+
};
|
|
342
430
|
},
|
|
343
431
|
configResolved(config) {
|
|
344
432
|
if (!config.base.startsWith("/") || config.base.startsWith("//")) throw new Error(`k8ordo serves its pages under Vite's base, so base has to be a path from the root, like '/docs/' — got '${config.base}'`);
|
|
345
433
|
({root, logger} = config);
|
|
346
|
-
routesDir = path.resolve(root,
|
|
434
|
+
routesDir = path.resolve(root, ROUTES_DIR);
|
|
347
435
|
localesModule = path.resolve(root, LOCALES_MODULE);
|
|
348
436
|
outDir = path.resolve(root, OUT_DIR);
|
|
349
437
|
},
|
|
@@ -399,6 +487,7 @@ const engine = (options, host) => {
|
|
|
399
487
|
};
|
|
400
488
|
return [
|
|
401
489
|
react({ compiler: options.reactCompiler === true }),
|
|
490
|
+
mdxCss(),
|
|
402
491
|
rsc(),
|
|
403
492
|
plugin
|
|
404
493
|
];
|
|
@@ -434,6 +523,21 @@ const serverActionModules = (config) => {
|
|
|
434
523
|
* `node_modules`; the question here is about the id in hand.
|
|
435
524
|
*/
|
|
436
525
|
const isServerActionModule = (config, id) => getPluginApi(config)?.manager.serverReferences.claimMap.has(id) ?? false;
|
|
526
|
+
// src/options.ts
|
|
527
|
+
const STATIC_ONLY = ["site", "csp"];
|
|
528
|
+
const TAKEN = {
|
|
529
|
+
static: [
|
|
530
|
+
"mode",
|
|
531
|
+
"reactCompiler",
|
|
532
|
+
"headers",
|
|
533
|
+
...STATIC_ONLY
|
|
534
|
+
],
|
|
535
|
+
server: [
|
|
536
|
+
"mode",
|
|
537
|
+
"reactCompiler",
|
|
538
|
+
"headers"
|
|
539
|
+
]
|
|
540
|
+
};
|
|
437
541
|
// src/precompress.ts
|
|
438
542
|
const compress = {
|
|
439
543
|
br: (data) => promisify(brotliCompress)(data, { params: {
|
|
@@ -555,12 +659,10 @@ const serverMode = () => ({
|
|
|
555
659
|
// src/documents.ts
|
|
556
660
|
const escapeMarkup = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
557
661
|
/**
|
|
558
|
-
* The sitemap protocol's one required element per URL: `<loc
|
|
559
|
-
*
|
|
560
|
-
* carries it, escaped for XML.
|
|
662
|
+
* The sitemap protocol's one required element per URL: `<loc>`, the origin
|
|
663
|
+
* followed by the pathname as the URL carries it, escaped for XML.
|
|
561
664
|
*/
|
|
562
|
-
const sitemap = (
|
|
563
|
-
const origin = site.endsWith("/") ? site.slice(0, -1) : site;
|
|
665
|
+
const sitemap = (origin, pathnames) => {
|
|
564
666
|
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${pathnames.toSorted().map((pathname) => ` <url><loc>${escapeMarkup(`${origin}${pathname}`)}</loc></url>`).join("\n")}\n</urlset>\n`;
|
|
565
667
|
};
|
|
566
668
|
/**
|
|
@@ -572,15 +674,17 @@ const redirectPage = (to) => {
|
|
|
572
674
|
const escaped = escapeMarkup(to);
|
|
573
675
|
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${escaped}"><link rel="canonical" href="${escaped}"><title>Redirecting</title></head><body><a href="${escaped}">${escaped}</a></body></html>\n`;
|
|
574
676
|
};
|
|
575
|
-
|
|
576
|
-
|
|
677
|
+
/**
|
|
678
|
+
* What `CLIENT_FILES_PATH` lists: each page's files, by its payload's path —
|
|
679
|
+
* what its client components need and what its Server Components link.
|
|
680
|
+
*/
|
|
577
681
|
const clientFiles = (pages, documents) => {
|
|
578
682
|
let everywhere;
|
|
579
|
-
for (const
|
|
580
|
-
const files =
|
|
683
|
+
for (const linked of documents) {
|
|
684
|
+
const files = new Set(linked);
|
|
581
685
|
everywhere = everywhere?.intersection(files) ?? files;
|
|
582
686
|
}
|
|
583
|
-
const own = [...pages].map(([page,
|
|
687
|
+
const own = [...pages].map(([page, linked]) => [page, [...new Set(linked)].filter((file) => everywhere?.has(file) !== true)]).filter(([, files]) => files.length > 0).toSorted(([a], [b]) => a < b ? -1 : 1);
|
|
584
688
|
const files = [...new Set(own.flatMap(([, listed]) => listed))].toSorted();
|
|
585
689
|
const indexOf = new Map(files.map((file, index) => [file, index]));
|
|
586
690
|
return {
|
|
@@ -647,7 +751,18 @@ const policyProblems = (policy) => {
|
|
|
647
751
|
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script[\s/>]/giu;
|
|
648
752
|
const ORDER_STYLE = new RegExp(`<style\\b[^>]*\\sdata-href="${STYLESHEET_ORDER_HREF}"[^>]*>([^<]*)</style>`, "u");
|
|
649
753
|
const CHARSET = /^<meta(?:\s[^>]*)?\scharset=[^>]*>/iu;
|
|
650
|
-
const
|
|
754
|
+
const asParsed = (source) => source.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
|
755
|
+
const hashOf = (source) => `'sha256-${createHash("sha256").update(asParsed(source)).digest("base64")}'`;
|
|
756
|
+
/**
|
|
757
|
+
* An inline script of the application's as a CSP source, `'sha256-…'`: the
|
|
758
|
+
* hash of `text`, the string its `<script>` is given, for static mode's
|
|
759
|
+
* `csp` option, which adds the hashes of the framework's own scripts alone.
|
|
760
|
+
* A line break counts as the browser parses the page, a CR LF as one LF.
|
|
761
|
+
*/
|
|
762
|
+
const scriptHash = async (text) => {
|
|
763
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(asParsed(text)));
|
|
764
|
+
return `'sha256-${btoa(String.fromCodePoint(...new Uint8Array(digest)))}'`;
|
|
765
|
+
};
|
|
651
766
|
/**
|
|
652
767
|
* The policy as the page's `<meta>` says it: the application's directives,
|
|
653
768
|
* with the hashes added wherever a script element is decided —
|
|
@@ -730,9 +845,10 @@ const writtenOutsideScripts = (html) => {
|
|
|
730
845
|
}
|
|
731
846
|
};
|
|
732
847
|
// src/static.ts
|
|
733
|
-
const
|
|
848
|
+
const NO_PLAN = {
|
|
734
849
|
paths: /* @__PURE__ */ new Set(),
|
|
735
|
-
shells: []
|
|
850
|
+
shells: [],
|
|
851
|
+
failed: true
|
|
736
852
|
};
|
|
737
853
|
/** Every file below a directory, relative to it, POSIX separators. */
|
|
738
854
|
const filesBelow = async (dir) => (await readdir(dir, {
|
|
@@ -740,7 +856,6 @@ const filesBelow = async (dir) => (await readdir(dir, {
|
|
|
740
856
|
withFileTypes: true
|
|
741
857
|
})).filter((entry) => entry.isFile()).map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)).split(path.sep).join("/")).toSorted();
|
|
742
858
|
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
743
|
-
const ORIGIN = "http://k8ordo.localhost";
|
|
744
859
|
const WANTS_SERVER = "this application wants mode: 'server'";
|
|
745
860
|
/** The entry whose every export answers a request. */
|
|
746
861
|
const SERVER_ENTRY = "@k8ordo/framework/server";
|
|
@@ -759,6 +874,12 @@ const actionRefusal = (files) => `static build cannot ship Server Actions — a
|
|
|
759
874
|
*/
|
|
760
875
|
const guardRefusal = (files) => `static build cannot run guard.ts — a file has no request to guard, and these are guards:\n${files.map((file) => ` ${file}`).join("\n")}\n${WANTS_SERVER}`;
|
|
761
876
|
/**
|
|
877
|
+
* A `[...name]` directory answers pathnames of any depth, and a build writes
|
|
878
|
+
* a file per pathname it is told of — `paths.ts` gives one parameter's values,
|
|
879
|
+
* one segment each. Named every one at once.
|
|
880
|
+
*/
|
|
881
|
+
const restRefusal = (dirs) => `static build cannot write a [...name] directory — it answers a pathname of any depth, which only a request names, and ${dirs.length === 1 ? "this is one" : "these are"}:\n${dirs.map((dir) => ` ${dir}`).join("\n")}\n${WANTS_SERVER}`;
|
|
882
|
+
/**
|
|
762
883
|
* A page that reads the search is rendered for each search it is given, and a
|
|
763
884
|
* file is the same whatever the search holds. Named every one at once.
|
|
764
885
|
*/
|
|
@@ -780,13 +901,14 @@ const reexportRefusal = (files) => `static build reads a route.ts's methods and
|
|
|
780
901
|
const READ_BY_NAME = /* @__PURE__ */ new Set(["route", "page"]);
|
|
781
902
|
/**
|
|
782
903
|
* Static mode: the same request handler the server mode runs per request is
|
|
783
|
-
* called at build time — for each route
|
|
784
|
-
*
|
|
904
|
+
* called at build time — once for each route, whose HTML and the payload it
|
|
905
|
+
* was rendered from are both written to files.
|
|
785
906
|
* There is no server here, and the build refuses a Server Action, because a
|
|
786
907
|
* file cannot receive one.
|
|
787
908
|
*/
|
|
788
|
-
const staticMode = (options) => {
|
|
909
|
+
const staticMode = (options, host) => {
|
|
789
910
|
const { csp } = options;
|
|
911
|
+
const { origin } = new URL(options.site);
|
|
790
912
|
const unwritablePolicy = csp === void 0 ? [] : policyProblems(csp);
|
|
791
913
|
if (unwritablePolicy.length > 0) throw new Error(`the "csp" option cannot go into a page's <meta> as it is:\n${unwritablePolicy.map((problem) => ` ${problem}`).join("\n")}`);
|
|
792
914
|
let root = "";
|
|
@@ -796,10 +918,10 @@ const staticMode = (options) => {
|
|
|
796
918
|
let plugins = [];
|
|
797
919
|
const serverImporters = /* @__PURE__ */ new Set();
|
|
798
920
|
let routesRead;
|
|
799
|
-
let
|
|
800
|
-
let
|
|
801
|
-
let suppliedInDev = Promise.resolve([]);
|
|
921
|
+
let planRead;
|
|
922
|
+
let devServer;
|
|
802
923
|
const noticed = /* @__PURE__ */ new Set();
|
|
924
|
+
const warned = /* @__PURE__ */ new Set();
|
|
803
925
|
const fromRoot = (file) => path.relative(root, path.join(routesDir, file));
|
|
804
926
|
const devRoutes = () => routesRead ??= (async () => {
|
|
805
927
|
const { tree, problems } = parseRouteTree(await scanRoutes(routesDir));
|
|
@@ -807,65 +929,115 @@ const staticMode = (options) => {
|
|
|
807
929
|
return {
|
|
808
930
|
tree,
|
|
809
931
|
failed,
|
|
810
|
-
shapes: failed ? [] : fallbackShapes(tree)
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
const key = JSON.stringify(patterns);
|
|
817
|
-
if (key !== suppliedFor) {
|
|
818
|
-
suppliedFor = key;
|
|
819
|
-
noticed.clear();
|
|
820
|
-
suppliedInDev = (async () => await options.paths?.(patterns) ?? [])();
|
|
821
|
-
}
|
|
822
|
-
let given;
|
|
823
|
-
try {
|
|
824
|
-
given = await suppliedInDev;
|
|
825
|
-
} catch (error) {
|
|
826
|
-
suppliedFor = void 0;
|
|
827
|
-
logger?.error(`k8ordo: the "paths" option failed, so vite dev renders every value with page.tsx: ${messageOf(error)}`);
|
|
828
|
-
return NO_SHELLS;
|
|
829
|
-
}
|
|
830
|
-
const plan = planPaths(tree, given);
|
|
831
|
-
for (const refusal of planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths)))) logger?.warn(`k8ordo: the build will refuse "paths": ${refusal}`);
|
|
832
|
-
return {
|
|
833
|
-
paths: new Set(plan.paths),
|
|
834
|
-
shells: plan.shells
|
|
932
|
+
shapes: failed ? [] : fallbackShapes(tree),
|
|
933
|
+
needing: failed ? [] : patternsNeedingPaths(tree).map((pathname) => new URLPattern({ pathname })),
|
|
934
|
+
declared: failed ? [] : answeringPatterns(tree).map(({ pattern }) => ({
|
|
935
|
+
pattern,
|
|
936
|
+
matcher: new URLPattern({ pathname: pattern })
|
|
937
|
+
}))
|
|
835
938
|
};
|
|
836
939
|
})();
|
|
837
940
|
/**
|
|
838
|
-
*
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
*
|
|
941
|
+
* A paths.ts under `vite dev`, asked through the handler's own entry in the
|
|
942
|
+
* RSC environment's runner — the graph the pages are in, so it sees the
|
|
943
|
+
* application's aliases, an edit to it, or to what it imports, is what the
|
|
944
|
+
* next call reads, and it receives the params above as the build hands them.
|
|
945
|
+
*/
|
|
946
|
+
const devValues = async (file, above) => {
|
|
947
|
+
const environment = devServer?.environments.rsc;
|
|
948
|
+
if (environment === void 0 || !("runner" in environment)) throw new Error("the rsc environment cannot run a paths.ts");
|
|
949
|
+
const { runner } = environment;
|
|
950
|
+
const { pathValues } = await runner.import(path.join(host.runtimeDir, "entry.rsc.mjs"));
|
|
951
|
+
return pathValues(file, above);
|
|
952
|
+
};
|
|
953
|
+
/**
|
|
954
|
+
* What the build would write, as the paths.ts files say now. Kept until a
|
|
955
|
+
* file under `routes/` changes — and asked for again when a request names
|
|
956
|
+
* a value it does not hold, since the values come from data that changes
|
|
957
|
+
* with no file changing.
|
|
958
|
+
*/
|
|
959
|
+
const devPlan = (again = false) => {
|
|
960
|
+
if (again) planRead = void 0;
|
|
961
|
+
return planRead ??= (async () => {
|
|
962
|
+
const { tree } = await devRoutes();
|
|
963
|
+
let supplied;
|
|
964
|
+
try {
|
|
965
|
+
supplied = await suppliedFrom(tree, devValues);
|
|
966
|
+
} catch (error) {
|
|
967
|
+
planRead = void 0;
|
|
968
|
+
const message = `k8ordo: a paths.ts failed, so vite dev renders every value with page.tsx: ${messageOf(error)}`;
|
|
969
|
+
if (!warned.has(message)) {
|
|
970
|
+
warned.add(message);
|
|
971
|
+
logger?.error(message);
|
|
972
|
+
}
|
|
973
|
+
return NO_PLAN;
|
|
974
|
+
}
|
|
975
|
+
const plan = planPaths(tree, supplied);
|
|
976
|
+
for (const refusal of [...supplied.problems, ...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths)))]) {
|
|
977
|
+
if (warned.has(refusal)) continue;
|
|
978
|
+
warned.add(refusal);
|
|
979
|
+
logger?.warn(`k8ordo: the build will refuse this: ${refusal}`);
|
|
980
|
+
}
|
|
981
|
+
return {
|
|
982
|
+
paths: new Set(plan.paths),
|
|
983
|
+
shells: plan.shells,
|
|
984
|
+
failed: false
|
|
985
|
+
};
|
|
986
|
+
})();
|
|
987
|
+
};
|
|
988
|
+
/**
|
|
989
|
+
* Under `vite dev`, a value no paths.ts returns is answered as the build's
|
|
990
|
+
* host would answer it — so what works locally is what is deployed. With a
|
|
991
|
+
* fallback.tsx beside its page, that is the shell: the URL is rewritten to
|
|
992
|
+
* the shell pathname before the RSC plugin's handler reads it. Without
|
|
993
|
+
* one, it is the not-found: a document is rewritten to the pathname the
|
|
994
|
+
* build renders `404.html` from, and a payload — a file the host does not
|
|
995
|
+
* have — is a plain 404, which the browser answers by loading the
|
|
996
|
+
* document. Everything else passes untouched.
|
|
842
997
|
*/
|
|
843
|
-
const
|
|
844
|
-
if (request.method !== "GET" && request.method !== "HEAD") return;
|
|
845
|
-
const url = new URL(request.originalUrl ?? request.url ?? "/",
|
|
998
|
+
const answerUnbuilt = async (request, response) => {
|
|
999
|
+
if (request.method !== "GET" && request.method !== "HEAD") return false;
|
|
1000
|
+
const url = new URL(request.originalUrl ?? request.url ?? "/", origin);
|
|
846
1001
|
const own = withoutBase(url.pathname, base);
|
|
847
|
-
if (own === null) return;
|
|
1002
|
+
if (own === null) return false;
|
|
848
1003
|
const payload = isPayloadPath(own);
|
|
849
1004
|
const page = payload ? pagePathFor(own) : own;
|
|
850
1005
|
const routes = await devRoutes();
|
|
851
|
-
if (routes.failed
|
|
852
|
-
if (!routes.
|
|
853
|
-
const state = await devShells();
|
|
854
|
-
if (state.shells.length === 0) return;
|
|
1006
|
+
if (routes.failed) return false;
|
|
1007
|
+
if (!routes.needing.some((matcher) => matcher.test({ pathname: page }))) return false;
|
|
855
1008
|
const pathname = normalizePathname(page);
|
|
856
|
-
|
|
1009
|
+
const first = routes.declared.find(({ matcher }) => matcher.test({ pathname }));
|
|
1010
|
+
if (first === void 0 || isConcrete(first.pattern)) return false;
|
|
1011
|
+
if (pathname.split("/").some((segment) => decodePathname(segment) === "!fallback")) return false;
|
|
1012
|
+
let state = await devPlan();
|
|
1013
|
+
if (!state.failed && !state.paths.has(pathname)) state = await devPlan(true);
|
|
1014
|
+
if (state.failed || state.paths.has(pathname)) return false;
|
|
1015
|
+
const notice = (key, message) => {
|
|
1016
|
+
if (noticed.has(key)) return;
|
|
1017
|
+
noticed.add(key);
|
|
1018
|
+
logger?.info(message);
|
|
1019
|
+
};
|
|
857
1020
|
const answered = shellRules(state.shells, "/").filter((rule) => rule.to.endsWith("/")).find((rule) => rewriteFor([rule], page) !== null);
|
|
858
|
-
if (answered
|
|
859
|
-
|
|
860
|
-
|
|
1021
|
+
if (answered !== void 0) {
|
|
1022
|
+
const shell = answered.to.slice(0, -1);
|
|
1023
|
+
const target = `${withBase(payload ? `${shell}/index.rsc` : shell, base)}${url.search}`;
|
|
1024
|
+
request.originalUrl = target;
|
|
1025
|
+
request.url = target;
|
|
1026
|
+
const pattern = state.shells.find((each) => shellRules([each], "/").some((rule) => rule.from === answered.from))?.pattern;
|
|
1027
|
+
const fallback = routes.shapes.find((shape) => shape.pattern === pattern)?.file;
|
|
1028
|
+
if (fallback !== void 0) notice(fallback, `k8ordo: no paths.ts returns ${pathname}, so vite dev answers it with ${fallback}'s shell, as the build's host will`);
|
|
1029
|
+
return false;
|
|
1030
|
+
}
|
|
1031
|
+
notice(first.pattern, `k8ordo: no paths.ts returns ${pathname}, so vite dev answers it with the not-found, as the build's host will — return its value from the paths.ts of ${first.pattern} to render it`);
|
|
1032
|
+
const notFoundAt = catchAllPath(routes.tree);
|
|
1033
|
+
if (payload || notFoundAt === null) {
|
|
1034
|
+
response.writeHead(404).end();
|
|
1035
|
+
return true;
|
|
1036
|
+
}
|
|
1037
|
+
const target = `${withBase(notFoundAt, base)}${url.search}`;
|
|
861
1038
|
request.originalUrl = target;
|
|
862
1039
|
request.url = target;
|
|
863
|
-
|
|
864
|
-
const fallback = routes.shapes.find((shape) => shape.pattern === pattern)?.file;
|
|
865
|
-
if (fallback !== void 0 && !noticed.has(fallback)) {
|
|
866
|
-
noticed.add(fallback);
|
|
867
|
-
logger?.info(`k8ordo: ${pathname} is not in "paths", so vite dev answers it with ${fallback}'s shell — list it in "paths" to render page.tsx`);
|
|
868
|
-
}
|
|
1040
|
+
return false;
|
|
869
1041
|
};
|
|
870
1042
|
/**
|
|
871
1043
|
* Writes `dist/client/_redirects` once every file is in place — the
|
|
@@ -909,11 +1081,13 @@ const staticMode = (options) => {
|
|
|
909
1081
|
async handler() {
|
|
910
1082
|
const files = await scanRoutes(routesDir);
|
|
911
1083
|
const guards = files.filter((file) => slotOf(file) === "guard").map((file) => fromRoot(file));
|
|
1084
|
+
const restDirs = [...new Set(files.flatMap((file) => restDirOf(file) ?? []))].map((dir) => fromRoot(dir));
|
|
912
1085
|
const exported = await readExports(routesDir, files);
|
|
913
1086
|
const routes = [...exported].filter(([file]) => slotOf(file) === "route").map(([file, names]) => [fromRoot(file), unwritable(names)]).filter(([, methods]) => methods.length > 0);
|
|
914
1087
|
const searching = [...pagesReadingSearch(exported)].map((file) => fromRoot(file));
|
|
915
1088
|
const reexporting = [...exported].filter(([file, names]) => READ_BY_NAME.has(slotOf(file) ?? "") && names.has("*")).map(([file]) => fromRoot(file));
|
|
916
1089
|
const refusals = [
|
|
1090
|
+
...restDirs.length > 0 ? [restRefusal(restDirs)] : [],
|
|
917
1091
|
...guards.length > 0 ? [guardRefusal(guards)] : [],
|
|
918
1092
|
...routes.length > 0 ? [routeRefusal(routes)] : [],
|
|
919
1093
|
...searching.length > 0 ? [searchRefusal(searching)] : [],
|
|
@@ -926,17 +1100,14 @@ const staticMode = (options) => {
|
|
|
926
1100
|
name: "k8ordo:static",
|
|
927
1101
|
configResolved(config) {
|
|
928
1102
|
({root, plugins, base, logger} = config);
|
|
929
|
-
routesDir = path.resolve(root,
|
|
1103
|
+
routesDir = path.resolve(root, ROUTES_DIR);
|
|
930
1104
|
},
|
|
931
1105
|
configureServer: {
|
|
932
1106
|
order: "pre",
|
|
933
1107
|
handler(server) {
|
|
934
|
-
|
|
1108
|
+
devServer = server;
|
|
935
1109
|
return () => {
|
|
936
|
-
server.middlewares.use(middlewareOf(
|
|
937
|
-
await rewriteUnbuilt(request);
|
|
938
|
-
return false;
|
|
939
|
-
}));
|
|
1110
|
+
server.middlewares.use(middlewareOf(answerUnbuilt));
|
|
940
1111
|
};
|
|
941
1112
|
}
|
|
942
1113
|
},
|
|
@@ -945,7 +1116,7 @@ const staticMode = (options) => {
|
|
|
945
1116
|
const client = path.resolve(config.root, config.environments.client?.build.outDir ?? "dist/client");
|
|
946
1117
|
const rules = await readRules(client);
|
|
947
1118
|
const answeredHere = async (request, response) => {
|
|
948
|
-
const url = new URL(`${
|
|
1119
|
+
const url = new URL(`${origin}${request.url ?? "/"}`);
|
|
949
1120
|
if (withoutBase(url.pathname, config.base) === null) return false;
|
|
950
1121
|
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
951
1122
|
response.writeHead(405, { allow: "GET, HEAD" }).end();
|
|
@@ -971,7 +1142,9 @@ const staticMode = (options) => {
|
|
|
971
1142
|
watchChange(file) {
|
|
972
1143
|
if (!path.resolve(file).startsWith(`${routesDir}${path.sep}`)) return;
|
|
973
1144
|
routesRead = void 0;
|
|
974
|
-
|
|
1145
|
+
planRead = void 0;
|
|
1146
|
+
noticed.clear();
|
|
1147
|
+
warned.clear();
|
|
975
1148
|
},
|
|
976
1149
|
resolveId: {
|
|
977
1150
|
order: "pre",
|
|
@@ -992,6 +1165,8 @@ const staticMode = (options) => {
|
|
|
992
1165
|
const [module = id] = id.split("?");
|
|
993
1166
|
const file = path.relative(routesDir, module).split(path.sep).join("/");
|
|
994
1167
|
const slot = file.startsWith("..") ? null : slotOf(file);
|
|
1168
|
+
const restDir = file.startsWith("..") ? null : restDirOf(file);
|
|
1169
|
+
if (restDir !== null) throw new Error(restRefusal([fromRoot(restDir)]));
|
|
995
1170
|
if (slot === "guard") throw new Error(guardRefusal([path.relative(root, module)]));
|
|
996
1171
|
const names = READ_BY_NAME.has(slot ?? "") ? exportsOf(await readFile(module, "utf8"), file) : /* @__PURE__ */ new Set();
|
|
997
1172
|
if (names.has("*")) throw new Error(reexportRefusal([path.relative(root, module)]));
|
|
@@ -1006,28 +1181,28 @@ const staticMode = (options) => {
|
|
|
1006
1181
|
order: "post",
|
|
1007
1182
|
async handler(builder) {
|
|
1008
1183
|
const { tree } = parseRouteTree(await scanRoutes(routesDir));
|
|
1009
|
-
const
|
|
1184
|
+
const rscOut = builder.environments.rsc?.config.build.outDir;
|
|
1185
|
+
const client = builder.environments.client?.config;
|
|
1186
|
+
if (rscOut === void 0 || client === void 0) throw new Error("static build ran without the rsc/client builds");
|
|
1187
|
+
const built = await import(pathToFileURL(path.resolve(root, rscOut, "index.js")).href);
|
|
1188
|
+
const supplied = await suppliedFrom(tree, built.pathValues);
|
|
1189
|
+
const plan = planPaths(tree, supplied);
|
|
1010
1190
|
const answers = answersOf(tree, plan.paths);
|
|
1011
1191
|
const actions = serverActionModules(builder.config);
|
|
1012
1192
|
const importers = [...serverImporters].toSorted();
|
|
1013
1193
|
const refusals = [
|
|
1194
|
+
...supplied.problems,
|
|
1014
1195
|
...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths))),
|
|
1015
1196
|
...catchAllRefusals(tree),
|
|
1016
1197
|
...actions.length > 0 ? [actionRefusal(actions)] : [],
|
|
1017
1198
|
...importers.length > 0 ? [serverImportRefusal(importers)] : [],
|
|
1018
|
-
...routeFileRefusals(tree, plan, answers, {
|
|
1019
|
-
site: options.site !== void 0,
|
|
1020
|
-
named: fromRoot
|
|
1021
|
-
})
|
|
1199
|
+
...routeFileRefusals(tree, plan, answers, { named: fromRoot })
|
|
1022
1200
|
];
|
|
1023
1201
|
if (refusals.length > 0) throw new Error(refusals.join("\n\n"));
|
|
1024
|
-
const rscOut = builder.environments.rsc?.config.build.outDir;
|
|
1025
|
-
const client = builder.environments.client?.config;
|
|
1026
|
-
if (rscOut === void 0 || client === void 0) throw new Error("static build ran without the rsc/client builds");
|
|
1027
1202
|
const clientDir = path.resolve(root, client.build.outDir);
|
|
1028
|
-
const origin = options.site === void 0 ? ORIGIN : new URL(options.site).origin;
|
|
1029
1203
|
const render = {
|
|
1030
|
-
handler:
|
|
1204
|
+
handler: built.default,
|
|
1205
|
+
payloadOf: built.payloadOf,
|
|
1031
1206
|
clientDir,
|
|
1032
1207
|
urlFor: (pathname) => `${origin}${withBase(pathname, base)}`,
|
|
1033
1208
|
csp
|
|
@@ -1044,8 +1219,11 @@ const staticMode = (options) => {
|
|
|
1044
1219
|
for (const location of await leakingShells(clientDir, plan.shells)) builder.config.logger.warn(`k8ordo: the shell for ${location} has "${FALLBACK_SEGMENT}" in its HTML — a layout wrote the shell's pathname into the page (a link, a canonical URL); derive what depends on the URL in a client component`);
|
|
1045
1220
|
await writeClientFiles(clientDir, rendered);
|
|
1046
1221
|
const notPages = rendered.flatMap((each) => each.kind === "route" || each.kind === "redirect" ? [each.pathname] : []);
|
|
1047
|
-
|
|
1222
|
+
const listed = answers.get(SITEMAP_PATHNAME)?.kind !== "route";
|
|
1223
|
+
if (listed) await writeSitemap(clientDir, origin, plan.paths.filter((pathname) => !notPages.includes(pathname)).map((pathname) => withBase(pathname, base)));
|
|
1048
1224
|
const adapter = adapterOf(builder.config.plugins);
|
|
1225
|
+
const declared = options.headers ?? {};
|
|
1226
|
+
if (Object.keys(declared).length > 0) await writeFile(path.join(clientDir, "_headers"), formatHeaders(declared, await ownPublicFile(client.build.copyPublicDir ? builder.config.publicDir : "", "_headers")));
|
|
1049
1227
|
if (plan.shells.length > 0) {
|
|
1050
1228
|
const misread = await writeRedirects({
|
|
1051
1229
|
clientDir,
|
|
@@ -1062,7 +1240,7 @@ const staticMode = (options) => {
|
|
|
1062
1240
|
});
|
|
1063
1241
|
builder.config.logger.info(`k8ordo: wrote ${summaryOf(plan, {
|
|
1064
1242
|
notFound: notFoundAt !== null,
|
|
1065
|
-
sitemap:
|
|
1243
|
+
sitemap: listed
|
|
1066
1244
|
})}`);
|
|
1067
1245
|
}
|
|
1068
1246
|
}
|
|
@@ -1084,6 +1262,16 @@ const middlewareOf = (answered) => (request, response, next) => {
|
|
|
1084
1262
|
if (!done) next();
|
|
1085
1263
|
})();
|
|
1086
1264
|
};
|
|
1265
|
+
/** The application's own file of that name in `public/`, if there is one. */
|
|
1266
|
+
const ownPublicFile = async (publicDir, name) => {
|
|
1267
|
+
if (publicDir === "") return null;
|
|
1268
|
+
try {
|
|
1269
|
+
return await readFile(path.join(publicDir, name), "utf8");
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
if (error.code === "ENOENT") return null;
|
|
1272
|
+
throw error;
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1087
1275
|
/** The host adapter among the plugins, if any. */
|
|
1088
1276
|
const adapterOf = (plugins) => plugins.map((plugin) => plugin.api).find((api) => typeof api?.writeStatic === "function");
|
|
1089
1277
|
/**
|
|
@@ -1106,9 +1294,9 @@ const inParallel = async (tasks) => {
|
|
|
1106
1294
|
const FAILURES = {
|
|
1107
1295
|
render: (names) => `static build could not render ${names.join(", ")} — see the error above`,
|
|
1108
1296
|
route: (names) => `static build writes a route.ts from a GET that answers 200, and these did not: ${names.join(", ")}`,
|
|
1109
|
-
refused: (names) => `
|
|
1110
|
-
disowned: (names) => `
|
|
1111
|
-
shellRefused: (names) => `the
|
|
1297
|
+
refused: (names) => `a paths.ts returned values a params schema refused: ${names.join(", ")}`,
|
|
1298
|
+
disowned: (names) => `a paths.ts returned values whose page called notFound(): ${names.join(", ")}`,
|
|
1299
|
+
shellRefused: (names) => `the shells stand where a params schema refuses the values above them: ${names.join(", ")}`,
|
|
1112
1300
|
shellDisowned: (names) => names.map((location) => `the shell for ${location} called notFound() while it rendered, and a shell has no value to disown — call notFound() from the client component that reads the value in the browser`).join("\n"),
|
|
1113
1301
|
shellTaken: (names) => names.join("\n")
|
|
1114
1302
|
};
|
|
@@ -1132,30 +1320,26 @@ const renderRoute = async ({ handler, clientDir, urlFor }, pathname) => {
|
|
|
1132
1320
|
};
|
|
1133
1321
|
const renderPage = async (render, pathname) => {
|
|
1134
1322
|
const dir = path.join(render.clientDir, dirFor(pathname));
|
|
1135
|
-
const { status, notFound,
|
|
1323
|
+
const { status, notFound, files, payload } = await writeHtml(path.join(dir, "index.html"), render, render.urlFor(pathname), { notFoundIsPage: false });
|
|
1136
1324
|
if (status === 500) return failed("render", pathname);
|
|
1137
1325
|
if (status === 404) return failed(notFound ? "disowned" : "refused", pathname);
|
|
1138
1326
|
if (status === 307 || status === 308) return {
|
|
1139
1327
|
kind: "redirect",
|
|
1140
1328
|
pathname
|
|
1141
1329
|
};
|
|
1142
|
-
if (
|
|
1330
|
+
if (payload === null) return failed("render", pathname);
|
|
1331
|
+
await writeFile(path.join(dir, "index.rsc"), Buffer.from(payload));
|
|
1332
|
+
return {
|
|
1143
1333
|
kind: "document",
|
|
1144
|
-
|
|
1145
|
-
payload:
|
|
1334
|
+
files,
|
|
1335
|
+
payload: new URL(render.urlFor(payloadPathFor(pathname))).pathname
|
|
1146
1336
|
};
|
|
1147
|
-
const payload = render.urlFor(payloadPathFor(pathname));
|
|
1148
|
-
return (await writeBody(path.join(dir, "index.rsc"), render.handler, payload)).status === 200 ? {
|
|
1149
|
-
kind: "document",
|
|
1150
|
-
named,
|
|
1151
|
-
payload: new URL(payload).pathname
|
|
1152
|
-
} : failed("render", pathname);
|
|
1153
1337
|
};
|
|
1154
1338
|
const renderNotFound = async (render, pathname) => {
|
|
1155
|
-
const { status,
|
|
1339
|
+
const { status, files } = await writeHtml(path.join(render.clientDir, "404.html"), render, render.urlFor(pathname), { notFoundIsPage: true });
|
|
1156
1340
|
return status === 500 ? failed("render", "404.html") : {
|
|
1157
1341
|
kind: "document",
|
|
1158
|
-
|
|
1342
|
+
files,
|
|
1159
1343
|
payload: null
|
|
1160
1344
|
};
|
|
1161
1345
|
};
|
|
@@ -1169,12 +1353,14 @@ const renderShell = async (render, shell, fallbacks) => {
|
|
|
1169
1353
|
if (answered.status === 500) return failed("render", shell.location);
|
|
1170
1354
|
if (answered.status === 404) return failed(answered.notFound ? "shellDisowned" : "shellRefused", shell.location);
|
|
1171
1355
|
if (answered.shell === null) return failed("shellTaken", `the shell for ${named} was answered by another route, which took "${FALLBACK_SEGMENT}" as a value`);
|
|
1172
|
-
if (answered.shell !== shell.pattern) return failed("shellTaken", `the shell for ${named} was answered by ${fallbacks.get(answered.shell) ?? answered.shell}, which the table tries first —
|
|
1173
|
-
|
|
1356
|
+
if (answered.shell !== shell.pattern) return failed("shellTaken", `the shell for ${named} was answered by ${fallbacks.get(answered.shell) ?? answered.shell}, which the table tries first — put the shell where that pattern cannot match, with a paths.ts above it`);
|
|
1357
|
+
if (answered.payload === null) return failed("render", shell.location);
|
|
1358
|
+
await writeFile(path.join(dir, "index.rsc"), Buffer.from(answered.payload));
|
|
1359
|
+
return {
|
|
1174
1360
|
kind: "document",
|
|
1175
|
-
|
|
1361
|
+
files: answered.files,
|
|
1176
1362
|
payload: null
|
|
1177
|
-
}
|
|
1363
|
+
};
|
|
1178
1364
|
};
|
|
1179
1365
|
/** The shells whose HTML outside its scripts holds the shell pathname. */
|
|
1180
1366
|
const leakingShells = async (clientDir, shells) => (await Promise.all(shells.map(async (shell) => {
|
|
@@ -1182,11 +1368,11 @@ const leakingShells = async (clientDir, shells) => (await Promise.all(shells.map
|
|
|
1182
1368
|
return writtenOutsideScripts(html).some((written) => written.includes("!fallback")) ? [shell.location] : [];
|
|
1183
1369
|
}))).flat();
|
|
1184
1370
|
const writeClientFiles = async (clientDir, rendered) => {
|
|
1185
|
-
const documents = rendered.flatMap((each) => each.kind === "document" && each.
|
|
1186
|
-
await writeFile(path.join(clientDir, CLIENT_FILES_PATH.slice(1)), JSON.stringify(clientFiles(new Map(documents.flatMap(({ payload,
|
|
1371
|
+
const documents = rendered.flatMap((each) => each.kind === "document" && each.files !== null ? [each] : []);
|
|
1372
|
+
await writeFile(path.join(clientDir, CLIENT_FILES_PATH.slice(1)), JSON.stringify(clientFiles(new Map(documents.flatMap(({ payload, files }) => payload === null || files === null ? [] : [[payload, files]])), documents.map(({ files }) => files ?? []))));
|
|
1187
1373
|
};
|
|
1188
|
-
const writeSitemap = async (clientDir,
|
|
1189
|
-
await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(
|
|
1374
|
+
const writeSitemap = async (clientDir, origin, pathnames) => {
|
|
1375
|
+
await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(origin, pathnames));
|
|
1190
1376
|
};
|
|
1191
1377
|
/** The type each route.ts's `GET` answered with, by the file it wrote. */
|
|
1192
1378
|
const typesOf = (rendered) => new Map(rendered.flatMap((each) => each.kind === "route" && each.type !== null ? [[fileAt(each.pathname), each.type]] : []));
|
|
@@ -1200,7 +1386,7 @@ const summaryOf = (plan, { notFound, sitemap: listed }) => {
|
|
|
1200
1386
|
* HTML says the nonce the framework signed its scripts with, which the file
|
|
1201
1387
|
* says as hashes in the application's policy, if it gave one.
|
|
1202
1388
|
*/
|
|
1203
|
-
const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell }) => {
|
|
1389
|
+
const writeHtml = async (file, { handler, payloadOf, csp }, url, { notFoundIsPage, shell }) => {
|
|
1204
1390
|
const response = await handler(new Request(url));
|
|
1205
1391
|
const notFound = response.headers.has(NOT_FOUND_HEADER);
|
|
1206
1392
|
const answered = response.headers.get(SHELL_HEADER);
|
|
@@ -1208,7 +1394,8 @@ const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell })
|
|
|
1208
1394
|
status: response.status,
|
|
1209
1395
|
notFound,
|
|
1210
1396
|
shell: answered,
|
|
1211
|
-
|
|
1397
|
+
files: null,
|
|
1398
|
+
payload: payloadOf(response) ?? null
|
|
1212
1399
|
};
|
|
1213
1400
|
if (response.status === 500) {
|
|
1214
1401
|
console.error(`k8ordo: ${url} — ${await response.text()}`);
|
|
@@ -1223,15 +1410,13 @@ const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell })
|
|
|
1223
1410
|
return written;
|
|
1224
1411
|
}
|
|
1225
1412
|
const nonce = response.headers.get(NONCE_HEADER);
|
|
1226
|
-
if (nonce === null) {
|
|
1227
|
-
await writeFile(file, Buffer.from(await response.arrayBuffer()));
|
|
1228
|
-
return written;
|
|
1229
|
-
}
|
|
1413
|
+
if (nonce === null) throw new Error(`${url} answered HTML without saying the nonce it signed its scripts with`);
|
|
1230
1414
|
await writeFile(file, asFile(await response.text(), nonce, csp));
|
|
1231
|
-
const
|
|
1415
|
+
const named = response.headers.get(CLIENT_DEPS_HEADER);
|
|
1416
|
+
const linked = response.headers.get(SERVER_STYLESHEETS_HEADER);
|
|
1232
1417
|
return {
|
|
1233
1418
|
...written,
|
|
1234
|
-
|
|
1419
|
+
files: named === null ? null : [...readClientDeps(named).flatMap(({ js, css }) => js.concat(css)), ...linked === null ? [] : readServerStylesheets(linked)]
|
|
1235
1420
|
};
|
|
1236
1421
|
};
|
|
1237
1422
|
/**
|
|
@@ -1259,23 +1444,44 @@ const writeBody = async (file, handler, url) => {
|
|
|
1259
1444
|
};
|
|
1260
1445
|
// src/vite.ts
|
|
1261
1446
|
const RUNTIME_DIR = fileURLToPath(new URL("./runtime/", import.meta.url));
|
|
1262
|
-
const STATIC_ONLY = [
|
|
1263
|
-
"paths",
|
|
1264
|
-
"site",
|
|
1265
|
-
"csp"
|
|
1266
|
-
];
|
|
1267
1447
|
const shown = (value) => typeof value === "string" ? `'${value}'` : String(value);
|
|
1448
|
+
const kindOf = (value) => {
|
|
1449
|
+
if (value === null) return "null";
|
|
1450
|
+
if (Array.isArray(value)) return "an array";
|
|
1451
|
+
if (typeof value === "object") return "an object";
|
|
1452
|
+
return `a ${typeof value}`;
|
|
1453
|
+
};
|
|
1454
|
+
const notAnOrigin = (value) => {
|
|
1455
|
+
if (value === void 0) return "and got none";
|
|
1456
|
+
if (typeof value !== "string") return `and the value is not a string but ${kindOf(value)}`;
|
|
1457
|
+
if (value.includes("@")) return "and the site has an @, which no origin has (a username or a password comes before one, so the value is left out)";
|
|
1458
|
+
if (!URL.canParse(value)) return `and ${shown(value)} is not a URL`;
|
|
1459
|
+
const url = new URL(value);
|
|
1460
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return `and ${shown(value)} is served over ${url.protocol}, not http: or https:`;
|
|
1461
|
+
if (url.pathname !== "/") return `and ${shown(value)} has a path, ${url.pathname} — where under the origin the site sits is Vite's base`;
|
|
1462
|
+
if (url.search !== "") return `and ${shown(value)} has a query, ${url.search}`;
|
|
1463
|
+
if (url.hash !== "") return `and ${shown(value)} has a fragment, ${url.hash}`;
|
|
1464
|
+
return null;
|
|
1465
|
+
};
|
|
1268
1466
|
/**
|
|
1269
1467
|
* What the type already says, said again when the config is loaded: a
|
|
1270
1468
|
* `vite.config.js`, or a `vite.config.ts` outside the tsconfig, is never
|
|
1271
1469
|
* type-checked, and the options the type refuses do not fail on their own —
|
|
1272
|
-
* a mode that is not `'static'` builds no files,
|
|
1273
|
-
* `mode: 'server'` is a policy the application believes it has
|
|
1470
|
+
* a mode that is not `'static'` builds no files, a `csp` under
|
|
1471
|
+
* `mode: 'server'` is a policy the application believes it has, and a key
|
|
1472
|
+
* spelt wrong is an option that silently does nothing.
|
|
1274
1473
|
*/
|
|
1275
1474
|
const checked = (options) => {
|
|
1276
1475
|
const given = options ?? {};
|
|
1277
1476
|
const { mode } = given;
|
|
1278
1477
|
if (mode !== "static" && mode !== "server") throw new Error(`framework() needs mode: 'static' or 'server', and got ${shown(mode)}`);
|
|
1478
|
+
const taken = TAKEN[mode];
|
|
1479
|
+
const unknown = Object.keys(given).filter((name) => given[name] !== void 0 && !taken.includes(name) && !STATIC_ONLY.includes(name));
|
|
1480
|
+
if (unknown.length > 0) throw new Error(`framework() takes no ${unknown.join(", ")} — under mode: '${mode}' it takes ${taken.join(", ")}`);
|
|
1481
|
+
const notOrigin = mode === "static" ? notAnOrigin(given.site) : null;
|
|
1482
|
+
if (notOrigin !== null) throw new Error(`mode: 'static' needs site, the origin the site is served from, like 'https://example.com' — ${notOrigin}`);
|
|
1483
|
+
const refused = headersRefusal(given.headers);
|
|
1484
|
+
if (refused !== null) throw new Error(refused);
|
|
1279
1485
|
const staticOnly = STATIC_ONLY.filter((name) => given[name] !== void 0);
|
|
1280
1486
|
if (mode === "server" && staticOnly.length > 0) throw new Error(`mode: 'server' takes no ${staticOnly.join(", ")} — only mode: 'static' writes files for ${staticOnly.length === 1 ? "it" : "them"} to describe${staticOnly.includes("csp") ? "; under mode: 'server', a guard.ts writes the Content-Security-Policy header, with nonce()" : ""}`);
|
|
1281
1487
|
return options;
|
|
@@ -1287,9 +1493,13 @@ const checked = (options) => {
|
|
|
1287
1493
|
*/
|
|
1288
1494
|
const framework = (options) => {
|
|
1289
1495
|
const valid = checked(options);
|
|
1290
|
-
return [
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1496
|
+
return [
|
|
1497
|
+
headersPlugin(valid.headers ?? {}),
|
|
1498
|
+
...engine(valid, {
|
|
1499
|
+
mode: valid.mode,
|
|
1500
|
+
runtimeDir: RUNTIME_DIR
|
|
1501
|
+
}),
|
|
1502
|
+
...valid.mode === "static" ? staticMode(valid, { runtimeDir: RUNTIME_DIR }) : [serverMode()]
|
|
1503
|
+
];
|
|
1294
1504
|
};
|
|
1295
|
-
export { framework };
|
|
1505
|
+
export { framework, scriptHash };
|