@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.4
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/actions.d.ts +7 -0
- package/dist/actions.js +21 -3
- package/dist/actions.test.js +8 -410
- package/dist/after.d.ts +28 -0
- package/dist/after.js +48 -0
- package/dist/after.test.js +58 -0
- package/dist/assets-static.d.ts +10 -1
- package/dist/assets-static.js +10 -2
- package/dist/base-path.js +4 -3
- package/dist/builtin-tags.d.ts +12 -0
- package/dist/builtin-tags.js +42 -0
- package/dist/builtin-tags.test.js +12 -0
- package/dist/cache-adapter.test.js +4 -203
- package/dist/cache-scope.d.ts +2 -0
- package/dist/cache.test.js +1 -197
- package/dist/cloudflare-workers.d.ts +2 -0
- package/dist/cloudflare-workers.js +27 -0
- package/dist/dev-overlay.d.ts +54 -3
- package/dist/dev-overlay.js +469 -76
- package/dist/dom.js +3 -1
- package/dist/events.test.js +2 -407
- package/dist/handler-html.test.js +1 -202
- package/dist/handler-routing.js +3 -0
- package/dist/handler-segments.d.ts +6 -0
- package/dist/handler-segments.js +16 -2
- package/dist/handler-segments.test.js +8 -200
- package/dist/head-tags.d.ts +9 -0
- package/dist/head-tags.js +85 -1
- package/dist/head-tags.test.js +18 -125
- package/dist/index.d.ts +1 -5
- package/dist/index.js +3 -0
- package/dist/inline-action-token.test.js +31 -0
- package/dist/jsx-svg-types.test.js +58 -0
- package/dist/jsx-types.d.ts +92 -1
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +384 -65
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router-lite.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +2 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/link-base-path.test.js +28 -0
- package/dist/node-server.test.js +1 -355
- package/dist/platform.d.ts +52 -0
- package/dist/platform.js +57 -0
- package/dist/platform.test.js +44 -0
- package/dist/router-nav.test.js +15 -444
- package/dist/router.js +39 -1
- package/dist/server-handler.d.ts +48 -0
- package/dist/server-handler.js +279 -17
- package/dist/server-handler.test.js +54 -388
- package/dist/server-renderer.test.js +0 -104
- package/dist/server.d.ts +15 -5
- package/dist/server.js +149 -22
- package/dist/server.test.js +52 -60
- package/dist/site-config.d.ts +13 -0
- package/dist/site-config.js +28 -0
- package/dist/site-config.test.js +30 -0
- package/dist/slot.d.ts +12 -0
- package/dist/slot.js +23 -0
- package/dist/slot.test.js +25 -0
- package/dist/ssr-core-behavior.test.js +3 -515
- package/dist/testing.d.ts +59 -0
- package/dist/testing.js +88 -0
- package/dist/testing.test.js +73 -0
- package/package.json +9 -1
- package/dist/action-context.test.js +0 -72
- package/dist/base-path.test.js +0 -88
- package/dist/class-component.test.js +0 -462
- package/dist/class-helpers.test.js +0 -169
- package/dist/context.test.js +0 -57
- package/dist/derived.test.js +0 -140
- package/dist/dev-overlay.test.js +0 -165
- package/dist/discrete.test.js +0 -100
- package/dist/dom.test.js +0 -39
- package/dist/effect-errors.test.d.ts +0 -1
- package/dist/effect-errors.test.js +0 -199
- package/dist/effects.test.d.ts +0 -1
- package/dist/effects.test.js +0 -485
- package/dist/handler-routing.test.d.ts +0 -1
- package/dist/handler-routing.test.js +0 -99
- package/dist/highlight-bind.test.d.ts +0 -1
- package/dist/highlight-bind.test.js +0 -124
- package/dist/highlight.test.d.ts +0 -1
- package/dist/highlight.test.js +0 -56
- package/dist/lanes.test.d.ts +0 -1
- package/dist/lanes.test.js +0 -59
- package/dist/list.test.d.ts +0 -1
- package/dist/list.test.js +0 -435
- package/dist/metadata.test.d.ts +0 -1
- package/dist/metadata.test.js +0 -167
- package/dist/navigation.test.d.ts +0 -1
- package/dist/navigation.test.js +0 -130
- package/dist/optimistic-lanes.test.d.ts +0 -1
- package/dist/optimistic-lanes.test.js +0 -45
- package/dist/patterns.test.d.ts +0 -1
- package/dist/patterns.test.js +0 -125
- package/dist/portal.test.d.ts +0 -1
- package/dist/portal.test.js +0 -99
- package/dist/react-effects.test.d.ts +0 -1
- package/dist/react-effects.test.js +0 -133
- package/dist/react-suspense.test.d.ts +0 -1
- package/dist/react-suspense.test.js +0 -194
- package/dist/react.test.d.ts +0 -1
- package/dist/react.test.js +0 -60
- package/dist/react19.test.d.ts +0 -1
- package/dist/react19.test.js +0 -176
- package/dist/reactivity-core.test.d.ts +0 -1
- package/dist/reactivity-core.test.js +0 -152
- package/dist/reconcile.test.d.ts +0 -1
- package/dist/reconcile.test.js +0 -110
- package/dist/refs.test.d.ts +0 -1
- package/dist/refs.test.js +0 -257
- package/dist/router-layout.test.d.ts +0 -1
- package/dist/router-layout.test.js +0 -249
- package/dist/router-slots.test.d.ts +0 -1
- package/dist/router-slots.test.js +0 -144
- package/dist/router-speculation.test.d.ts +0 -1
- package/dist/router-speculation.test.js +0 -25
- package/dist/router-styles.test.d.ts +0 -1
- package/dist/router-styles.test.js +0 -98
- package/dist/router.test.d.ts +0 -1
- package/dist/router.test.js +0 -36
- package/dist/server-async.test.d.ts +0 -1
- package/dist/server-async.test.js +0 -216
- package/dist/server-highlight.test.d.ts +0 -1
- package/dist/server-highlight.test.js +0 -32
- package/dist/signal-lanes.test.d.ts +0 -1
- package/dist/signal-lanes.test.js +0 -32
- package/dist/slots.test.d.ts +0 -1
- package/dist/slots.test.js +0 -187
- package/dist/snapshots.test.d.ts +0 -1
- package/dist/snapshots.test.js +0 -208
- package/dist/ssr-core.test.d.ts +0 -1
- package/dist/ssr-core.test.js +0 -324
- package/dist/static-memory.test.d.ts +0 -1
- package/dist/static-memory.test.js +0 -26
- package/dist/storage.test.d.ts +0 -1
- package/dist/storage.test.js +0 -46
- package/dist/suspense-actions.test.d.ts +0 -1
- package/dist/suspense-actions.test.js +0 -72
- package/dist/suspense.test.d.ts +0 -1
- package/dist/suspense.test.js +0 -556
- /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
- /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
- /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
- /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
- /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
- /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
- /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
- /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
- /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
package/dist/server-handler.js
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
// generates (`krate deploy`), and static files come from a pluggable layer.
|
|
12
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
13
13
|
import { createSSRCore, MemoryIsrStore, } from "./ssr-core.js";
|
|
14
|
+
import { runAfterTasks } from "./after.js";
|
|
15
|
+
import { platformWaitUntil } from "./platform.js";
|
|
14
16
|
import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
|
|
15
17
|
import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectFlashNotice, parseRegionShell, regionReplaceScript, requestFlash, signFlash, spliceShell, splitBodyScripts, } from "./handler-html.js";
|
|
16
18
|
import { mergeHead } from "./head-tags.js";
|
|
@@ -21,6 +23,25 @@ import { sha256Hex as portableSha256Hex } from "./sha256.js";
|
|
|
21
23
|
import { INVALIDATE_CHANNEL, cacheSpecFromConfig } from "./cache-adapter.js";
|
|
22
24
|
import { isrStoreFor } from "./shared-isr.js";
|
|
23
25
|
import { createMemoryStaticLayer } from "./static-memory.js";
|
|
26
|
+
/** The API route key serving URL path p, or "" when no metadata route does. */
|
|
27
|
+
export function matchMetaRoute(routes, p) {
|
|
28
|
+
for (const r of routes || []) {
|
|
29
|
+
if (r.path) {
|
|
30
|
+
if (p === r.path)
|
|
31
|
+
return r.key;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const prefix = r.prefix || "";
|
|
35
|
+
const suffix = r.suffix || "";
|
|
36
|
+
if (p.length <= prefix.length + suffix.length || !p.startsWith(prefix) || !p.endsWith(suffix))
|
|
37
|
+
continue;
|
|
38
|
+
const id = p.slice(prefix.length, p.length - suffix.length);
|
|
39
|
+
if (/[\/\\]/.test(id) || id === "." || id === "..")
|
|
40
|
+
continue;
|
|
41
|
+
return r.key.replace(/\[id\]$/, "") + id;
|
|
42
|
+
}
|
|
43
|
+
return "";
|
|
44
|
+
}
|
|
24
45
|
// Internals
|
|
25
46
|
const NO_BODY_STATUS = new Set([101, 204, 205, 304]);
|
|
26
47
|
const KRATE_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
|
|
@@ -35,6 +56,28 @@ function globalStore(name) {
|
|
|
35
56
|
g[key] = new AsyncLocalStorage();
|
|
36
57
|
return g[key];
|
|
37
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Runs fn with the platform of a request (or of a Worker event such as a cron
|
|
61
|
+
* trigger) published to getPlatform() / getCloudflareContext(). The generated
|
|
62
|
+
* Cloudflare Worker wraps the exports of src/cloudflare.ts with it.
|
|
63
|
+
*/
|
|
64
|
+
export function runWithPlatform(target, ctx, fn) {
|
|
65
|
+
const platform = {
|
|
66
|
+
target,
|
|
67
|
+
env: ctx.env && typeof ctx.env === "object" ? ctx.env : {},
|
|
68
|
+
ctx: {
|
|
69
|
+
waitUntil: (work) => {
|
|
70
|
+
if (ctx.waitUntil)
|
|
71
|
+
ctx.waitUntil(work);
|
|
72
|
+
else
|
|
73
|
+
void Promise.resolve(work).catch(() => { });
|
|
74
|
+
},
|
|
75
|
+
passThroughOnException: ctx.passThroughOnException ? () => ctx.passThroughOnException() : undefined,
|
|
76
|
+
},
|
|
77
|
+
cf: ctx.cf,
|
|
78
|
+
};
|
|
79
|
+
return globalStore("krate.platform.store").run(platform, fn);
|
|
80
|
+
}
|
|
38
81
|
function safeDecode(p) {
|
|
39
82
|
try {
|
|
40
83
|
return decodeURIComponent(p);
|
|
@@ -123,7 +166,7 @@ function requestCookiesOf(headers) {
|
|
|
123
166
|
}
|
|
124
167
|
return jar;
|
|
125
168
|
}
|
|
126
|
-
function attachCookies(request) {
|
|
169
|
+
function attachCookies(request, basePath = "") {
|
|
127
170
|
try {
|
|
128
171
|
const jar = requestCookiesOf(request.headers);
|
|
129
172
|
Object.defineProperty(request, "cookies", {
|
|
@@ -134,12 +177,20 @@ function attachCookies(request) {
|
|
|
134
177
|
},
|
|
135
178
|
enumerable: false,
|
|
136
179
|
});
|
|
180
|
+
Object.defineProperty(request, "nextUrl", { value: makeNextUrl(request.url, basePath), enumerable: false });
|
|
137
181
|
}
|
|
138
182
|
catch {
|
|
139
183
|
// frozen request objects keep working without the cookies accessor
|
|
140
184
|
}
|
|
141
185
|
return request;
|
|
142
186
|
}
|
|
187
|
+
/** A URL carrying Next's NextURL extras: basePath (pathname never includes it) and clone(). */
|
|
188
|
+
function makeNextUrl(href, basePath) {
|
|
189
|
+
const u = new URL(href);
|
|
190
|
+
Object.defineProperty(u, "basePath", { value: basePath, enumerable: false });
|
|
191
|
+
Object.defineProperty(u, "clone", { value: () => makeNextUrl(u.href, basePath), enumerable: false });
|
|
192
|
+
return u;
|
|
193
|
+
}
|
|
143
194
|
const sleepMicrotask = () => Promise.resolve();
|
|
144
195
|
const PLATFORMS = {
|
|
145
196
|
node: { forwardedHostProto: false, clientIP: [] },
|
|
@@ -176,6 +227,56 @@ function resolveFlashSecret(option, target) {
|
|
|
176
227
|
hex += b.toString(16).padStart(2, "0");
|
|
177
228
|
return hex;
|
|
178
229
|
}
|
|
230
|
+
function decodeInlineValue(v) {
|
|
231
|
+
if (Array.isArray(v))
|
|
232
|
+
return v.map(decodeInlineValue);
|
|
233
|
+
if (v && typeof v === "object") {
|
|
234
|
+
const o = v;
|
|
235
|
+
if (typeof o.$ === "string") {
|
|
236
|
+
if (o.$ === "u")
|
|
237
|
+
return undefined;
|
|
238
|
+
if (o.$ === "n")
|
|
239
|
+
return BigInt(o.v);
|
|
240
|
+
if (o.$ === "d")
|
|
241
|
+
return new Date(o.v);
|
|
242
|
+
if (o.$ === "o") {
|
|
243
|
+
const wrapped = {};
|
|
244
|
+
for (const k of Object.keys(o.v))
|
|
245
|
+
wrapped[k] = decodeInlineValue(o.v[k]);
|
|
246
|
+
return wrapped;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const out = {};
|
|
250
|
+
for (const k of Object.keys(o))
|
|
251
|
+
out[k] = decodeInlineValue(o[k]);
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
return v;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Opens the closure token of an inline server action: AES-256-GCM over the
|
|
258
|
+
* JSON of the captured values, authenticated against the action id, with the
|
|
259
|
+
* key derived from the action secret (the format the server renderer seals).
|
|
260
|
+
*/
|
|
261
|
+
export async function openInlineToken(token, entry, secret) {
|
|
262
|
+
if (typeof token !== "string" || !token.startsWith("k1."))
|
|
263
|
+
throw new Error("missing closure token");
|
|
264
|
+
if (!secret)
|
|
265
|
+
throw new Error("no action encryption key");
|
|
266
|
+
const b64 = token.slice(3).replace(/-/g, "+").replace(/_/g, "/");
|
|
267
|
+
const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
|
|
268
|
+
const raw = Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
269
|
+
if (raw.length < 12 + 16)
|
|
270
|
+
throw new Error("truncated closure token");
|
|
271
|
+
const enc = new TextEncoder();
|
|
272
|
+
const digest = await crypto.subtle.digest("SHA-256", enc.encode("krate-inline-action\0" + secret));
|
|
273
|
+
const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["decrypt"]);
|
|
274
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: enc.encode(entry.id) }, key, raw.subarray(12));
|
|
275
|
+
const values = JSON.parse(new TextDecoder().decode(plain));
|
|
276
|
+
if (!Array.isArray(values) || values.length !== (entry.captures || []).length)
|
|
277
|
+
throw new Error("closure token does not match the action");
|
|
278
|
+
return values.map(decodeInlineValue);
|
|
279
|
+
}
|
|
179
280
|
// Handler factory
|
|
180
281
|
export function createKrateHandler(options) {
|
|
181
282
|
const { data, modules } = options;
|
|
@@ -193,6 +294,10 @@ export function createKrateHandler(options) {
|
|
|
193
294
|
const staticOnly = new Set(data.staticOnlyRoutes.map(normalizeRoutePattern));
|
|
194
295
|
const sha256Hex = options.sha256Hex || portableSha256Hex;
|
|
195
296
|
const flashSecret = resolveFlashSecret(options.flashSecret, target);
|
|
297
|
+
// Inline-action values are sealed with KRATE_ACTION_SECRET; the key is never part of the bundle.
|
|
298
|
+
// A deployed handler never falls back to the build's local key file.
|
|
299
|
+
globalThis[Symbol.for("krate.action.deployed")] = true;
|
|
300
|
+
const actionSecret = globalThis.process?.env?.KRATE_ACTION_SECRET || "";
|
|
196
301
|
const segEntries = data.segments || [];
|
|
197
302
|
const segPages = data.segmentPages || {};
|
|
198
303
|
const segDirByRoute = new Map();
|
|
@@ -243,7 +348,7 @@ export function createKrateHandler(options) {
|
|
|
243
348
|
let sharedAdapter = null;
|
|
244
349
|
const instanceId = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
245
350
|
// Pages: most specific route first, like SSRServer.FindPageForRoute.
|
|
246
|
-
const pagesBySpecificity =
|
|
351
|
+
const pagesBySpecificity = data.pages.filter((p) => !p.segment).sort((a, b) => compareRouteSpecificity(a.route, b.route));
|
|
247
352
|
const manifest = { pages: data.pages, regions: data.regions };
|
|
248
353
|
const core = createSSRCore({
|
|
249
354
|
manifest,
|
|
@@ -266,7 +371,7 @@ export function createKrateHandler(options) {
|
|
|
266
371
|
ppr: cfg.ssr.ppr,
|
|
267
372
|
pprRevalidate: cfg.ssr.pprRevalidate,
|
|
268
373
|
background: (p) => {
|
|
269
|
-
if (latestWaitUntil)
|
|
374
|
+
if (!platformWaitUntil(p) && latestWaitUntil)
|
|
270
375
|
latestWaitUntil(p);
|
|
271
376
|
},
|
|
272
377
|
});
|
|
@@ -351,7 +456,7 @@ export function createKrateHandler(options) {
|
|
|
351
456
|
return null;
|
|
352
457
|
let result;
|
|
353
458
|
try {
|
|
354
|
-
const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }));
|
|
459
|
+
const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }), basePath);
|
|
355
460
|
result = await handler(request);
|
|
356
461
|
}
|
|
357
462
|
catch (e) {
|
|
@@ -533,7 +638,35 @@ export function createKrateHandler(options) {
|
|
|
533
638
|
return staticLayer.isAsset(p);
|
|
534
639
|
return staticLayer.exists(p);
|
|
535
640
|
}
|
|
641
|
+
/** trailingSlash: "always" (default) sends /x to /x/, "never" sends /x/ to /x, "ignore" serves both. */
|
|
642
|
+
const slashMode = cfg.trailingSlash || "always";
|
|
643
|
+
/** The /404 and /404.html URLs of the not-found page itself answer 404, never the file or a redirect to it. */
|
|
644
|
+
function notFoundPageURL(p) {
|
|
645
|
+
return p === "/404" || p === "/404/" || p === "/404.html";
|
|
646
|
+
}
|
|
647
|
+
async function answerNotFoundPageURL(rs) {
|
|
648
|
+
const page = errorPage(rs.path, 404);
|
|
649
|
+
if (page)
|
|
650
|
+
return custom404(rs, page);
|
|
651
|
+
return notFoundText(rs, true);
|
|
652
|
+
}
|
|
653
|
+
/** trailingSlash "never": a page URL ending in a slash redirects to the slashless URL. */
|
|
654
|
+
function redirectToSlashless(rs) {
|
|
655
|
+
const p = rs.path;
|
|
656
|
+
if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || notFoundPageURL(p))
|
|
657
|
+
return null;
|
|
658
|
+
if (rs.method !== "GET" && rs.method !== "HEAD")
|
|
659
|
+
return null;
|
|
660
|
+
const trimmed = p.replace(/\/+$/, "");
|
|
661
|
+
if (trimmed === "" || isFileLikePath(trimmed) || trimmed === "/api" || trimmed.startsWith("/api/") || trimmed.startsWith("/__krate"))
|
|
662
|
+
return null;
|
|
663
|
+
// "../" keeps a segment such as "ftp:3232235777" from parsing as an absolute URL.
|
|
664
|
+
rs.res.set("Location", "../" + baseName(trimmed) + (rs.search || ""));
|
|
665
|
+
return finish(rs, 301, null);
|
|
666
|
+
}
|
|
536
667
|
function redirectToCanonicalSlash(rs) {
|
|
668
|
+
if (slashMode !== "always")
|
|
669
|
+
return null;
|
|
537
670
|
const p = rs.path;
|
|
538
671
|
if (p === "" || p.endsWith("/") || isFileLikePath(p))
|
|
539
672
|
return null;
|
|
@@ -547,7 +680,13 @@ export function createKrateHandler(options) {
|
|
|
547
680
|
return finish(rs, 301, null);
|
|
548
681
|
}
|
|
549
682
|
/** Answers 404 with a not-found page; segment pages are never cached. */
|
|
550
|
-
function custom404(rs, page, status = 404) {
|
|
683
|
+
async function custom404(rs, page, status = 404) {
|
|
684
|
+
if (page.match && page.match.route) {
|
|
685
|
+
// A page that renders per request: the baked file is only its shell.
|
|
686
|
+
const rendered = await renderSegmentPage404(rs, page.match, status);
|
|
687
|
+
if (rendered)
|
|
688
|
+
return rendered;
|
|
689
|
+
}
|
|
551
690
|
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
552
691
|
rs.res.delete("Cache-Control");
|
|
553
692
|
rs.res.delete("Etag");
|
|
@@ -556,7 +695,7 @@ export function createKrateHandler(options) {
|
|
|
556
695
|
return finish(rs, status, page.match ? renderSegmentPage(page.html, page.match) : page.html);
|
|
557
696
|
}
|
|
558
697
|
/** The 403 or 401 response of a request whose render called forbidden() or unauthorized(). */
|
|
559
|
-
function accessDenied(rs, status, route) {
|
|
698
|
+
async function accessDenied(rs, status, route) {
|
|
560
699
|
rs.res.delete("X-Krate-Cache");
|
|
561
700
|
const page = errorPage(rs.path, status, route);
|
|
562
701
|
if (page)
|
|
@@ -569,6 +708,8 @@ export function createKrateHandler(options) {
|
|
|
569
708
|
const p = rs.path;
|
|
570
709
|
if (isInternalOutputPath(p))
|
|
571
710
|
return notFoundText(rs);
|
|
711
|
+
if (notFoundPageURL(p))
|
|
712
|
+
return answerNotFoundPageURL(rs);
|
|
572
713
|
if (p.endsWith(".map"))
|
|
573
714
|
rs.res.set("Content-Type", "application/json; charset=utf-8");
|
|
574
715
|
rs.res.set("Cache-Control", staticCacheControl(p, hashed));
|
|
@@ -590,12 +731,24 @@ export function createKrateHandler(options) {
|
|
|
590
731
|
}
|
|
591
732
|
}
|
|
592
733
|
}
|
|
593
|
-
const wantsHTML = isHTMLDocRequest(p) || (rs.headers.get("accept") || "").includes("text/html");
|
|
734
|
+
const wantsHTML = isHTMLDocRequest(p) || extName(p) === "" || (rs.headers.get("accept") || "").includes("text/html");
|
|
594
735
|
// Conditional headers dropped by an outer layer (flash notices) must not reach the file server.
|
|
595
736
|
const sreq = rs.headers === rs.request.headers ? rs.request : new Request(rs.request.url, { method: rs.request.method, headers: rs.headers });
|
|
596
|
-
|
|
737
|
+
let served = staticLayer ? await staticLayer.serve(sreq, p) : null;
|
|
738
|
+
if (staticLayer && served && slashMode !== "always" && !p.endsWith("/") && [301, 302, 307, 308].includes(served.status)) {
|
|
739
|
+
// A layer answers a folder URL with a redirect to its slash form; the other modes serve the index in place.
|
|
740
|
+
const inPlace = await staticLayer.serve(sreq, p + "/");
|
|
741
|
+
if (inPlace && inPlace.status !== 404)
|
|
742
|
+
served = inPlace;
|
|
743
|
+
}
|
|
597
744
|
if (served && served.status !== 404)
|
|
598
745
|
return mergeStaticResponse(rs, served);
|
|
746
|
+
// An unknown URL follows the same slash rule as a page, then answers 404 at its canonical form.
|
|
747
|
+
if (p !== "/api" && !p.startsWith("/api/") && !p.startsWith("/__krate") && !p.split("/").some((seg) => seg.startsWith("."))) {
|
|
748
|
+
const slash = redirectToCanonicalSlash(rs);
|
|
749
|
+
if (slash)
|
|
750
|
+
return slash;
|
|
751
|
+
}
|
|
599
752
|
const page404 = wantsHTML ? errorPage(p, 404, { closed: closedPattern }) : null;
|
|
600
753
|
if (page404)
|
|
601
754
|
return custom404(rs, page404);
|
|
@@ -628,6 +781,8 @@ export function createKrateHandler(options) {
|
|
|
628
781
|
const denied = pageMethodAllowed(rs);
|
|
629
782
|
if (denied)
|
|
630
783
|
return denied;
|
|
784
|
+
if (notFoundPageURL(rs.path))
|
|
785
|
+
return answerNotFoundPageURL(rs);
|
|
631
786
|
if (data.pages.length === 0)
|
|
632
787
|
return staticHandler(rs);
|
|
633
788
|
let route = requestRoute(rs.path);
|
|
@@ -667,6 +822,19 @@ export function createKrateHandler(options) {
|
|
|
667
822
|
return finish(rs, 200, baked);
|
|
668
823
|
return staticHandler(rs);
|
|
669
824
|
}
|
|
825
|
+
/** Renders a segment page that renders per request, with the status of its role. Null: the baked shell answers. */
|
|
826
|
+
async function renderSegmentPage404(rs, m, status) {
|
|
827
|
+
const route = m.route || "";
|
|
828
|
+
const page = data.pages.find((p) => p.route === route);
|
|
829
|
+
const shell = loadShell(route);
|
|
830
|
+
if (!page || !shell || !shell.ok)
|
|
831
|
+
return null;
|
|
832
|
+
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
833
|
+
rs.res.set("Cache-Control", "no-store");
|
|
834
|
+
rs.res.delete("Etag");
|
|
835
|
+
rs.res.delete("Last-Modified");
|
|
836
|
+
return servePageRegions(rs, shell, page, route, m.params || {}, queryOf(rs), headerMap(rs), false, 0, false, status);
|
|
837
|
+
}
|
|
670
838
|
/** Renders the regions of a shell like /__krate/regions does and returns one frame per region. */
|
|
671
839
|
function startRegionRenders(page, route, shell, renderReq) {
|
|
672
840
|
const list = shell.all.map((b) => ({
|
|
@@ -692,9 +860,10 @@ export function createKrateHandler(options) {
|
|
|
692
860
|
}
|
|
693
861
|
});
|
|
694
862
|
}
|
|
695
|
-
async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder) {
|
|
863
|
+
async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder, segmentStatus = 0) {
|
|
696
864
|
let shell = shellInfo.shell;
|
|
697
|
-
|
|
865
|
+
// A segment page renders for the URL that missed, not for its own route.
|
|
866
|
+
const renderReq = { route, url: segmentStatus ? rs.path : route, method: "GET", headers, params, query };
|
|
698
867
|
const pending = startRegionRenders(page, route, shellInfo, renderReq);
|
|
699
868
|
if (outOfOrder && !isISR && canStreamOutOfOrder(shellInfo.all) && (!page.serverComponents || allSuspense(shellInfo.all))) {
|
|
700
869
|
return streamSiblingRegions(rs, route, shell, shellInfo, pending);
|
|
@@ -761,6 +930,12 @@ export function createKrateHandler(options) {
|
|
|
761
930
|
}
|
|
762
931
|
}
|
|
763
932
|
}
|
|
933
|
+
// A segment page that failed, or asked for another answer, leaves the response to its baked shell.
|
|
934
|
+
if (segmentStatus && (renderErr || fatalErr || notFound || denied || redirect)) {
|
|
935
|
+
if (renderErr)
|
|
936
|
+
console.error(`[krate] Segment page render error (${route}): ${renderErr}`);
|
|
937
|
+
return null;
|
|
938
|
+
}
|
|
764
939
|
// A segment error page makes any failed render answer with that page
|
|
765
940
|
// instead of the baked body (build/serve.go failOnRenderErr).
|
|
766
941
|
const routeRef = { segDir: page.segDir !== undefined ? page.segDir : "" };
|
|
@@ -836,7 +1011,7 @@ export function createKrateHandler(options) {
|
|
|
836
1011
|
}
|
|
837
1012
|
html = mergeHead(html, title, head);
|
|
838
1013
|
}
|
|
839
|
-
return finish(rs, 200, html);
|
|
1014
|
+
return finish(rs, segmentStatus || 200, html);
|
|
840
1015
|
}
|
|
841
1016
|
// A <Head> inside a streamed Suspense region renders after the head of the
|
|
842
1017
|
// response has been sent. It is applied by the region's script instead, which
|
|
@@ -1050,6 +1225,8 @@ export function createKrateHandler(options) {
|
|
|
1050
1225
|
}
|
|
1051
1226
|
if (status === 413)
|
|
1052
1227
|
return finish(rs, 413, '{"error":"Request Entity Too Large"}');
|
|
1228
|
+
if (status === 504)
|
|
1229
|
+
return finish(rs, 504, '{"error":"Gateway Timeout"}');
|
|
1053
1230
|
return finish(rs, status < 400 ? 500 : status, '{"error":"Internal Server Error"}');
|
|
1054
1231
|
}
|
|
1055
1232
|
function allowList(mod) {
|
|
@@ -1281,16 +1458,58 @@ export function createKrateHandler(options) {
|
|
|
1281
1458
|
console.error(`[krate] API route ${file} uses the legacy (req, res) handler, which the portable server does not support; export named handlers (GET, POST, ...) that take a Request and return a Response.`);
|
|
1282
1459
|
return apiFailure(rs, 500);
|
|
1283
1460
|
}
|
|
1461
|
+
const budgetSec = (data.apiMaxDuration && data.apiMaxDuration[file]) || 0;
|
|
1462
|
+
const abort = budgetSec ? new AbortController() : undefined;
|
|
1463
|
+
let timer;
|
|
1284
1464
|
try {
|
|
1465
|
+
let signal = rs.request.signal;
|
|
1466
|
+
if (abort) {
|
|
1467
|
+
const upstream = rs.request.signal;
|
|
1468
|
+
if (upstream) {
|
|
1469
|
+
if (upstream.aborted)
|
|
1470
|
+
abort.abort(upstream.reason);
|
|
1471
|
+
else
|
|
1472
|
+
upstream.addEventListener("abort", () => abort.abort(upstream.reason), { once: true });
|
|
1473
|
+
}
|
|
1474
|
+
signal = abort.signal;
|
|
1475
|
+
}
|
|
1285
1476
|
const request = attachCookies(new Request(fullURL(rs), {
|
|
1286
1477
|
method: rs.method,
|
|
1287
1478
|
headers: new Headers(rs.request.headers),
|
|
1288
1479
|
body: body && body.byteLength > 0 ? body : undefined,
|
|
1289
|
-
signal
|
|
1290
|
-
}));
|
|
1480
|
+
signal,
|
|
1481
|
+
}), basePath);
|
|
1291
1482
|
const scope = { kind: "api", paths: [], tags: [] };
|
|
1292
|
-
const
|
|
1293
|
-
|
|
1483
|
+
const work = async () => {
|
|
1484
|
+
const res = await revalidateStore.run(scope, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) })));
|
|
1485
|
+
await flushRevalidate(scope);
|
|
1486
|
+
return res;
|
|
1487
|
+
};
|
|
1488
|
+
let out;
|
|
1489
|
+
if (abort) {
|
|
1490
|
+
const deadline = new Promise((_, reject) => {
|
|
1491
|
+
timer = setTimeout(() => {
|
|
1492
|
+
const err = new Error(`API route exceeded its maxDuration of ${budgetSec}s`);
|
|
1493
|
+
err.krateTimeout = true;
|
|
1494
|
+
reject(err);
|
|
1495
|
+
abort.abort(err);
|
|
1496
|
+
}, budgetSec * 1000);
|
|
1497
|
+
});
|
|
1498
|
+
out = await Promise.race([work(), deadline]);
|
|
1499
|
+
}
|
|
1500
|
+
else {
|
|
1501
|
+
out = await work();
|
|
1502
|
+
}
|
|
1503
|
+
if (scope.after && scope.after.length > 0) {
|
|
1504
|
+
// after() tasks start once this handler has returned the response.
|
|
1505
|
+
const later = new Promise((resolve) => setTimeout(resolve, 0)).then(async () => {
|
|
1506
|
+
await revalidateStore.run(scope, () => runAfterTasks(scope));
|
|
1507
|
+
await flushRevalidate(scope).catch((e) => console.error(`[krate] revalidation after() failed: ${e}`));
|
|
1508
|
+
});
|
|
1509
|
+
const keepAlive = rs.ctx.waitUntil ? rs.ctx.waitUntil.bind(rs.ctx) : latestWaitUntil;
|
|
1510
|
+
if (keepAlive)
|
|
1511
|
+
keepAlive(later);
|
|
1512
|
+
}
|
|
1294
1513
|
writeHeaderPairs(rs.res, headerPairs(out.headers));
|
|
1295
1514
|
const status = out.status < 100 || out.status > 999 ? 502 : out.status;
|
|
1296
1515
|
if (headOnly || rs.method === "HEAD" || !out.body || NO_BODY_STATUS.has(status)) {
|
|
@@ -1301,6 +1520,10 @@ export function createKrateHandler(options) {
|
|
|
1301
1520
|
return new Response(out.body, { status, headers: rs.res });
|
|
1302
1521
|
}
|
|
1303
1522
|
catch (err) {
|
|
1523
|
+
if (err && err.krateTimeout) {
|
|
1524
|
+
console.error(`[krate] ${err.message}: ${rs.method} ${rs.path}`);
|
|
1525
|
+
return apiFailure(rs, 504);
|
|
1526
|
+
}
|
|
1304
1527
|
// notFound(), forbidden() and unauthorized() end the request with that status.
|
|
1305
1528
|
const fallback = httpFallbackStatus(err);
|
|
1306
1529
|
if (fallback === 403 || fallback === 401)
|
|
@@ -1313,6 +1536,10 @@ export function createKrateHandler(options) {
|
|
|
1313
1536
|
console.error(`[krate] API error (${rs.method} ${rs.path}): ${(err && err.stack) || err}`);
|
|
1314
1537
|
return apiFailure(rs, 500);
|
|
1315
1538
|
}
|
|
1539
|
+
finally {
|
|
1540
|
+
if (timer)
|
|
1541
|
+
clearTimeout(timer);
|
|
1542
|
+
}
|
|
1316
1543
|
}
|
|
1317
1544
|
// Server actions
|
|
1318
1545
|
const actionById = new Map(data.actions.map((a) => [a.id, a]));
|
|
@@ -1572,6 +1799,23 @@ export function createKrateHandler(options) {
|
|
|
1572
1799
|
catch {
|
|
1573
1800
|
return withHeaders(rs, actionFail(400, "Invalid server action request body"));
|
|
1574
1801
|
}
|
|
1802
|
+
if (entry.inline && entry.captures && entry.captures.length > 0) {
|
|
1803
|
+
// A hoisted inline action: its closed-over values arrive sealed in a token
|
|
1804
|
+
// (the first leading argument, or the URL query for JSON calls).
|
|
1805
|
+
let token = typeof args[0] === "string" && args[0].startsWith("k1.") ? args.shift() : null;
|
|
1806
|
+
if (!token) {
|
|
1807
|
+
const q = leadingActionArgs(query.get("__krate_args"));
|
|
1808
|
+
if (q && typeof q[0] === "string" && q[0].startsWith("k1."))
|
|
1809
|
+
token = q[0];
|
|
1810
|
+
}
|
|
1811
|
+
try {
|
|
1812
|
+
args.unshift(...(await openInlineToken(token, entry, actionSecret)));
|
|
1813
|
+
}
|
|
1814
|
+
catch (e) {
|
|
1815
|
+
console.error(`[krate] rejected closure data for server action ${entry.source || id}: ${e.message}`);
|
|
1816
|
+
return withHeaders(rs, actionFail(400, "Invalid server action request"));
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1575
1819
|
const ctx = makeActionContext(reqHeaders, id, rs.path);
|
|
1576
1820
|
const scope = { kind: "action", paths: [], tags: [] };
|
|
1577
1821
|
let result;
|
|
@@ -1712,6 +1956,10 @@ export function createKrateHandler(options) {
|
|
|
1712
1956
|
const blocked = await runMiddleware(rs2);
|
|
1713
1957
|
if (blocked)
|
|
1714
1958
|
return blocked;
|
|
1959
|
+
// Checked on the requested URL, before a rewrite changes the internal path.
|
|
1960
|
+
const slashless = redirectToSlashless(rs2);
|
|
1961
|
+
if (slashless)
|
|
1962
|
+
return slashless;
|
|
1715
1963
|
return redirectRewriteHandler(rs2);
|
|
1716
1964
|
});
|
|
1717
1965
|
}
|
|
@@ -1744,6 +1992,16 @@ export function createKrateHandler(options) {
|
|
|
1744
1992
|
return blocked;
|
|
1745
1993
|
return actionHandler(rs);
|
|
1746
1994
|
}
|
|
1995
|
+
if (data.metaRoutes && (rs.method === "GET" || rs.method === "HEAD")) {
|
|
1996
|
+
const key = matchMetaRoute(data.metaRoutes, p);
|
|
1997
|
+
if (key) {
|
|
1998
|
+
const blocked = await runMiddleware(rs);
|
|
1999
|
+
if (blocked)
|
|
2000
|
+
return blocked;
|
|
2001
|
+
rs.path = "/api/" + key;
|
|
2002
|
+
return apiHandler(rs);
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
1747
2005
|
return pageChain(rs);
|
|
1748
2006
|
}
|
|
1749
2007
|
function applySecurityAndHeaders(rs) {
|
|
@@ -1801,7 +2059,11 @@ export function createKrateHandler(options) {
|
|
|
1801
2059
|
return finish(rs, 204, null);
|
|
1802
2060
|
return null;
|
|
1803
2061
|
}
|
|
1804
|
-
return
|
|
2062
|
+
return function handle(request, ctx = {}) {
|
|
2063
|
+
// Every page, API route, action and middleware of the request sees the same platform.
|
|
2064
|
+
return runWithPlatform(target, ctx, () => handleRequest(request, ctx));
|
|
2065
|
+
};
|
|
2066
|
+
async function handleRequest(request, ctx) {
|
|
1805
2067
|
if (ctx.waitUntil)
|
|
1806
2068
|
latestWaitUntil = ctx.waitUntil.bind(ctx);
|
|
1807
2069
|
request = sanitizeForwarded(request);
|
|
@@ -1861,6 +2123,6 @@ export function createKrateHandler(options) {
|
|
|
1861
2123
|
}
|
|
1862
2124
|
return httpError(rs, "Internal Server Error", 500);
|
|
1863
2125
|
}
|
|
1864
|
-
}
|
|
2126
|
+
}
|
|
1865
2127
|
}
|
|
1866
2128
|
export { isDynamicPattern };
|