@k8ordo/framework 2.3.1 → 3.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 +25 -12
- package/dist/generated.d.mts +2 -1
- package/dist/headers-BxB_jJVk.mjs +73 -0
- package/dist/index.d.mts +2 -1
- package/dist/paths-type-DtsL8JuC.d.mts +19 -0
- package/dist/runtime/app-router.mjs +20 -7
- 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/entry.rsc.d.mts +27 -1
- package/dist/runtime/entry.rsc.mjs +66 -9
- package/dist/runtime/entry.ssr.d.mts +6 -1
- package/dist/runtime/entry.ssr.mjs +8 -3
- 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/serve.mjs +5 -3
- package/dist/{static-DnbgGIoy.d.mts → static-c-nX9Juk.d.mts} +11 -17
- package/dist/{static-file-BAjwBMMl.mjs → static-file-BEk_xO5y.mjs} +157 -24
- package/dist/{static-host-B-1fAfAw.mjs → static-host-CyAmsL_7.mjs} +1 -1
- package/dist/vercel.d.mts +1 -1
- package/dist/vercel.mjs +30 -15
- package/dist/vite.d.mts +2 -2
- package/dist/vite.mjs +231 -111
- package/docs/GUIDE.md +26 -27
- package/docs/llms.txt +37 -28
- package/docs/references/deploy.md +69 -9
- package/docs/references/errors.md +39 -2
- package/docs/references/params.md +166 -127
- package/docs/references/routing.md +192 -49
- package/package.json +9 -9
- package/dist/shared-dir-CNXFRZgP.mjs +0 -9
package/dist/vite.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
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 emitRoutesModule, C as SHELL_HEADER, D as decodePathname, E as FALLBACK_SEGMENT, F as parseRouteTree, I as slotOf, M as FRAMEWORK, N as ROUTE_METHODS, O as LOCALES_MODULE, P as fallbackShapes, S as SERVER_STYLESHEETS_HEADER, T as readServerStylesheets, _ as suppliedFrom, a as catchAllPath, b as NONCE_HEADER, c as fileAt, d as patternsNeedingPaths, f as patternsOf, g as shadowedShells, h as routeFileRefusals, i as answersOf, j as unreachableRoutes, k as emitRegisterModule, l as isConcrete, m as planRefusals, o as catchAllRefusals, p as planPaths, s as dirFor, v as CLIENT_DEPS_HEADER, w as readClientDeps, x as NOT_FOUND_HEADER, y as CLIENT_FILES_PATH } from "./static-file-BEk_xO5y.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-CyAmsL_7.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";
|
|
10
11
|
import { existsSync } from "node:fs";
|
|
11
12
|
import react from "@vitejs/plugin-react";
|
|
12
13
|
import rsc, { getPluginApi } from "@vitejs/plugin-rsc";
|
|
@@ -187,6 +188,49 @@ 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
|
+
});
|
|
190
234
|
// ../framework-engine/dist/plugin/core.mjs
|
|
191
235
|
const VIRTUAL_ROUTES = "virtual:k8ordo/routes";
|
|
192
236
|
const VIRTUAL_LOCALES = "virtual:k8ordo/locales";
|
|
@@ -290,7 +334,8 @@ const engine = (options, host) => {
|
|
|
290
334
|
return {
|
|
291
335
|
define: {
|
|
292
336
|
"process.env.NODE_ENV": JSON.stringify(isProduction(env.mode) ? "production" : "development"),
|
|
293
|
-
"import.meta.env.K8ORDO_MODE": JSON.stringify(host.mode)
|
|
337
|
+
"import.meta.env.K8ORDO_MODE": JSON.stringify(host.mode),
|
|
338
|
+
"import.meta.env.K8ORDO_HEADERS": JSON.stringify(options.headers ?? {})
|
|
294
339
|
},
|
|
295
340
|
resolve: { dedupe: ["react", "react-dom"] },
|
|
296
341
|
environments: {
|
|
@@ -399,6 +444,7 @@ const engine = (options, host) => {
|
|
|
399
444
|
};
|
|
400
445
|
return [
|
|
401
446
|
react({ compiler: options.reactCompiler === true }),
|
|
447
|
+
mdxCss(),
|
|
402
448
|
rsc(),
|
|
403
449
|
plugin
|
|
404
450
|
];
|
|
@@ -572,15 +618,17 @@ const redirectPage = (to) => {
|
|
|
572
618
|
const escaped = escapeMarkup(to);
|
|
573
619
|
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
620
|
};
|
|
575
|
-
|
|
576
|
-
|
|
621
|
+
/**
|
|
622
|
+
* What `CLIENT_FILES_PATH` lists: each page's files, by its payload's path —
|
|
623
|
+
* what its client components need and what its Server Components link.
|
|
624
|
+
*/
|
|
577
625
|
const clientFiles = (pages, documents) => {
|
|
578
626
|
let everywhere;
|
|
579
|
-
for (const
|
|
580
|
-
const files =
|
|
627
|
+
for (const linked of documents) {
|
|
628
|
+
const files = new Set(linked);
|
|
581
629
|
everywhere = everywhere?.intersection(files) ?? files;
|
|
582
630
|
}
|
|
583
|
-
const own = [...pages].map(([page,
|
|
631
|
+
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
632
|
const files = [...new Set(own.flatMap(([, listed]) => listed))].toSorted();
|
|
585
633
|
const indexOf = new Map(files.map((file, index) => [file, index]));
|
|
586
634
|
return {
|
|
@@ -730,9 +778,10 @@ const writtenOutsideScripts = (html) => {
|
|
|
730
778
|
}
|
|
731
779
|
};
|
|
732
780
|
// src/static.ts
|
|
733
|
-
const
|
|
781
|
+
const NO_PLAN = {
|
|
734
782
|
paths: /* @__PURE__ */ new Set(),
|
|
735
|
-
shells: []
|
|
783
|
+
shells: [],
|
|
784
|
+
failed: true
|
|
736
785
|
};
|
|
737
786
|
/** Every file below a directory, relative to it, POSIX separators. */
|
|
738
787
|
const filesBelow = async (dir) => (await readdir(dir, {
|
|
@@ -780,8 +829,8 @@ const reexportRefusal = (files) => `static build reads a route.ts's methods and
|
|
|
780
829
|
const READ_BY_NAME = /* @__PURE__ */ new Set(["route", "page"]);
|
|
781
830
|
/**
|
|
782
831
|
* Static mode: the same request handler the server mode runs per request is
|
|
783
|
-
* called at build time — for each route
|
|
784
|
-
*
|
|
832
|
+
* called at build time — once for each route, whose HTML and the payload it
|
|
833
|
+
* was rendered from are both written to files.
|
|
785
834
|
* There is no server here, and the build refuses a Server Action, because a
|
|
786
835
|
* file cannot receive one.
|
|
787
836
|
*/
|
|
@@ -796,10 +845,10 @@ const staticMode = (options) => {
|
|
|
796
845
|
let plugins = [];
|
|
797
846
|
const serverImporters = /* @__PURE__ */ new Set();
|
|
798
847
|
let routesRead;
|
|
799
|
-
let
|
|
800
|
-
let
|
|
801
|
-
let suppliedInDev = Promise.resolve([]);
|
|
848
|
+
let planRead;
|
|
849
|
+
let devServer;
|
|
802
850
|
const noticed = /* @__PURE__ */ new Set();
|
|
851
|
+
const warned = /* @__PURE__ */ new Set();
|
|
803
852
|
const fromRoot = (file) => path.relative(root, path.join(routesDir, file));
|
|
804
853
|
const devRoutes = () => routesRead ??= (async () => {
|
|
805
854
|
const { tree, problems } = parseRouteTree(await scanRoutes(routesDir));
|
|
@@ -807,65 +856,115 @@ const staticMode = (options) => {
|
|
|
807
856
|
return {
|
|
808
857
|
tree,
|
|
809
858
|
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
|
|
859
|
+
shapes: failed ? [] : fallbackShapes(tree),
|
|
860
|
+
needing: failed ? [] : patternsNeedingPaths(tree).map((pathname) => new URLPattern({ pathname })),
|
|
861
|
+
declared: failed ? [] : patternsOf(tree).filter((pattern) => !pattern.endsWith("/*")).map((pattern) => ({
|
|
862
|
+
pattern,
|
|
863
|
+
matcher: new URLPattern({ pathname: pattern })
|
|
864
|
+
}))
|
|
835
865
|
};
|
|
836
866
|
})();
|
|
837
867
|
/**
|
|
838
|
-
*
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
|
|
868
|
+
* A paths.ts under `vite dev`, read through the RSC environment's runner —
|
|
869
|
+
* the graph the pages are in, so it sees the application's aliases and an
|
|
870
|
+
* edit to it, or to what it imports, is what the next call reads.
|
|
871
|
+
*/
|
|
872
|
+
const devValues = async (file, params) => {
|
|
873
|
+
const environment = devServer?.environments.rsc;
|
|
874
|
+
if (environment === void 0 || !("runner" in environment)) throw new Error("the rsc environment cannot run a paths.ts");
|
|
875
|
+
const { runner } = environment;
|
|
876
|
+
const { default: values } = await runner.import(path.join(routesDir, file));
|
|
877
|
+
if (typeof values !== "function") throw new TypeError(`${fromRoot(file)} has to export default a function returning its parameter's values`);
|
|
878
|
+
return values(params);
|
|
879
|
+
};
|
|
880
|
+
/**
|
|
881
|
+
* What the build would write, as the paths.ts files say now. Kept until a
|
|
882
|
+
* file under `routes/` changes — and asked for again when a request names
|
|
883
|
+
* a value it does not hold, since the values come from data that changes
|
|
884
|
+
* with no file changing.
|
|
842
885
|
*/
|
|
843
|
-
const
|
|
844
|
-
if (
|
|
886
|
+
const devPlan = (again = false) => {
|
|
887
|
+
if (again) planRead = void 0;
|
|
888
|
+
return planRead ??= (async () => {
|
|
889
|
+
const { tree } = await devRoutes();
|
|
890
|
+
let supplied;
|
|
891
|
+
try {
|
|
892
|
+
supplied = await suppliedFrom(tree, devValues);
|
|
893
|
+
} catch (error) {
|
|
894
|
+
planRead = void 0;
|
|
895
|
+
const message = `k8ordo: a paths.ts failed, so vite dev renders every value with page.tsx: ${messageOf(error)}`;
|
|
896
|
+
if (!warned.has(message)) {
|
|
897
|
+
warned.add(message);
|
|
898
|
+
logger?.error(message);
|
|
899
|
+
}
|
|
900
|
+
return NO_PLAN;
|
|
901
|
+
}
|
|
902
|
+
const plan = planPaths(tree, supplied.locations);
|
|
903
|
+
for (const refusal of [...supplied.problems, ...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths)))]) {
|
|
904
|
+
if (warned.has(refusal)) continue;
|
|
905
|
+
warned.add(refusal);
|
|
906
|
+
logger?.warn(`k8ordo: the build will refuse this: ${refusal}`);
|
|
907
|
+
}
|
|
908
|
+
return {
|
|
909
|
+
paths: new Set(plan.paths),
|
|
910
|
+
shells: plan.shells,
|
|
911
|
+
failed: false
|
|
912
|
+
};
|
|
913
|
+
})();
|
|
914
|
+
};
|
|
915
|
+
/**
|
|
916
|
+
* Under `vite dev`, a value no paths.ts returns is answered as the build's
|
|
917
|
+
* host would answer it — so what works locally is what is deployed. With a
|
|
918
|
+
* fallback.tsx beside its page, that is the shell: the URL is rewritten to
|
|
919
|
+
* the shell pathname before the RSC plugin's handler reads it. Without
|
|
920
|
+
* one, it is the not-found: a document is rewritten to the pathname the
|
|
921
|
+
* build renders `404.html` from, and a payload — a file the host does not
|
|
922
|
+
* have — is a plain 404, which the browser answers by loading the
|
|
923
|
+
* document. Everything else passes untouched.
|
|
924
|
+
*/
|
|
925
|
+
const answerUnbuilt = async (request, response) => {
|
|
926
|
+
if (request.method !== "GET" && request.method !== "HEAD") return false;
|
|
845
927
|
const url = new URL(request.originalUrl ?? request.url ?? "/", ORIGIN);
|
|
846
928
|
const own = withoutBase(url.pathname, base);
|
|
847
|
-
if (own === null) return;
|
|
929
|
+
if (own === null) return false;
|
|
848
930
|
const payload = isPayloadPath(own);
|
|
849
931
|
const page = payload ? pagePathFor(own) : own;
|
|
850
932
|
const routes = await devRoutes();
|
|
851
|
-
if (routes.failed
|
|
852
|
-
if (!routes.
|
|
853
|
-
const state = await devShells();
|
|
854
|
-
if (state.shells.length === 0) return;
|
|
933
|
+
if (routes.failed) return false;
|
|
934
|
+
if (!routes.needing.some((matcher) => matcher.test({ pathname: page }))) return false;
|
|
855
935
|
const pathname = normalizePathname(page);
|
|
856
|
-
|
|
936
|
+
const first = routes.declared.find(({ matcher }) => matcher.test({ pathname }));
|
|
937
|
+
if (first === void 0 || isConcrete(first.pattern)) return false;
|
|
938
|
+
if (pathname.split("/").some((segment) => decodePathname(segment) === "!fallback")) return false;
|
|
939
|
+
let state = await devPlan();
|
|
940
|
+
if (!state.failed && !state.paths.has(pathname)) state = await devPlan(true);
|
|
941
|
+
if (state.failed || state.paths.has(pathname)) return false;
|
|
942
|
+
const notice = (key, message) => {
|
|
943
|
+
if (noticed.has(key)) return;
|
|
944
|
+
noticed.add(key);
|
|
945
|
+
logger?.info(message);
|
|
946
|
+
};
|
|
857
947
|
const answered = shellRules(state.shells, "/").filter((rule) => rule.to.endsWith("/")).find((rule) => rewriteFor([rule], page) !== null);
|
|
858
|
-
if (answered
|
|
859
|
-
|
|
860
|
-
|
|
948
|
+
if (answered !== void 0) {
|
|
949
|
+
const shell = answered.to.slice(0, -1);
|
|
950
|
+
const target = `${withBase(payload ? `${shell}/index.rsc` : shell, base)}${url.search}`;
|
|
951
|
+
request.originalUrl = target;
|
|
952
|
+
request.url = target;
|
|
953
|
+
const pattern = state.shells.find((each) => shellRules([each], "/").some((rule) => rule.from === answered.from))?.pattern;
|
|
954
|
+
const fallback = routes.shapes.find((shape) => shape.pattern === pattern)?.file;
|
|
955
|
+
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`);
|
|
956
|
+
return false;
|
|
957
|
+
}
|
|
958
|
+
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`);
|
|
959
|
+
const notFoundAt = catchAllPath(routes.tree);
|
|
960
|
+
if (payload || notFoundAt === null) {
|
|
961
|
+
response.writeHead(404).end();
|
|
962
|
+
return true;
|
|
963
|
+
}
|
|
964
|
+
const target = `${withBase(notFoundAt, base)}${url.search}`;
|
|
861
965
|
request.originalUrl = target;
|
|
862
966
|
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
|
-
}
|
|
967
|
+
return false;
|
|
869
968
|
};
|
|
870
969
|
/**
|
|
871
970
|
* Writes `dist/client/_redirects` once every file is in place — the
|
|
@@ -931,12 +1030,9 @@ const staticMode = (options) => {
|
|
|
931
1030
|
configureServer: {
|
|
932
1031
|
order: "pre",
|
|
933
1032
|
handler(server) {
|
|
934
|
-
|
|
1033
|
+
devServer = server;
|
|
935
1034
|
return () => {
|
|
936
|
-
server.middlewares.use(middlewareOf(
|
|
937
|
-
await rewriteUnbuilt(request);
|
|
938
|
-
return false;
|
|
939
|
-
}));
|
|
1035
|
+
server.middlewares.use(middlewareOf(answerUnbuilt));
|
|
940
1036
|
};
|
|
941
1037
|
}
|
|
942
1038
|
},
|
|
@@ -971,7 +1067,9 @@ const staticMode = (options) => {
|
|
|
971
1067
|
watchChange(file) {
|
|
972
1068
|
if (!path.resolve(file).startsWith(`${routesDir}${path.sep}`)) return;
|
|
973
1069
|
routesRead = void 0;
|
|
974
|
-
|
|
1070
|
+
planRead = void 0;
|
|
1071
|
+
noticed.clear();
|
|
1072
|
+
warned.clear();
|
|
975
1073
|
},
|
|
976
1074
|
resolveId: {
|
|
977
1075
|
order: "pre",
|
|
@@ -1006,28 +1104,29 @@ const staticMode = (options) => {
|
|
|
1006
1104
|
order: "post",
|
|
1007
1105
|
async handler(builder) {
|
|
1008
1106
|
const { tree } = parseRouteTree(await scanRoutes(routesDir));
|
|
1009
|
-
const
|
|
1107
|
+
const rscOut = builder.environments.rsc?.config.build.outDir;
|
|
1108
|
+
const client = builder.environments.client?.config;
|
|
1109
|
+
if (rscOut === void 0 || client === void 0) throw new Error("static build ran without the rsc/client builds");
|
|
1110
|
+
const built = await import(pathToFileURL(path.resolve(root, rscOut, "index.js")).href);
|
|
1111
|
+
const supplied = await suppliedFrom(tree, built.pathValues);
|
|
1112
|
+
const plan = planPaths(tree, supplied.locations);
|
|
1010
1113
|
const answers = answersOf(tree, plan.paths);
|
|
1011
1114
|
const actions = serverActionModules(builder.config);
|
|
1012
1115
|
const importers = [...serverImporters].toSorted();
|
|
1013
1116
|
const refusals = [
|
|
1117
|
+
...supplied.problems,
|
|
1014
1118
|
...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths))),
|
|
1015
1119
|
...catchAllRefusals(tree),
|
|
1016
1120
|
...actions.length > 0 ? [actionRefusal(actions)] : [],
|
|
1017
1121
|
...importers.length > 0 ? [serverImportRefusal(importers)] : [],
|
|
1018
|
-
...routeFileRefusals(tree, plan, answers, {
|
|
1019
|
-
site: options.site !== void 0,
|
|
1020
|
-
named: fromRoot
|
|
1021
|
-
})
|
|
1122
|
+
...routeFileRefusals(tree, plan, answers, { named: fromRoot })
|
|
1022
1123
|
];
|
|
1023
1124
|
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
1125
|
const clientDir = path.resolve(root, client.build.outDir);
|
|
1028
1126
|
const origin = options.site === void 0 ? ORIGIN : new URL(options.site).origin;
|
|
1029
1127
|
const render = {
|
|
1030
|
-
handler:
|
|
1128
|
+
handler: built.default,
|
|
1129
|
+
payloadOf: built.payloadOf,
|
|
1031
1130
|
clientDir,
|
|
1032
1131
|
urlFor: (pathname) => `${origin}${withBase(pathname, base)}`,
|
|
1033
1132
|
csp
|
|
@@ -1044,8 +1143,11 @@ const staticMode = (options) => {
|
|
|
1044
1143
|
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
1144
|
await writeClientFiles(clientDir, rendered);
|
|
1046
1145
|
const notPages = rendered.flatMap((each) => each.kind === "route" || each.kind === "redirect" ? [each.pathname] : []);
|
|
1047
|
-
|
|
1146
|
+
const listed = answers.get("/sitemap.xml")?.kind === "route" ? void 0 : options.site;
|
|
1147
|
+
if (listed !== void 0) await writeSitemap(clientDir, listed, plan.paths.filter((pathname) => !notPages.includes(pathname)).map((pathname) => withBase(pathname, base)));
|
|
1048
1148
|
const adapter = adapterOf(builder.config.plugins);
|
|
1149
|
+
const declared = options.headers ?? {};
|
|
1150
|
+
if (Object.keys(declared).length > 0) await writeFile(path.join(clientDir, "_headers"), formatHeaders(declared, await ownPublicFile(client.build.copyPublicDir ? builder.config.publicDir : "", "_headers")));
|
|
1049
1151
|
if (plan.shells.length > 0) {
|
|
1050
1152
|
const misread = await writeRedirects({
|
|
1051
1153
|
clientDir,
|
|
@@ -1062,7 +1164,7 @@ const staticMode = (options) => {
|
|
|
1062
1164
|
});
|
|
1063
1165
|
builder.config.logger.info(`k8ordo: wrote ${summaryOf(plan, {
|
|
1064
1166
|
notFound: notFoundAt !== null,
|
|
1065
|
-
sitemap:
|
|
1167
|
+
sitemap: listed !== void 0
|
|
1066
1168
|
})}`);
|
|
1067
1169
|
}
|
|
1068
1170
|
}
|
|
@@ -1084,6 +1186,16 @@ const middlewareOf = (answered) => (request, response, next) => {
|
|
|
1084
1186
|
if (!done) next();
|
|
1085
1187
|
})();
|
|
1086
1188
|
};
|
|
1189
|
+
/** The application's own file of that name in `public/`, if there is one. */
|
|
1190
|
+
const ownPublicFile = async (publicDir, name) => {
|
|
1191
|
+
if (publicDir === "") return null;
|
|
1192
|
+
try {
|
|
1193
|
+
return await readFile(path.join(publicDir, name), "utf8");
|
|
1194
|
+
} catch (error) {
|
|
1195
|
+
if (error.code === "ENOENT") return null;
|
|
1196
|
+
throw error;
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1087
1199
|
/** The host adapter among the plugins, if any. */
|
|
1088
1200
|
const adapterOf = (plugins) => plugins.map((plugin) => plugin.api).find((api) => typeof api?.writeStatic === "function");
|
|
1089
1201
|
/**
|
|
@@ -1106,9 +1218,9 @@ const inParallel = async (tasks) => {
|
|
|
1106
1218
|
const FAILURES = {
|
|
1107
1219
|
render: (names) => `static build could not render ${names.join(", ")} — see the error above`,
|
|
1108
1220
|
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
|
|
1221
|
+
refused: (names) => `a paths.ts returned values a params schema refused: ${names.join(", ")}`,
|
|
1222
|
+
disowned: (names) => `a paths.ts returned values whose page called notFound(): ${names.join(", ")}`,
|
|
1223
|
+
shellRefused: (names) => `the shells stand where a params schema refuses the values above them: ${names.join(", ")}`,
|
|
1112
1224
|
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
1225
|
shellTaken: (names) => names.join("\n")
|
|
1114
1226
|
};
|
|
@@ -1132,7 +1244,7 @@ const renderRoute = async ({ handler, clientDir, urlFor }, pathname) => {
|
|
|
1132
1244
|
};
|
|
1133
1245
|
const renderPage = async (render, pathname) => {
|
|
1134
1246
|
const dir = path.join(render.clientDir, dirFor(pathname));
|
|
1135
|
-
const { status, notFound,
|
|
1247
|
+
const { status, notFound, files, payload } = await writeHtml(path.join(dir, "index.html"), render, render.urlFor(pathname), { notFoundIsPage: false });
|
|
1136
1248
|
if (status === 500) return failed("render", pathname);
|
|
1137
1249
|
if (status === 404) return failed(notFound ? "disowned" : "refused", pathname);
|
|
1138
1250
|
if (status === 307 || status === 308) return {
|
|
@@ -1141,21 +1253,22 @@ const renderPage = async (render, pathname) => {
|
|
|
1141
1253
|
};
|
|
1142
1254
|
if (status !== 200) return {
|
|
1143
1255
|
kind: "document",
|
|
1144
|
-
|
|
1256
|
+
files,
|
|
1145
1257
|
payload: null
|
|
1146
1258
|
};
|
|
1147
|
-
|
|
1148
|
-
|
|
1259
|
+
if (payload === null) return failed("render", pathname);
|
|
1260
|
+
await writeFile(path.join(dir, "index.rsc"), Buffer.from(payload));
|
|
1261
|
+
return {
|
|
1149
1262
|
kind: "document",
|
|
1150
|
-
|
|
1151
|
-
payload: new URL(
|
|
1152
|
-
}
|
|
1263
|
+
files,
|
|
1264
|
+
payload: new URL(render.urlFor(payloadPathFor(pathname))).pathname
|
|
1265
|
+
};
|
|
1153
1266
|
};
|
|
1154
1267
|
const renderNotFound = async (render, pathname) => {
|
|
1155
|
-
const { status,
|
|
1268
|
+
const { status, files } = await writeHtml(path.join(render.clientDir, "404.html"), render, render.urlFor(pathname), { notFoundIsPage: true });
|
|
1156
1269
|
return status === 500 ? failed("render", "404.html") : {
|
|
1157
1270
|
kind: "document",
|
|
1158
|
-
|
|
1271
|
+
files,
|
|
1159
1272
|
payload: null
|
|
1160
1273
|
};
|
|
1161
1274
|
};
|
|
@@ -1169,12 +1282,14 @@ const renderShell = async (render, shell, fallbacks) => {
|
|
|
1169
1282
|
if (answered.status === 500) return failed("render", shell.location);
|
|
1170
1283
|
if (answered.status === 404) return failed(answered.notFound ? "shellDisowned" : "shellRefused", shell.location);
|
|
1171
1284
|
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
|
-
|
|
1285
|
+
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`);
|
|
1286
|
+
if (answered.payload === null) return failed("render", shell.location);
|
|
1287
|
+
await writeFile(path.join(dir, "index.rsc"), Buffer.from(answered.payload));
|
|
1288
|
+
return {
|
|
1174
1289
|
kind: "document",
|
|
1175
|
-
|
|
1290
|
+
files: answered.files,
|
|
1176
1291
|
payload: null
|
|
1177
|
-
}
|
|
1292
|
+
};
|
|
1178
1293
|
};
|
|
1179
1294
|
/** The shells whose HTML outside its scripts holds the shell pathname. */
|
|
1180
1295
|
const leakingShells = async (clientDir, shells) => (await Promise.all(shells.map(async (shell) => {
|
|
@@ -1182,8 +1297,8 @@ const leakingShells = async (clientDir, shells) => (await Promise.all(shells.map
|
|
|
1182
1297
|
return writtenOutsideScripts(html).some((written) => written.includes("!fallback")) ? [shell.location] : [];
|
|
1183
1298
|
}))).flat();
|
|
1184
1299
|
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,
|
|
1300
|
+
const documents = rendered.flatMap((each) => each.kind === "document" && each.files !== null ? [each] : []);
|
|
1301
|
+
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
1302
|
};
|
|
1188
1303
|
const writeSitemap = async (clientDir, site, pathnames) => {
|
|
1189
1304
|
await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(site, pathnames));
|
|
@@ -1200,7 +1315,7 @@ const summaryOf = (plan, { notFound, sitemap: listed }) => {
|
|
|
1200
1315
|
* HTML says the nonce the framework signed its scripts with, which the file
|
|
1201
1316
|
* says as hashes in the application's policy, if it gave one.
|
|
1202
1317
|
*/
|
|
1203
|
-
const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell }) => {
|
|
1318
|
+
const writeHtml = async (file, { handler, payloadOf, csp }, url, { notFoundIsPage, shell }) => {
|
|
1204
1319
|
const response = await handler(new Request(url));
|
|
1205
1320
|
const notFound = response.headers.has(NOT_FOUND_HEADER);
|
|
1206
1321
|
const answered = response.headers.get(SHELL_HEADER);
|
|
@@ -1208,7 +1323,8 @@ const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell })
|
|
|
1208
1323
|
status: response.status,
|
|
1209
1324
|
notFound,
|
|
1210
1325
|
shell: answered,
|
|
1211
|
-
|
|
1326
|
+
files: null,
|
|
1327
|
+
payload: payloadOf(response) ?? null
|
|
1212
1328
|
};
|
|
1213
1329
|
if (response.status === 500) {
|
|
1214
1330
|
console.error(`k8ordo: ${url} — ${await response.text()}`);
|
|
@@ -1228,10 +1344,11 @@ const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell })
|
|
|
1228
1344
|
return written;
|
|
1229
1345
|
}
|
|
1230
1346
|
await writeFile(file, asFile(await response.text(), nonce, csp));
|
|
1231
|
-
const
|
|
1347
|
+
const named = response.headers.get(CLIENT_DEPS_HEADER);
|
|
1348
|
+
const linked = response.headers.get(SERVER_STYLESHEETS_HEADER);
|
|
1232
1349
|
return {
|
|
1233
1350
|
...written,
|
|
1234
|
-
|
|
1351
|
+
files: named === null ? null : [...readClientDeps(named).flatMap(({ js, css }) => js.concat(css)), ...linked === null ? [] : readServerStylesheets(linked)]
|
|
1235
1352
|
};
|
|
1236
1353
|
};
|
|
1237
1354
|
/**
|
|
@@ -1259,11 +1376,7 @@ const writeBody = async (file, handler, url) => {
|
|
|
1259
1376
|
};
|
|
1260
1377
|
// src/vite.ts
|
|
1261
1378
|
const RUNTIME_DIR = fileURLToPath(new URL("./runtime/", import.meta.url));
|
|
1262
|
-
const STATIC_ONLY = [
|
|
1263
|
-
"paths",
|
|
1264
|
-
"site",
|
|
1265
|
-
"csp"
|
|
1266
|
-
];
|
|
1379
|
+
const STATIC_ONLY = ["site", "csp"];
|
|
1267
1380
|
const shown = (value) => typeof value === "string" ? `'${value}'` : String(value);
|
|
1268
1381
|
/**
|
|
1269
1382
|
* What the type already says, said again when the config is loaded: a
|
|
@@ -1276,6 +1389,9 @@ const checked = (options) => {
|
|
|
1276
1389
|
const given = options ?? {};
|
|
1277
1390
|
const { mode } = given;
|
|
1278
1391
|
if (mode !== "static" && mode !== "server") throw new Error(`framework() needs mode: 'static' or 'server', and got ${shown(mode)}`);
|
|
1392
|
+
if (given.paths !== void 0) throw new Error("framework() takes no paths — a parameter's values come from a paths.ts in its directory under routes/");
|
|
1393
|
+
const refused = headersRefusal(given.headers);
|
|
1394
|
+
if (refused !== null) throw new Error(refused);
|
|
1279
1395
|
const staticOnly = STATIC_ONLY.filter((name) => given[name] !== void 0);
|
|
1280
1396
|
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
1397
|
return options;
|
|
@@ -1287,9 +1403,13 @@ const checked = (options) => {
|
|
|
1287
1403
|
*/
|
|
1288
1404
|
const framework = (options) => {
|
|
1289
1405
|
const valid = checked(options);
|
|
1290
|
-
return [
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1406
|
+
return [
|
|
1407
|
+
headersPlugin(valid.headers ?? {}),
|
|
1408
|
+
...engine(valid, {
|
|
1409
|
+
mode: valid.mode,
|
|
1410
|
+
runtimeDir: RUNTIME_DIR
|
|
1411
|
+
}),
|
|
1412
|
+
...valid.mode === "static" ? staticMode(valid) : [serverMode()]
|
|
1413
|
+
];
|
|
1294
1414
|
};
|
|
1295
1415
|
export { framework };
|