@krate/runtime 0.5.0-rc.3 → 0.5.0-rc.5
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/cache-scope.d.ts +4 -0
- package/dist/cache-scope.js +8 -0
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-hydrate.js +1 -1
- package/dist/krate-runtime.js +1 -1
- package/dist/react-server.d.ts +63 -0
- package/dist/react-server.js +125 -0
- package/dist/router.js +9 -0
- package/dist/server-handler.js +22 -5
- package/dist/server-handler.test.js +92 -1
- package/dist/server.d.ts +40 -0
- package/dist/server.js +55 -0
- package/dist/server.test.js +12 -1
- package/dist/slot.d.ts +12 -0
- package/dist/slot.js +23 -0
- package/dist/slot.test.d.ts +1 -0
- package/dist/slot.test.js +25 -0
- package/dist/ssr-core.d.ts +2 -0
- package/dist/ssr-core.js +8 -0
- package/package.json +5 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `react` module of a server bundle (an SSR page or server component).
|
|
3
|
+
*
|
|
4
|
+
* The compiler maps `import { ... } from "react"` in a server bundle onto this
|
|
5
|
+
* module. It exports the part of React's API that has a meaning while a server
|
|
6
|
+
* renders: effects are no-ops (React's server renderer never runs them),
|
|
7
|
+
* `cache` memoizes per request, and the transition/optimistic/action hooks
|
|
8
|
+
* return their initial state. Names that would behave differently from React
|
|
9
|
+
* here (useState, useRef, createContext, ...) are not exported, so importing
|
|
10
|
+
* them fails the build instead of silently misbehaving.
|
|
11
|
+
*/
|
|
12
|
+
import { Suspense, Fragment, lazy, createSignal, createEffect, createMemo, onCleanup, onMount } from './server.js';
|
|
13
|
+
export { Suspense, Fragment, lazy, createSignal, createEffect, createMemo, onCleanup, onMount };
|
|
14
|
+
type AnyFn = (...args: any[]) => any;
|
|
15
|
+
/** Effects never run while a server renders. */
|
|
16
|
+
export declare function useEffect(_effect: () => unknown, _deps?: readonly unknown[] | null): void;
|
|
17
|
+
export declare function useLayoutEffect(_effect: () => unknown, _deps?: readonly unknown[] | null): void;
|
|
18
|
+
export declare function useInsertionEffect(_effect: () => unknown, _deps?: readonly unknown[] | null): void;
|
|
19
|
+
export declare function createElement(type: any, props?: Record<string, any> | null, ...children: unknown[]): unknown;
|
|
20
|
+
export declare function forwardRef<P = any>(render: (props: P, ref: unknown) => unknown): (props: P) => unknown;
|
|
21
|
+
export declare function memo<C>(component: C, _compare?: unknown): C;
|
|
22
|
+
export declare function startTransition(fn: () => unknown): void;
|
|
23
|
+
export declare function useTransition(): [boolean, (fn: () => unknown) => void];
|
|
24
|
+
export declare function useOptimistic<T>(passthrough: T, _reducer?: unknown): [T, (action: unknown) => void];
|
|
25
|
+
export declare function useActionState<S>(_action: unknown, initialState: S, _permalink?: string): [S, () => void, boolean];
|
|
26
|
+
/** Ids are unique within the process; server-rendered output is never hydrated by React. */
|
|
27
|
+
export declare function useId(): string;
|
|
28
|
+
/**
|
|
29
|
+
* use(promise) cannot suspend a synchronous server render. A promise that
|
|
30
|
+
* already settled through React's own bookkeeping is read; anything else
|
|
31
|
+
* points the author at an async component.
|
|
32
|
+
*/
|
|
33
|
+
export declare function use<T>(usable: PromiseLike<T> | {
|
|
34
|
+
_currentValue?: T;
|
|
35
|
+
defaultValue?: T;
|
|
36
|
+
}): T;
|
|
37
|
+
/**
|
|
38
|
+
* React's cache(): memoizes fn by argument identity for the request being
|
|
39
|
+
* rendered. Results and thrown errors are both remembered, so a promise
|
|
40
|
+
* returned by fn is shared by every caller in the request. Outside a render
|
|
41
|
+
* (an API route, module scope) there is no request to scope the memo to, so
|
|
42
|
+
* fn runs on every call, as in React.
|
|
43
|
+
*/
|
|
44
|
+
export declare function cache<F extends AnyFn>(fn: F): F;
|
|
45
|
+
declare const _default: {
|
|
46
|
+
Suspense: typeof Suspense;
|
|
47
|
+
Fragment: typeof Fragment;
|
|
48
|
+
lazy: typeof lazy;
|
|
49
|
+
createElement: typeof createElement;
|
|
50
|
+
forwardRef: typeof forwardRef;
|
|
51
|
+
memo: typeof memo;
|
|
52
|
+
cache: typeof cache;
|
|
53
|
+
use: typeof use;
|
|
54
|
+
useId: typeof useId;
|
|
55
|
+
startTransition: typeof startTransition;
|
|
56
|
+
useTransition: typeof useTransition;
|
|
57
|
+
useOptimistic: typeof useOptimistic;
|
|
58
|
+
useActionState: typeof useActionState;
|
|
59
|
+
useEffect: typeof useEffect;
|
|
60
|
+
useLayoutEffect: typeof useLayoutEffect;
|
|
61
|
+
useInsertionEffect: typeof useInsertionEffect;
|
|
62
|
+
};
|
|
63
|
+
export default _default;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `react` module of a server bundle (an SSR page or server component).
|
|
3
|
+
*
|
|
4
|
+
* The compiler maps `import { ... } from "react"` in a server bundle onto this
|
|
5
|
+
* module. It exports the part of React's API that has a meaning while a server
|
|
6
|
+
* renders: effects are no-ops (React's server renderer never runs them),
|
|
7
|
+
* `cache` memoizes per request, and the transition/optimistic/action hooks
|
|
8
|
+
* return their initial state. Names that would behave differently from React
|
|
9
|
+
* here (useState, useRef, createContext, ...) are not exported, so importing
|
|
10
|
+
* them fails the build instead of silently misbehaving.
|
|
11
|
+
*/
|
|
12
|
+
import { Suspense, Fragment, jsx, lazy, createSignal, createEffect, createMemo, onCleanup, onMount } from './server.js';
|
|
13
|
+
import { currentRenderScope } from './cache-scope.js';
|
|
14
|
+
export { Suspense, Fragment, lazy, createSignal, createEffect, createMemo, onCleanup, onMount };
|
|
15
|
+
/** Effects never run while a server renders. */
|
|
16
|
+
export function useEffect(_effect, _deps) { }
|
|
17
|
+
export function useLayoutEffect(_effect, _deps) { }
|
|
18
|
+
export function useInsertionEffect(_effect, _deps) { }
|
|
19
|
+
export function createElement(type, props, ...children) {
|
|
20
|
+
const p = { ...(props || {}) };
|
|
21
|
+
delete p.key;
|
|
22
|
+
delete p.ref;
|
|
23
|
+
if (children.length === 1)
|
|
24
|
+
p.children = children[0];
|
|
25
|
+
else if (children.length > 1)
|
|
26
|
+
p.children = children;
|
|
27
|
+
return jsx(type, p);
|
|
28
|
+
}
|
|
29
|
+
export function forwardRef(render) {
|
|
30
|
+
return (props) => render(props, null);
|
|
31
|
+
}
|
|
32
|
+
export function memo(component, _compare) {
|
|
33
|
+
return component;
|
|
34
|
+
}
|
|
35
|
+
export function startTransition(fn) {
|
|
36
|
+
fn();
|
|
37
|
+
}
|
|
38
|
+
export function useTransition() {
|
|
39
|
+
return [false, startTransition];
|
|
40
|
+
}
|
|
41
|
+
export function useOptimistic(passthrough, _reducer) {
|
|
42
|
+
return [passthrough, () => { }];
|
|
43
|
+
}
|
|
44
|
+
export function useActionState(_action, initialState, _permalink) {
|
|
45
|
+
return [initialState, () => { }, false];
|
|
46
|
+
}
|
|
47
|
+
let idCounter = 0;
|
|
48
|
+
/** Ids are unique within the process; server-rendered output is never hydrated by React. */
|
|
49
|
+
export function useId() {
|
|
50
|
+
return ':R' + (idCounter++).toString(36) + ':';
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* use(promise) cannot suspend a synchronous server render. A promise that
|
|
54
|
+
* already settled through React's own bookkeeping is read; anything else
|
|
55
|
+
* points the author at an async component.
|
|
56
|
+
*/
|
|
57
|
+
export function use(usable) {
|
|
58
|
+
const u = usable;
|
|
59
|
+
if (u && typeof u.then === 'function') {
|
|
60
|
+
if (u.status === 'fulfilled')
|
|
61
|
+
return u.value;
|
|
62
|
+
if (u.status === 'rejected')
|
|
63
|
+
throw u.reason;
|
|
64
|
+
throw new Error('use(promise) cannot wait for a promise while a Krate server renders. Make the component async and await the promise.');
|
|
65
|
+
}
|
|
66
|
+
if (u && ('_currentValue' in u || 'defaultValue' in u))
|
|
67
|
+
return (u._currentValue ?? u.defaultValue);
|
|
68
|
+
throw new Error('use() received something that is neither a promise nor a context.');
|
|
69
|
+
}
|
|
70
|
+
const perRequest = new WeakMap();
|
|
71
|
+
/**
|
|
72
|
+
* React's cache(): memoizes fn by argument identity for the request being
|
|
73
|
+
* rendered. Results and thrown errors are both remembered, so a promise
|
|
74
|
+
* returned by fn is shared by every caller in the request. Outside a render
|
|
75
|
+
* (an API route, module scope) there is no request to scope the memo to, so
|
|
76
|
+
* fn runs on every call, as in React.
|
|
77
|
+
*/
|
|
78
|
+
export function cache(fn) {
|
|
79
|
+
const wrapped = function (...args) {
|
|
80
|
+
const scope = currentRenderScope();
|
|
81
|
+
if (!scope)
|
|
82
|
+
return fn.apply(this, args);
|
|
83
|
+
let byFn = perRequest.get(scope);
|
|
84
|
+
if (!byFn) {
|
|
85
|
+
byFn = new WeakMap();
|
|
86
|
+
perRequest.set(scope, byFn);
|
|
87
|
+
}
|
|
88
|
+
let node = byFn.get(wrapped);
|
|
89
|
+
if (!node) {
|
|
90
|
+
node = { done: false };
|
|
91
|
+
byFn.set(wrapped, node);
|
|
92
|
+
}
|
|
93
|
+
for (const arg of args) {
|
|
94
|
+
if (!node.next)
|
|
95
|
+
node.next = new Map();
|
|
96
|
+
let child = node.next.get(arg);
|
|
97
|
+
if (!child) {
|
|
98
|
+
child = { done: false };
|
|
99
|
+
node.next.set(arg, child);
|
|
100
|
+
}
|
|
101
|
+
node = child;
|
|
102
|
+
}
|
|
103
|
+
if (node.done) {
|
|
104
|
+
if (node.failed)
|
|
105
|
+
throw node.error;
|
|
106
|
+
return node.value;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
node.value = fn.apply(this, args);
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
node.failed = true;
|
|
113
|
+
node.error = e;
|
|
114
|
+
node.done = true;
|
|
115
|
+
throw e;
|
|
116
|
+
}
|
|
117
|
+
node.done = true;
|
|
118
|
+
return node.value;
|
|
119
|
+
};
|
|
120
|
+
return wrapped;
|
|
121
|
+
}
|
|
122
|
+
export default {
|
|
123
|
+
Suspense, Fragment, lazy, createElement, forwardRef, memo, cache, use, useId, startTransition, useTransition,
|
|
124
|
+
useOptimistic, useActionState, useEffect, useLayoutEffect, useInsertionEffect,
|
|
125
|
+
};
|
package/dist/router.js
CHANGED
|
@@ -455,6 +455,15 @@ function setupSpeculationRules() {
|
|
|
455
455
|
},
|
|
456
456
|
],
|
|
457
457
|
});
|
|
458
|
+
// A CSP sent as a header cannot be read from here: when it blocks the
|
|
459
|
+
// inline script, drop it and leave prefetching to the JS path.
|
|
460
|
+
const onViolation = (e) => {
|
|
461
|
+
if (e && e.blockedURI === 'inline' && /^script-src/.test(String(e.effectiveDirective || e.violatedDirective || ''))) {
|
|
462
|
+
script.remove();
|
|
463
|
+
document.removeEventListener('securitypolicyviolation', onViolation);
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
document.addEventListener('securitypolicyviolation', onViolation);
|
|
458
467
|
document.head.appendChild(script);
|
|
459
468
|
}
|
|
460
469
|
catch {
|
package/dist/server-handler.js
CHANGED
|
@@ -731,7 +731,7 @@ export function createKrateHandler(options) {
|
|
|
731
731
|
}
|
|
732
732
|
}
|
|
733
733
|
}
|
|
734
|
-
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");
|
|
735
735
|
// Conditional headers dropped by an outer layer (flash notices) must not reach the file server.
|
|
736
736
|
const sreq = rs.headers === rs.request.headers ? rs.request : new Request(rs.request.url, { method: rs.request.method, headers: rs.headers });
|
|
737
737
|
let served = staticLayer ? await staticLayer.serve(sreq, p) : null;
|
|
@@ -743,6 +743,12 @@ export function createKrateHandler(options) {
|
|
|
743
743
|
}
|
|
744
744
|
if (served && served.status !== 404)
|
|
745
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
|
+
}
|
|
746
752
|
const page404 = wantsHTML ? errorPage(p, 404, { closed: closedPattern }) : null;
|
|
747
753
|
if (page404)
|
|
748
754
|
return custom404(rs, page404);
|
|
@@ -797,7 +803,8 @@ export function createKrateHandler(options) {
|
|
|
797
803
|
const query = queryOf(rs);
|
|
798
804
|
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
799
805
|
rs.res.set("X-Content-Type-Options", "nosniff");
|
|
800
|
-
|
|
806
|
+
// A Cache-Control that middleware or a headers rule already set wins over the default.
|
|
807
|
+
if (!isISR && !rs.res.has("Cache-Control"))
|
|
801
808
|
rs.res.set("Cache-Control", "no-store");
|
|
802
809
|
let reval = 0;
|
|
803
810
|
if (isISR) {
|
|
@@ -876,6 +883,7 @@ export function createKrateHandler(options) {
|
|
|
876
883
|
let errStack = "";
|
|
877
884
|
let errDigest = "";
|
|
878
885
|
let noStore = false;
|
|
886
|
+
let errorCaught = false;
|
|
879
887
|
for (const frame of await Promise.all(pending)) {
|
|
880
888
|
switch (frame.type) {
|
|
881
889
|
case "region": {
|
|
@@ -889,6 +897,8 @@ export function createKrateHandler(options) {
|
|
|
889
897
|
}
|
|
890
898
|
if (frame.noStore)
|
|
891
899
|
noStore = true;
|
|
900
|
+
if (frame.errorCaught)
|
|
901
|
+
errorCaught = true;
|
|
892
902
|
if (id === "page") {
|
|
893
903
|
isISRFrame = !!frame.cacheStatus;
|
|
894
904
|
cacheStatus = frame.cacheStatus || "";
|
|
@@ -967,12 +977,19 @@ export function createKrateHandler(options) {
|
|
|
967
977
|
}
|
|
968
978
|
if (isISR && isISRFrame && cacheStatus)
|
|
969
979
|
rs.res.set("X-Krate-Cache", cacheStatus.toUpperCase());
|
|
970
|
-
if (
|
|
980
|
+
if (errorCaught) {
|
|
981
|
+
// The fallback is an error response: no CDN may keep it, whatever cache
|
|
982
|
+
// headers the route or middleware set.
|
|
983
|
+
rs.res.set("X-Krate-Error", "render");
|
|
984
|
+
rs.res.delete("X-Krate-Cache");
|
|
985
|
+
rs.res.set("Cache-Control", "no-store");
|
|
986
|
+
}
|
|
987
|
+
else if (isISR) {
|
|
971
988
|
if (noStore || renderErr) {
|
|
972
989
|
rs.res.set("Cache-Control", "private, no-store");
|
|
973
990
|
rs.res.delete("X-Krate-Cache");
|
|
974
991
|
}
|
|
975
|
-
else {
|
|
992
|
+
else if (!rs.res.has("Cache-Control")) {
|
|
976
993
|
const r = revalidate > 0 ? revalidate : 60;
|
|
977
994
|
rs.res.set("Cache-Control", `public, s-maxage=${r}, stale-while-revalidate=${2 * r}`);
|
|
978
995
|
}
|
|
@@ -1005,7 +1022,7 @@ export function createKrateHandler(options) {
|
|
|
1005
1022
|
}
|
|
1006
1023
|
html = mergeHead(html, title, head);
|
|
1007
1024
|
}
|
|
1008
|
-
return finish(rs, segmentStatus || 200, html);
|
|
1025
|
+
return finish(rs, errorCaught ? 500 : segmentStatus || 200, html);
|
|
1009
1026
|
}
|
|
1010
1027
|
// A <Head> inside a streamed Suspense region renders after the head of the
|
|
1011
1028
|
// response has been sent. It is applied by the region's script instead, which
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @vitest-environment node
|
|
2
2
|
import { describe, expect, it, vi } from "vitest";
|
|
3
3
|
import { createKrateHandler, matchMetaRoute } from "./server-handler.js";
|
|
4
|
-
import { jsx } from "./server.js";
|
|
4
|
+
import { jsx, ServerErrorBoundary } from "./server.js";
|
|
5
5
|
const config = {
|
|
6
6
|
basePath: "",
|
|
7
7
|
trustProxy: true,
|
|
@@ -245,3 +245,94 @@ describe("per-request metadata routes", () => {
|
|
|
245
245
|
expect((await handler(new Request("http://localhost/robots.txt", { method: "POST" }))).status).not.toBe(200);
|
|
246
246
|
});
|
|
247
247
|
});
|
|
248
|
+
describe("Cache-Control on request-time pages", () => {
|
|
249
|
+
const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
|
|
250
|
+
const mk = (target) => createKrateHandler({
|
|
251
|
+
target,
|
|
252
|
+
data: data({
|
|
253
|
+
hasMiddleware: true,
|
|
254
|
+
pages: [
|
|
255
|
+
{ route: "/cached", mode: "ssr", bundlePath: "page" },
|
|
256
|
+
{ route: "/plain", mode: "ssr", bundlePath: "page" },
|
|
257
|
+
],
|
|
258
|
+
allPages: [{ route: "/cached", mode: "ssr" }, { route: "/plain", mode: "ssr" }],
|
|
259
|
+
shells: { "/cached": shell, "/plain": shell },
|
|
260
|
+
}),
|
|
261
|
+
modules: {
|
|
262
|
+
pages: { page: { default: () => jsx("main", { children: "ssr" }) } },
|
|
263
|
+
middleware: {
|
|
264
|
+
middleware: (req) => {
|
|
265
|
+
const headers = { "x-middleware-next": "1" };
|
|
266
|
+
if (new URL(req.url).pathname.startsWith("/cached"))
|
|
267
|
+
headers["cache-control"] = "public, s-maxage=60";
|
|
268
|
+
return new Response(null, { headers });
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
it("lets middleware set it and defaults to no-store", async () => {
|
|
274
|
+
for (const target of ["node", "cloudflare", "vercel"]) {
|
|
275
|
+
const h = mk(target);
|
|
276
|
+
const cached = await h(new Request("http://localhost/cached/"));
|
|
277
|
+
expect(cached.headers.get("cache-control"), target).toBe("public, s-maxage=60");
|
|
278
|
+
expect(await cached.text()).toContain("ssr");
|
|
279
|
+
expect((await h(new Request("http://localhost/plain/"))).headers.get("cache-control"), target).toBe("no-store");
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
describe("error boundary under a request-time page", () => {
|
|
284
|
+
const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
|
|
285
|
+
const boom = async () => {
|
|
286
|
+
throw new Error("db down");
|
|
287
|
+
};
|
|
288
|
+
const h = createKrateHandler({
|
|
289
|
+
target: "node",
|
|
290
|
+
data: data({
|
|
291
|
+
hasMiddleware: false,
|
|
292
|
+
pages: [{ route: "/boom", mode: "ssr", bundlePath: "boom" }],
|
|
293
|
+
allPages: [{ route: "/boom", mode: "ssr" }],
|
|
294
|
+
shells: { "/boom": shell },
|
|
295
|
+
}),
|
|
296
|
+
modules: {
|
|
297
|
+
pages: {
|
|
298
|
+
boom: {
|
|
299
|
+
default: () => jsx("div", {
|
|
300
|
+
children: jsx(ServerErrorBoundary, { fallback: (p) => jsx("p", { children: "failed " + p.error.digest }), children: jsx(boom, {}) }),
|
|
301
|
+
}),
|
|
302
|
+
},
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
it("answers 500 with no-store and the fallback in place", async () => {
|
|
307
|
+
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
308
|
+
const r = await h(new Request("http://localhost/boom/"));
|
|
309
|
+
const body = await r.text();
|
|
310
|
+
expect(r.status).toBe(500);
|
|
311
|
+
expect(r.headers.get("cache-control")).toBe("no-store");
|
|
312
|
+
expect(body).toMatch(/<p>failed [0-9a-f]{10}<\/p>/);
|
|
313
|
+
expect(body).not.toContain("db down");
|
|
314
|
+
});
|
|
315
|
+
it("keeps no-store when middleware asked for public caching", async () => {
|
|
316
|
+
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
317
|
+
const cached = createKrateHandler({
|
|
318
|
+
target: "cloudflare",
|
|
319
|
+
data: data({
|
|
320
|
+
hasMiddleware: true,
|
|
321
|
+
pages: [{ route: "/boom", mode: "ssr", bundlePath: "boom" }],
|
|
322
|
+
allPages: [{ route: "/boom", mode: "ssr" }],
|
|
323
|
+
shells: { "/boom": shell },
|
|
324
|
+
}),
|
|
325
|
+
modules: {
|
|
326
|
+
pages: {
|
|
327
|
+
boom: {
|
|
328
|
+
default: () => jsx("div", { children: jsx(ServerErrorBoundary, { fallback: () => jsx("p", { children: "failed" }), children: jsx(boom, {}) }) }),
|
|
329
|
+
},
|
|
330
|
+
},
|
|
331
|
+
middleware: { middleware: () => new Response(null, { headers: { "x-middleware-next": "1", "cache-control": "public, s-maxage=60" } }) },
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
const r = await cached(new Request("http://localhost/boom/"));
|
|
335
|
+
expect(r.status).toBe(500);
|
|
336
|
+
expect(r.headers.get("cache-control")).toBe("no-store");
|
|
337
|
+
});
|
|
338
|
+
});
|
package/dist/server.d.ts
CHANGED
|
@@ -39,6 +39,36 @@ export declare function Fragment(_props: {
|
|
|
39
39
|
}): JSXNode;
|
|
40
40
|
export declare function jsx(type: string | Function, props: Record<string, any>, _key?: string): JSXElement;
|
|
41
41
|
export declare const jsxs: typeof jsx;
|
|
42
|
+
/**
|
|
43
|
+
* ServerErrorBoundary is the request-time form of a segment's error.tsx under
|
|
44
|
+
* an async layout: it renders `children`, and when rendering them throws it
|
|
45
|
+
* renders `<fallback error={{ name, message, digest }} />` in their place.
|
|
46
|
+
* notFound(), forbidden(), unauthorized() and redirect() signals pass through.
|
|
47
|
+
* The visitor sees a generic message and a digest; the real error is logged
|
|
48
|
+
* with the same digest. The render's scope records the catch, so the host
|
|
49
|
+
* answers 500 with no-store instead of a cacheable 200.
|
|
50
|
+
*/
|
|
51
|
+
export declare class ServerErrorBoundary {
|
|
52
|
+
props: {
|
|
53
|
+
fallback: any;
|
|
54
|
+
children?: JSXNode;
|
|
55
|
+
};
|
|
56
|
+
state: {
|
|
57
|
+
error: unknown;
|
|
58
|
+
};
|
|
59
|
+
constructor(props: {
|
|
60
|
+
fallback: any;
|
|
61
|
+
children?: JSXNode;
|
|
62
|
+
});
|
|
63
|
+
static getDerivedStateFromError(error: unknown): {
|
|
64
|
+
error: {
|
|
65
|
+
name: string;
|
|
66
|
+
message: string;
|
|
67
|
+
digest: string;
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
render(): JSXNode;
|
|
71
|
+
}
|
|
42
72
|
export declare function renderToString(node: JSXNode): string;
|
|
43
73
|
/**
|
|
44
74
|
* renderToStringAsync renders a tree that may contain async (server)
|
|
@@ -57,6 +87,16 @@ interface SuspenseProps {
|
|
|
57
87
|
children: JSXNode;
|
|
58
88
|
}
|
|
59
89
|
export declare function Suspense(props: SuspenseProps): JSXNode;
|
|
90
|
+
/**
|
|
91
|
+
* lazy() in a server tree: the loader's module is imported while the page
|
|
92
|
+
* renders and its component renders in place. Nothing is code-split to the
|
|
93
|
+
* browser, so a server-only module can be loaded this way.
|
|
94
|
+
*/
|
|
95
|
+
export declare function lazy<P = Record<string, any>>(loader: () => Promise<{
|
|
96
|
+
default: (props: P) => unknown;
|
|
97
|
+
} | ((props: P) => unknown)>): (props: P & {
|
|
98
|
+
children?: JSXNode;
|
|
99
|
+
}) => Promise<JSXNode>;
|
|
60
100
|
type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null) => string;
|
|
61
101
|
/**
|
|
62
102
|
* clientBoundary wraps an export of a `"use client"` module, or a component
|
package/dist/server.js
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
import { ATTR_ALIASES } from './htmlspec-attributes.js';
|
|
4
4
|
import { withBase } from './base-path.js';
|
|
5
5
|
import { highlight as highlightCode, trimSpace } from './highlight.js';
|
|
6
|
+
import { accessDeniedStatus, isNotFoundSignal, redirectTarget } from './request-context.js';
|
|
7
|
+
import { sha256Hex } from './sha256.js';
|
|
8
|
+
import { markErrorCaught } from './cache-scope.js';
|
|
6
9
|
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
7
10
|
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
8
11
|
export { after } from './after.js';
|
|
@@ -146,6 +149,41 @@ function classFallback(type, instance, error) {
|
|
|
146
149
|
}
|
|
147
150
|
return instance.render();
|
|
148
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* ServerErrorBoundary is the request-time form of a segment's error.tsx under
|
|
154
|
+
* an async layout: it renders `children`, and when rendering them throws it
|
|
155
|
+
* renders `<fallback error={{ name, message, digest }} />` in their place.
|
|
156
|
+
* notFound(), forbidden(), unauthorized() and redirect() signals pass through.
|
|
157
|
+
* The visitor sees a generic message and a digest; the real error is logged
|
|
158
|
+
* with the same digest. The render's scope records the catch, so the host
|
|
159
|
+
* answers 500 with no-store instead of a cacheable 200.
|
|
160
|
+
*/
|
|
161
|
+
export class ServerErrorBoundary {
|
|
162
|
+
constructor(props) {
|
|
163
|
+
this.state = { error: undefined };
|
|
164
|
+
this.props = props;
|
|
165
|
+
}
|
|
166
|
+
static getDerivedStateFromError(error) {
|
|
167
|
+
if (isNotFoundSignal(error) || accessDeniedStatus(error) || redirectTarget(error))
|
|
168
|
+
throw error;
|
|
169
|
+
return { error: describeBoundaryError(error) };
|
|
170
|
+
}
|
|
171
|
+
render() {
|
|
172
|
+
const err = this.state.error;
|
|
173
|
+
if (!err)
|
|
174
|
+
return this.props.children;
|
|
175
|
+
return jsx(this.props.fallback, { error: err });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function describeBoundaryError(error) {
|
|
179
|
+
const e = error;
|
|
180
|
+
const message = (e && e.message) || String(error);
|
|
181
|
+
const stack = (e && typeof e.stack === "string" && e.stack) || "";
|
|
182
|
+
const digest = sha256Hex(message + "\n" + stack).slice(0, 10);
|
|
183
|
+
console.error(`[krate] Error caught by an error boundary (digest ${digest}):`, error);
|
|
184
|
+
markErrorCaught();
|
|
185
|
+
return { name: "Error", message: "Internal Server Error", digest };
|
|
186
|
+
}
|
|
149
187
|
function renderNode(node) {
|
|
150
188
|
if (node == null || node === false)
|
|
151
189
|
return "";
|
|
@@ -378,6 +416,23 @@ export function Suspense(props) {
|
|
|
378
416
|
`<template data-suspense="${id}">${inner}</template>`);
|
|
379
417
|
}
|
|
380
418
|
Suspense.__krateSuspense = true;
|
|
419
|
+
/**
|
|
420
|
+
* lazy() in a server tree: the loader's module is imported while the page
|
|
421
|
+
* renders and its component renders in place. Nothing is code-split to the
|
|
422
|
+
* browser, so a server-only module can be loaded this way.
|
|
423
|
+
*/
|
|
424
|
+
export function lazy(loader) {
|
|
425
|
+
let loaded;
|
|
426
|
+
return async function Lazy(props) {
|
|
427
|
+
loaded ?? (loaded = Promise.resolve(loader()));
|
|
428
|
+
const mod = await loaded;
|
|
429
|
+
const C = typeof mod === "function" ? mod : mod?.default;
|
|
430
|
+
if (typeof C !== "function") {
|
|
431
|
+
throw new Error("lazy(): the loader did not resolve to a component; export it as the module's default or return it from .then()");
|
|
432
|
+
}
|
|
433
|
+
return jsx(C, props);
|
|
434
|
+
};
|
|
435
|
+
}
|
|
381
436
|
function describeValue(v) {
|
|
382
437
|
if (typeof v === "function")
|
|
383
438
|
return "a function";
|
package/dist/server.test.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, it, expect } from 'vitest';
|
|
2
|
-
import { clientBoundary, jsx, renderToString, renderToStringAsync } from './server';
|
|
2
|
+
import { clientBoundary, jsx, lazy, renderToString, renderToStringAsync } from './server';
|
|
3
3
|
describe('renderToString', () => {
|
|
4
4
|
it('renders nested elements and escapes text', () => {
|
|
5
5
|
const node = jsx('div', { class: 'x', children: [jsx('span', { children: 'a & b' })] });
|
|
@@ -78,3 +78,14 @@ describe('clientBoundary', () => {
|
|
|
78
78
|
expect(html).toContain('__krateChildren');
|
|
79
79
|
});
|
|
80
80
|
});
|
|
81
|
+
describe('lazy', () => {
|
|
82
|
+
it('renders the loaded component in place on the server', async () => {
|
|
83
|
+
const Draw = lazy(() => Promise.resolve({ default: (p) => jsx('p', { id: 'd', children: ['n=' + p.n, p.children] }) }));
|
|
84
|
+
const html = await renderToStringAsync(jsx('main', { children: jsx(Draw, { n: 2, children: jsx('b', { children: 'kid' }) }) }));
|
|
85
|
+
expect(html).toBe('<main><p id="d">n=2<b>kid</b></p></main>');
|
|
86
|
+
});
|
|
87
|
+
it('accepts a loader that resolves to the component itself', async () => {
|
|
88
|
+
const Hi = lazy(() => Promise.resolve(() => jsx('i', { children: 'hi' })));
|
|
89
|
+
expect(await renderToStringAsync(jsx(Hi, {}))).toBe('<i>hi</i>');
|
|
90
|
+
});
|
|
91
|
+
});
|
package/dist/slot.d.ts
CHANGED
|
@@ -5,4 +5,16 @@ export declare const Root: typeof KrateSlot;
|
|
|
5
5
|
export declare function Slottable(props: {
|
|
6
6
|
children?: unknown;
|
|
7
7
|
}): unknown;
|
|
8
|
+
type SlotProps = Record<string, unknown> & {
|
|
9
|
+
children?: unknown;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Radix's `createSlot(ownerName)` (react-slot >= 1.2): a Slot that merges its
|
|
13
|
+
* props and `ref` onto its single child. `ownerName` only labels the component.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createSlot(ownerName: string): (props: SlotProps) => Node | null;
|
|
16
|
+
/** Radix's `createSlottable(ownerName)`: a `Slottable` marker for one owner. */
|
|
17
|
+
export declare function createSlottable(ownerName: string): (props: {
|
|
18
|
+
children?: unknown;
|
|
19
|
+
}) => unknown;
|
|
8
20
|
export default Slot;
|
package/dist/slot.js
CHANGED
|
@@ -8,4 +8,27 @@ export const Root = KrateSlot;
|
|
|
8
8
|
export function Slottable(props) {
|
|
9
9
|
return props?.children;
|
|
10
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* Radix's `createSlot(ownerName)` (react-slot >= 1.2): a Slot that merges its
|
|
13
|
+
* props and `ref` onto its single child. `ownerName` only labels the component.
|
|
14
|
+
*/
|
|
15
|
+
export function createSlot(ownerName) {
|
|
16
|
+
const OwnerSlot = (props) => {
|
|
17
|
+
const node = KrateSlot(props);
|
|
18
|
+
const ref = props?.ref;
|
|
19
|
+
if (node && typeof ref === 'function')
|
|
20
|
+
ref(node);
|
|
21
|
+
else if (node && ref && typeof ref === 'object')
|
|
22
|
+
ref.current = node;
|
|
23
|
+
return node;
|
|
24
|
+
};
|
|
25
|
+
OwnerSlot.displayName = ownerName + '.Slot';
|
|
26
|
+
return OwnerSlot;
|
|
27
|
+
}
|
|
28
|
+
/** Radix's `createSlottable(ownerName)`: a `Slottable` marker for one owner. */
|
|
29
|
+
export function createSlottable(ownerName) {
|
|
30
|
+
const OwnerSlottable = (props) => props?.children;
|
|
31
|
+
OwnerSlottable.displayName = ownerName + '.Slottable';
|
|
32
|
+
return OwnerSlottable;
|
|
33
|
+
}
|
|
11
34
|
export default Slot;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createSlot, createSlottable, Slot, Slottable } from './slot.js';
|
|
3
|
+
describe('react-slot shim', () => {
|
|
4
|
+
it('createSlot merges props and ref onto the single child', () => {
|
|
5
|
+
const SlotImpl = createSlot('Dialog');
|
|
6
|
+
const child = document.createElement('a');
|
|
7
|
+
child.setAttribute('class', 'base');
|
|
8
|
+
let refd = null;
|
|
9
|
+
const node = SlotImpl({ className: 'extra', 'data-x': '1', ref: (n) => (refd = n), children: child });
|
|
10
|
+
expect(node).toBe(child);
|
|
11
|
+
expect(child.getAttribute('class')).toBe('base extra');
|
|
12
|
+
expect(child.getAttribute('data-x')).toBe('1');
|
|
13
|
+
expect(refd).toBe(child);
|
|
14
|
+
const objRef = { current: null };
|
|
15
|
+
SlotImpl({ ref: objRef, children: [child] });
|
|
16
|
+
expect(objRef.current).toBe(child);
|
|
17
|
+
expect(SlotImpl.displayName).toBe('Dialog.Slot');
|
|
18
|
+
});
|
|
19
|
+
it('createSlottable returns a marker that renders its children', () => {
|
|
20
|
+
const Marker = createSlottable('Dialog');
|
|
21
|
+
expect(Marker({ children: 'x' })).toBe('x');
|
|
22
|
+
expect(typeof Slot).toBe('function');
|
|
23
|
+
expect(typeof Slottable).toBe('function');
|
|
24
|
+
});
|
|
25
|
+
});
|
package/dist/ssr-core.d.ts
CHANGED
|
@@ -63,6 +63,8 @@ export interface RenderResponse {
|
|
|
63
63
|
digest?: string;
|
|
64
64
|
stack?: string;
|
|
65
65
|
noStore?: boolean;
|
|
66
|
+
/** An error boundary caught a render error; html is its fallback and the answer is a 500. */
|
|
67
|
+
errorCaught?: boolean;
|
|
66
68
|
}
|
|
67
69
|
export declare function variantKey(req: {
|
|
68
70
|
route: string;
|
package/dist/ssr-core.js
CHANGED
|
@@ -449,6 +449,12 @@ export function createSSRCore(opts) {
|
|
|
449
449
|
status: 200,
|
|
450
450
|
noStore: scope.noStore || invalidated,
|
|
451
451
|
};
|
|
452
|
+
if (scope.errorCaught) {
|
|
453
|
+
// An error boundary rendered its fallback: the page is an error
|
|
454
|
+
// response, so it is never cached (scope.noStore keeps it out of ISR).
|
|
455
|
+
response.errorCaught = true;
|
|
456
|
+
response.noStore = true;
|
|
457
|
+
}
|
|
452
458
|
// An uncacheable read (no-store) keeps the render out of the ISR cache, and
|
|
453
459
|
// a revalidation that landed mid-render means the HTML may be stale.
|
|
454
460
|
if (page.mode === "isr" && !scope.noStore && !invalidated) {
|
|
@@ -865,6 +871,8 @@ export function createSSRCore(opts) {
|
|
|
865
871
|
frame.stack = result.stack;
|
|
866
872
|
if (result.noStore)
|
|
867
873
|
frame.noStore = true;
|
|
874
|
+
if (result.errorCaught)
|
|
875
|
+
frame.errorCaught = true;
|
|
868
876
|
if (page.serverComponents && frame.status >= 500)
|
|
869
877
|
frame.fatal = true;
|
|
870
878
|
// The page's <Head> children (title, meta, link, script) render in place;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krate/runtime",
|
|
3
|
-
"version": "0.5.0-rc.
|
|
3
|
+
"version": "0.5.0-rc.5",
|
|
4
4
|
"description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -62,6 +62,10 @@
|
|
|
62
62
|
"types": "./dist/react.d.ts",
|
|
63
63
|
"default": "./dist/react.js"
|
|
64
64
|
},
|
|
65
|
+
"./react-server": {
|
|
66
|
+
"types": "./dist/react-server.d.ts",
|
|
67
|
+
"default": "./dist/react-server.js"
|
|
68
|
+
},
|
|
65
69
|
"./react/jsx-runtime": {
|
|
66
70
|
"types": "./dist/react-jsx-runtime.d.ts",
|
|
67
71
|
"default": "./dist/react-jsx-runtime.js"
|