@krate/runtime 0.5.0-rc.15 → 0.5.0-rc.17
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/NOTICE +10 -0
- package/README.md +92 -1
- package/dist/actions.js +10 -5
- package/dist/cache-scope.d.ts +10 -2
- package/dist/cache-scope.js +26 -4
- package/dist/context.js +3 -0
- package/dist/dev/app.js +6 -2
- package/dist/dev/modal.js +9 -9
- package/dist/dev/panel.js +3 -1
- package/dist/dev/sourcemap.d.ts +5 -0
- package/dist/dev/sourcemap.js +36 -2
- package/dist/dev/util.d.ts +6 -0
- package/dist/dev/util.js +1 -0
- package/dist/dom.d.ts +26 -0
- package/dist/dom.js +78 -5
- package/dist/flight-props.d.ts +8 -0
- package/dist/flight-props.js +44 -0
- package/dist/hints.d.ts +12 -0
- package/dist/hints.js +32 -2
- package/dist/index.d.ts +4 -0
- package/dist/island-swap.js +46 -8
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +14 -14
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +32 -1
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-island-swap.js +1 -1
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +8 -3
- package/dist/memsize.d.ts +14 -0
- package/dist/memsize.js +71 -0
- package/dist/metadata.js +20 -5
- package/dist/middleware-cookies.d.ts +4 -0
- package/dist/middleware-cookies.js +67 -0
- package/dist/navigation-react.js +2 -1
- package/dist/navigation.d.ts +7 -0
- package/dist/navigation.js +26 -1
- package/dist/react-compat.js +9 -0
- package/dist/react.d.ts +1 -1
- package/dist/react.js +5 -0
- package/dist/router.js +55 -9
- package/dist/segmented-lru.d.ts +14 -1
- package/dist/segmented-lru.js +90 -21
- package/dist/server-handler.d.ts +1 -0
- package/dist/server-handler.js +100 -6
- package/dist/server-renderer.js +4 -1
- package/dist/server.d.ts +6 -3
- package/dist/server.js +78 -38
- package/dist/shared-isr.js +2 -1
- package/dist/signal.js +13 -3
- package/dist/slots.js +8 -1
- package/dist/ssr-core.d.ts +10 -2
- package/dist/ssr-core.js +19 -6
- package/package.json +3 -2
package/dist/segmented-lru.js
CHANGED
|
@@ -6,9 +6,13 @@
|
|
|
6
6
|
// flood of one-off keys only churns probation and never reaches the entries
|
|
7
7
|
// that were requested twice.
|
|
8
8
|
export class SegmentedLRU {
|
|
9
|
-
constructor(maxSize) {
|
|
9
|
+
constructor(maxSize, limit) {
|
|
10
10
|
this.probation = new Map();
|
|
11
11
|
this.protectedSeg = new Map();
|
|
12
|
+
this.sizes = new Map();
|
|
13
|
+
this.used = 0;
|
|
14
|
+
if (limit && limit.maxBytes > 0)
|
|
15
|
+
this.limit = limit;
|
|
12
16
|
this.max = Math.max(1, Math.floor(maxSize));
|
|
13
17
|
// At least one probation slot, so a new entry can always be admitted.
|
|
14
18
|
this.protectedMax = Math.min(this.max - 1, Math.max(1, Math.floor(this.max * 0.8)));
|
|
@@ -16,6 +20,10 @@ export class SegmentedLRU {
|
|
|
16
20
|
get size() {
|
|
17
21
|
return this.probation.size + this.protectedSeg.size;
|
|
18
22
|
}
|
|
23
|
+
/** The summed sizes of the entries (0 without a byte limit). */
|
|
24
|
+
get bytes() {
|
|
25
|
+
return this.used;
|
|
26
|
+
}
|
|
19
27
|
has(key) {
|
|
20
28
|
return this.protectedSeg.has(key) || this.probation.has(key);
|
|
21
29
|
}
|
|
@@ -40,43 +48,104 @@ export class SegmentedLRU {
|
|
|
40
48
|
return cold;
|
|
41
49
|
}
|
|
42
50
|
this.protectedSeg.set(key, cold);
|
|
43
|
-
if (this.protectedSeg.size > this.protectedMax)
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
this.
|
|
51
|
+
if (this.protectedSeg.size > this.protectedMax)
|
|
52
|
+
this.demoteColdest();
|
|
53
|
+
if (this.limit) {
|
|
54
|
+
// Protected entries keep at most 80% of the bytes too, so probation
|
|
55
|
+
// always has room and new entries never flush the hot set.
|
|
56
|
+
const cap = this.limit.maxBytes * 0.8;
|
|
57
|
+
let hot = 0;
|
|
58
|
+
for (const k of this.protectedSeg.keys())
|
|
59
|
+
hot += this.sizes.get(k) || 0;
|
|
60
|
+
while (hot > cap && this.protectedSeg.size > 1)
|
|
61
|
+
hot -= this.sizes.get(this.demoteColdest()) || 0;
|
|
49
62
|
}
|
|
50
63
|
return cold;
|
|
51
64
|
}
|
|
65
|
+
// demoteColdest moves the coldest protected entry to probation's newest
|
|
66
|
+
// slot and returns its key.
|
|
67
|
+
demoteColdest() {
|
|
68
|
+
const demoted = this.protectedSeg.keys().next().value;
|
|
69
|
+
const v = this.protectedSeg.get(demoted);
|
|
70
|
+
this.protectedSeg.delete(demoted);
|
|
71
|
+
this.probation.set(demoted, v);
|
|
72
|
+
return demoted;
|
|
73
|
+
}
|
|
52
74
|
/** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
|
|
53
75
|
set(key, value) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
76
|
+
const n = this.limit ? Math.max(0, this.limit.sizeOf(value)) : 0;
|
|
77
|
+
if (this.limit && n > this.limit.maxBytes) {
|
|
78
|
+
// Too large to cache: drop any older copy instead of keeping it stale.
|
|
79
|
+
const old = this.peek(key);
|
|
80
|
+
if (old === undefined)
|
|
81
|
+
return [];
|
|
82
|
+
this.delete(key);
|
|
83
|
+
return [[key, old]];
|
|
58
84
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
85
|
+
const seg = this.protectedSeg.has(key) ? this.protectedSeg : this.probation.has(key) ? this.probation : null;
|
|
86
|
+
if (seg) {
|
|
87
|
+
seg.delete(key);
|
|
88
|
+
seg.set(key, value);
|
|
89
|
+
this.account(key, n);
|
|
90
|
+
return this.fitBytes(key);
|
|
63
91
|
}
|
|
64
92
|
const evicted = [];
|
|
65
|
-
while (this.size >= this.max) {
|
|
66
|
-
|
|
67
|
-
const oldest = seg.keys().next().value;
|
|
68
|
-
evicted.push([oldest, seg.get(oldest)]);
|
|
69
|
-
seg.delete(oldest);
|
|
93
|
+
while (this.size > 0 && (this.size >= this.max || (this.limit && this.used + n > this.limit.maxBytes))) {
|
|
94
|
+
evicted.push(this.evictOldest());
|
|
70
95
|
}
|
|
71
96
|
this.probation.set(key, value);
|
|
97
|
+
this.account(key, n);
|
|
72
98
|
return evicted;
|
|
73
99
|
}
|
|
100
|
+
// evictOldest removes the coldest entry: probation first, then protected.
|
|
101
|
+
evictOldest() {
|
|
102
|
+
const seg = this.probation.size > 0 ? this.probation : this.protectedSeg;
|
|
103
|
+
const oldest = seg.keys().next().value;
|
|
104
|
+
const v = seg.get(oldest);
|
|
105
|
+
seg.delete(oldest);
|
|
106
|
+
this.account(oldest, 0);
|
|
107
|
+
return [oldest, v];
|
|
108
|
+
}
|
|
109
|
+
// fitBytes evicts other entries, coldest first, until the sizes fit the
|
|
110
|
+
// limit again.
|
|
111
|
+
fitBytes(keep) {
|
|
112
|
+
const evicted = [];
|
|
113
|
+
if (!this.limit || this.used <= this.limit.maxBytes)
|
|
114
|
+
return evicted;
|
|
115
|
+
for (const seg of [this.probation, this.protectedSeg]) {
|
|
116
|
+
for (const k of [...seg.keys()]) {
|
|
117
|
+
if (this.used <= this.limit.maxBytes)
|
|
118
|
+
return evicted;
|
|
119
|
+
if (k === keep)
|
|
120
|
+
continue;
|
|
121
|
+
evicted.push([k, seg.get(k)]);
|
|
122
|
+
seg.delete(k);
|
|
123
|
+
this.account(k, 0);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return evicted;
|
|
127
|
+
}
|
|
128
|
+
account(key, n) {
|
|
129
|
+
if (!this.limit)
|
|
130
|
+
return;
|
|
131
|
+
this.used -= this.sizes.get(key) || 0;
|
|
132
|
+
if (n > 0)
|
|
133
|
+
this.sizes.set(key, n);
|
|
134
|
+
else
|
|
135
|
+
this.sizes.delete(key);
|
|
136
|
+
this.used += n;
|
|
137
|
+
}
|
|
74
138
|
delete(key) {
|
|
75
|
-
|
|
139
|
+
const gone = this.protectedSeg.delete(key) || this.probation.delete(key);
|
|
140
|
+
if (gone)
|
|
141
|
+
this.account(key, 0);
|
|
142
|
+
return gone;
|
|
76
143
|
}
|
|
77
144
|
clear() {
|
|
78
145
|
this.probation.clear();
|
|
79
146
|
this.protectedSeg.clear();
|
|
147
|
+
this.sizes.clear();
|
|
148
|
+
this.used = 0;
|
|
80
149
|
}
|
|
81
150
|
keys() {
|
|
82
151
|
return [...this.probation.keys(), ...this.protectedSeg.keys()];
|
package/dist/server-handler.d.ts
CHANGED
package/dist/server-handler.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
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 { cacheByteBudgets } from "./memsize.js";
|
|
14
15
|
import { runAfterTasks } from "./after.js";
|
|
15
16
|
import { platformWaitUntil } from "./platform.js";
|
|
16
17
|
import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
|
|
@@ -18,6 +19,7 @@ import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectF
|
|
|
18
19
|
import { mergeHead } from "./head-tags.js";
|
|
19
20
|
import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, IMMUTABLE_CACHE_CONTROL, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
|
|
20
21
|
import { attachCookies } from "./request-extras.js";
|
|
22
|
+
import { mergeCookieHeader } from "./middleware-cookies.js";
|
|
21
23
|
import { buildDestination, compileMatcher as compileRuleMatcher, mergeRequestQuery } from "./route-source.js";
|
|
22
24
|
import { lookupSegmentPage, newServerError, renderSegmentPage, SEGMENT_KIND_OF_STATUS, } from "./handler-segments.js";
|
|
23
25
|
import { httpFallbackStatus } from "./request-context.js";
|
|
@@ -318,7 +320,7 @@ export function createKrateHandler(options) {
|
|
|
318
320
|
installRenderStore(new AsyncLocalStorage());
|
|
319
321
|
patchFetch();
|
|
320
322
|
// The ISR and data caches: this instance's memory, or the shared cache adapter.
|
|
321
|
-
const memoryIsr = new MemoryIsrStore(cfg.ssr.maxCacheSize > 0 ? cfg.ssr.maxCacheSize : 512);
|
|
323
|
+
const memoryIsr = new MemoryIsrStore(cfg.ssr.maxCacheSize > 0 ? cfg.ssr.maxCacheSize : 512, cacheByteBudgets(cfg.ssr.cacheBytes).pages);
|
|
322
324
|
const sharedCache = options.isrStore
|
|
323
325
|
? { store: options.isrStore, ready: Promise.resolve(null) }
|
|
324
326
|
: isrStoreFor(options.cache ?? cacheSpecFromConfig(cfg.cache), memoryIsr);
|
|
@@ -344,6 +346,7 @@ export function createKrateHandler(options) {
|
|
|
344
346
|
return fn;
|
|
345
347
|
},
|
|
346
348
|
maxCacheSize: cfg.ssr.maxCacheSize,
|
|
349
|
+
cacheBytes: cfg.ssr.cacheBytes,
|
|
347
350
|
timeoutMs: cfg.ssr.timeout > 0 ? cfg.ssr.timeout : 5000,
|
|
348
351
|
ppr: cfg.ssr.ppr,
|
|
349
352
|
pprRevalidate: cfg.ssr.pprRevalidate,
|
|
@@ -413,6 +416,47 @@ export function createKrateHandler(options) {
|
|
|
413
416
|
return false;
|
|
414
417
|
return !!(await staticLayer.exists(p));
|
|
415
418
|
}
|
|
419
|
+
/** Files the build generated: middleware never runs for them, as Next apps exclude _next/static. */
|
|
420
|
+
async function isBuildAsset(p) {
|
|
421
|
+
if (!staticLayer || !(hashed.has(p) || /^\/(?:chunks|workers|_krate)\//.test(p)))
|
|
422
|
+
return false;
|
|
423
|
+
return !!(await staticLayer.exists(p));
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* The URL and path middleware sees. A server action POST shows the page it
|
|
427
|
+
* was posted from, as Next posts actions to the page URL; the action still
|
|
428
|
+
* runs at its own endpoint.
|
|
429
|
+
*/
|
|
430
|
+
function middlewareView(rs) {
|
|
431
|
+
const own = { url: fullURL(rs), path: rs.path };
|
|
432
|
+
if (rs.method !== "POST" || !rs.path.startsWith("/__krate/action/"))
|
|
433
|
+
return own;
|
|
434
|
+
let ret = sanitizeActionReturn(new URLSearchParams(rs.search).get("__krate_return") || "", rs);
|
|
435
|
+
if (!ret)
|
|
436
|
+
ret = sanitizeActionReturn(rs.headers.get("x-krate-return") || "", rs);
|
|
437
|
+
if (!ret)
|
|
438
|
+
ret = sanitizeActionReturn(rs.headers.get("referer") || "", rs);
|
|
439
|
+
if (!ret)
|
|
440
|
+
return own;
|
|
441
|
+
let u;
|
|
442
|
+
try {
|
|
443
|
+
u = new URL(ret, rs.origin);
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
return own;
|
|
447
|
+
}
|
|
448
|
+
let path = u.pathname;
|
|
449
|
+
if (basePath && (path === basePath || path.startsWith(basePath + "/")))
|
|
450
|
+
path = path.slice(basePath.length) || "/";
|
|
451
|
+
let decoded = path;
|
|
452
|
+
try {
|
|
453
|
+
decoded = decodeURIComponent(path);
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
// keep the escaped form
|
|
457
|
+
}
|
|
458
|
+
return { url: rs.origin + path + u.search, path: decoded };
|
|
459
|
+
}
|
|
416
460
|
/** Runs middleware; a Response ends the request, null continues (headers/rewrite already applied). */
|
|
417
461
|
async function runMiddleware(rs) {
|
|
418
462
|
const p = rs.path;
|
|
@@ -434,13 +478,16 @@ export function createKrateHandler(options) {
|
|
|
434
478
|
catch (e) {
|
|
435
479
|
return middlewareFailed(rs, e);
|
|
436
480
|
}
|
|
481
|
+
if (await isBuildAsset(p))
|
|
482
|
+
return null;
|
|
437
483
|
if (!matchers && (await skipsMiddleware(p)))
|
|
438
484
|
return null;
|
|
439
|
-
|
|
485
|
+
const view = middlewareView(rs);
|
|
486
|
+
if (matchers && !matchers.some((re) => re.test(view.path)))
|
|
440
487
|
return null;
|
|
441
488
|
let result;
|
|
442
489
|
try {
|
|
443
|
-
const request = attachCookies(new Request(
|
|
490
|
+
const request = attachCookies(new Request(view.url, { method: rs.method, headers: new Headers(rs.request.headers) }), basePath);
|
|
444
491
|
result = await handler(request);
|
|
445
492
|
}
|
|
446
493
|
catch (e) {
|
|
@@ -453,6 +500,7 @@ export function createKrateHandler(options) {
|
|
|
453
500
|
const hdrs = [];
|
|
454
501
|
let keep = null;
|
|
455
502
|
const vals = new Map();
|
|
503
|
+
const setCookies = [];
|
|
456
504
|
for (const [k, v] of headerPairs(result.headers)) {
|
|
457
505
|
if (k === "x-middleware-next")
|
|
458
506
|
next = true;
|
|
@@ -462,14 +510,20 @@ export function createKrateHandler(options) {
|
|
|
462
510
|
keep = new Set(v.split(",").map((n) => n.trim().toLowerCase()).filter(Boolean));
|
|
463
511
|
else if (k.startsWith("x-middleware-request-"))
|
|
464
512
|
vals.set(k.slice("x-middleware-request-".length), v);
|
|
465
|
-
else
|
|
513
|
+
else if (k === "x-middleware-set-cookie")
|
|
514
|
+
setCookies.push(v);
|
|
515
|
+
// The rest of Next's x-middleware-* protocol never reaches the client.
|
|
516
|
+
else if (!k.startsWith("x-middleware-"))
|
|
466
517
|
hdrs.push([k, v]);
|
|
467
518
|
}
|
|
468
519
|
if (next || rewrite) {
|
|
469
520
|
if (keep)
|
|
470
521
|
overrideRequestHeaders(rs, keep, vals);
|
|
522
|
+
if (setCookies.length > 0)
|
|
523
|
+
mergeMiddlewareCookies(rs, setCookies);
|
|
471
524
|
writeHeaderPairs(rs.res, hdrs);
|
|
472
|
-
|
|
525
|
+
// A server action runs where it was posted, whatever its page rewrites to.
|
|
526
|
+
if (rewrite && !p.startsWith("/__krate/action/"))
|
|
473
527
|
applyRewrite(rs, rewrite);
|
|
474
528
|
return null;
|
|
475
529
|
}
|
|
@@ -497,6 +551,19 @@ export function createKrateHandler(options) {
|
|
|
497
551
|
rs.request = new Request(rs.request, { headers: edit(rs.request.headers) });
|
|
498
552
|
rs.headers = shared ? rs.request.headers : edit(rs.headers);
|
|
499
553
|
}
|
|
554
|
+
/** x-middleware-set-cookie: cookies middleware set join the request cookies, so cookies() sees them. */
|
|
555
|
+
function mergeMiddlewareCookies(rs, lines) {
|
|
556
|
+
const edit = (h) => {
|
|
557
|
+
const out = new Headers(h);
|
|
558
|
+
out.set("cookie", mergeCookieHeader(h.get("cookie") ?? "", lines));
|
|
559
|
+
if (out.get("cookie") === "")
|
|
560
|
+
out.delete("cookie");
|
|
561
|
+
return out;
|
|
562
|
+
};
|
|
563
|
+
const shared = rs.headers === rs.request.headers;
|
|
564
|
+
rs.request = new Request(rs.request, { headers: edit(rs.request.headers) });
|
|
565
|
+
rs.headers = shared ? rs.request.headers : edit(rs.headers);
|
|
566
|
+
}
|
|
500
567
|
function middlewareFailed(rs, err) {
|
|
501
568
|
console.error(`[krate] middleware error: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
|
|
502
569
|
// Fail closed: continuing would turn a broken auth check into an unauthenticated request.
|
|
@@ -1733,6 +1800,28 @@ export function createKrateHandler(options) {
|
|
|
1733
1800
|
return "";
|
|
1734
1801
|
}
|
|
1735
1802
|
}
|
|
1803
|
+
// What Next's redirect() takes: a path or an absolute URL. A URL on the
|
|
1804
|
+
// request's host becomes its path; another origin is followed with a full
|
|
1805
|
+
// navigation, but only when redirect() itself named it (thrown).
|
|
1806
|
+
function actionRedirectTarget(value, host, thrown) {
|
|
1807
|
+
const none = { to: "", external: false };
|
|
1808
|
+
if (typeof value !== "string")
|
|
1809
|
+
return none;
|
|
1810
|
+
const v = value.trim();
|
|
1811
|
+
if (!/^https?:\/\//i.test(v))
|
|
1812
|
+
return { to: safeActionRedirect(v), external: false };
|
|
1813
|
+
let u;
|
|
1814
|
+
try {
|
|
1815
|
+
u = new URL(v);
|
|
1816
|
+
}
|
|
1817
|
+
catch {
|
|
1818
|
+
return none;
|
|
1819
|
+
}
|
|
1820
|
+
const own = String(host || "").split(",")[0].trim().toLowerCase();
|
|
1821
|
+
if (own && u.host.toLowerCase() === own)
|
|
1822
|
+
return { to: safeActionRedirect(u.pathname + u.search + u.hash), external: false };
|
|
1823
|
+
return thrown ? { to: safeExternalRedirect(v), external: true } : none;
|
|
1824
|
+
}
|
|
1736
1825
|
function sanitizeActionReturn(value, rs) {
|
|
1737
1826
|
value = value.trim();
|
|
1738
1827
|
if (!value)
|
|
@@ -1940,6 +2029,7 @@ export function createKrateHandler(options) {
|
|
|
1940
2029
|
let result;
|
|
1941
2030
|
let redirect = "";
|
|
1942
2031
|
let external = false;
|
|
2032
|
+
let thrown = false;
|
|
1943
2033
|
let failure = null;
|
|
1944
2034
|
let fallback = 0;
|
|
1945
2035
|
try {
|
|
@@ -1949,6 +2039,7 @@ export function createKrateHandler(options) {
|
|
|
1949
2039
|
if (e && typeof e.__krateRedirect === "string") {
|
|
1950
2040
|
redirect = e.__krateRedirect;
|
|
1951
2041
|
external = e.__krateRedirectExternal === true;
|
|
2042
|
+
thrown = true;
|
|
1952
2043
|
}
|
|
1953
2044
|
else if ((fallback = httpFallbackStatus(e)))
|
|
1954
2045
|
failure = null;
|
|
@@ -1965,7 +2056,10 @@ export function createKrateHandler(options) {
|
|
|
1965
2056
|
}
|
|
1966
2057
|
if (!redirect && result && typeof result === "object" && typeof result.redirect === "string")
|
|
1967
2058
|
redirect = result.redirect;
|
|
1968
|
-
|
|
2059
|
+
if (external)
|
|
2060
|
+
redirect = safeExternalRedirect(redirect);
|
|
2061
|
+
else
|
|
2062
|
+
({ to: redirect, external } = actionRedirectTarget(redirect, reqHeaders.get("x-forwarded-host") || reqHeaders.get("host"), thrown));
|
|
1969
2063
|
if (fallback && !failure)
|
|
1970
2064
|
return withHeaders(rs, actionFallback(rs, fallback, fetchMode, ctx.setCookies, reqHeaders.get("x-krate-return") || ""));
|
|
1971
2065
|
let body = "";
|
package/dist/server-renderer.js
CHANGED
|
@@ -14,6 +14,7 @@ import { encodeFrame, REGION_FRAMES_TYPE, wantsRegionFrames } from "./region-wir
|
|
|
14
14
|
import { installRenderStore, patchFetch } from "./cache-scope.js";
|
|
15
15
|
import { cacheSpecFromEnv } from "./cache-adapter.js";
|
|
16
16
|
import { isrStoreFor } from "./shared-isr.js";
|
|
17
|
+
import { cacheByteBudgets, cacheBytesFromEnv } from "./memsize.js";
|
|
17
18
|
import { registerLanguage, setFenceResolver } from "./highlight.js";
|
|
18
19
|
import { installProcessGuards } from "./process-guard.js";
|
|
19
20
|
// Render cache scopes (tags / revalidate windows read during a render) and the
|
|
@@ -289,7 +290,8 @@ function loadRuntimeRenderer(relPath) {
|
|
|
289
290
|
}
|
|
290
291
|
// Render core
|
|
291
292
|
const pprEnabledEnv = process.env.KRATE_PPR === "1";
|
|
292
|
-
const
|
|
293
|
+
const cacheBytes = cacheBytesFromEnv(process.env);
|
|
294
|
+
const isrMemory = new MemoryIsrStore(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512, cacheByteBudgets(cacheBytes).pages);
|
|
293
295
|
// With a shared cache adapter (KRATE_CACHE) the ISR cache and the data cache live
|
|
294
296
|
// in the adapter, so every instance serves and invalidates the same pages.
|
|
295
297
|
const sharedCache = isrStoreFor(cacheSpecFromEnv(process.env), isrMemory);
|
|
@@ -300,6 +302,7 @@ const core = createSSRCore({
|
|
|
300
302
|
loadPageModule,
|
|
301
303
|
loadRuntimeRenderer,
|
|
302
304
|
maxCacheSize: parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512,
|
|
305
|
+
cacheBytes,
|
|
303
306
|
timeoutMs: parseInt(process.env.KRATE_SSR_TIMEOUT || "", 10) || 5000,
|
|
304
307
|
ppr: pprEnabledEnv,
|
|
305
308
|
pprRevalidate: parseInt(process.env.KRATE_PPR_REVALIDATE || "", 10) || 60,
|
package/dist/server.d.ts
CHANGED
|
@@ -33,11 +33,13 @@ interface JSXElement {
|
|
|
33
33
|
type: string | Function | object | symbol;
|
|
34
34
|
props: Record<string, any>;
|
|
35
35
|
children: JSXNode[];
|
|
36
|
+
/** The element's React key, when it has one (a client island carries it, see clientBoundary). */
|
|
37
|
+
key?: string;
|
|
36
38
|
}
|
|
37
39
|
export declare function Fragment(_props: {
|
|
38
40
|
children?: JSXNode;
|
|
39
41
|
}): JSXNode;
|
|
40
|
-
export declare function jsx(type: string | Function | object | symbol, props: Record<string, any>,
|
|
42
|
+
export declare function jsx(type: string | Function | object | symbol, props: Record<string, any>, key?: string): JSXElement;
|
|
41
43
|
export declare const jsxs: typeof jsx;
|
|
42
44
|
/**
|
|
43
45
|
* ServerErrorBoundary is the request-time form of a segment's error.tsx under
|
|
@@ -121,9 +123,10 @@ export declare const ISLAND_CLOSE = "<!--/krate-island-->";
|
|
|
121
123
|
* always travel as a tree, with a server component at the top of a child run
|
|
122
124
|
* to the element it renders, so the component's Slot can clone it. A
|
|
123
125
|
* namespace export (Radix's Dialog) is wrapped member by member. With `flight` the children always travel as a
|
|
124
|
-
* tree (a real-React island rebuilds them as elements, not HTML).
|
|
126
|
+
* tree (a real-React island rebuilds them as elements, not HTML). pkg names
|
|
127
|
+
* the package specifier of a package component (no "use client"), for errors.
|
|
125
128
|
*/
|
|
126
|
-
export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean): unknown;
|
|
129
|
+
export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean, pkg?: string): unknown;
|
|
127
130
|
export declare const HEAD_OPEN = "<!--krate-head-->";
|
|
128
131
|
export declare const HEAD_CLOSE = "<!--/krate-head-->";
|
|
129
132
|
export declare function Head(props: {
|
package/dist/server.js
CHANGED
|
@@ -7,7 +7,7 @@ import { sealBoundArgs } from './action-seal.js';
|
|
|
7
7
|
import { accessDeniedStatus, isDynamicUsageError, isNotFoundSignal, redirectTarget } from './request-context.js';
|
|
8
8
|
import { sha256Hex } from './sha256.js';
|
|
9
9
|
import { currentRenderScope, markErrorCaught } from './cache-scope.js';
|
|
10
|
-
import { encodeProp } from './flight-props.js';
|
|
10
|
+
import { encodeProp, settleThenables } from './flight-props.js';
|
|
11
11
|
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
12
12
|
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
13
13
|
export { after } from './after.js';
|
|
@@ -101,14 +101,19 @@ function base64url(s) {
|
|
|
101
101
|
export function Fragment(_props) {
|
|
102
102
|
return _props.children ?? [];
|
|
103
103
|
}
|
|
104
|
-
export function jsx(type, props,
|
|
104
|
+
export function jsx(type, props, key) {
|
|
105
105
|
const { children, ...rest } = props ?? {};
|
|
106
106
|
const childArray = Array.isArray(children)
|
|
107
107
|
? children.flat(Infinity)
|
|
108
108
|
: children != null
|
|
109
109
|
? [children]
|
|
110
110
|
: [];
|
|
111
|
-
|
|
111
|
+
const el = { type, props: rest, children: childArray };
|
|
112
|
+
// The automatic runtime passes the key apart; createElement leaves it in props.
|
|
113
|
+
const k = key ?? rest.key;
|
|
114
|
+
if (k != null)
|
|
115
|
+
el.key = String(k);
|
|
116
|
+
return el;
|
|
112
117
|
}
|
|
113
118
|
export const jsxs = jsx;
|
|
114
119
|
// HTML Rendering
|
|
@@ -217,7 +222,11 @@ function normalizeNode(node) {
|
|
|
217
222
|
return node;
|
|
218
223
|
const { children, ref: _ref, ...rest } = node.props ?? {};
|
|
219
224
|
const kids = Array.isArray(children) ? children.flat(Infinity) : children != null ? [children] : [];
|
|
220
|
-
|
|
225
|
+
const el = { type: node.type, props: rest, children: kids };
|
|
226
|
+
const k = node.key;
|
|
227
|
+
if (k != null)
|
|
228
|
+
el.key = String(k);
|
|
229
|
+
return el;
|
|
221
230
|
}
|
|
222
231
|
function foreignContext(type) {
|
|
223
232
|
if (type.$$typeof === R_PROVIDER)
|
|
@@ -515,7 +524,7 @@ async function expandComponent(node, vals) {
|
|
|
515
524
|
return { out: consumerChild(callProps)(vals?.has(ctx) ? vals.get(ctx) : ctx._currentValue), vals };
|
|
516
525
|
}
|
|
517
526
|
// A client boundary also gets the context values in scope (slotValues).
|
|
518
|
-
let out = fn.__krateClient ? fn(callProps, vals, RENDER_CALL) : fn(callProps);
|
|
527
|
+
let out = fn.__krateClient ? fn(callProps, vals, RENDER_CALL, node.key) : fn(callProps);
|
|
519
528
|
if (isThenable(out))
|
|
520
529
|
out = await out;
|
|
521
530
|
if (fn.__krateForeignProvider) {
|
|
@@ -551,7 +560,7 @@ function renderElement(el) {
|
|
|
551
560
|
throw asyncInSyncRender("A lazy component");
|
|
552
561
|
throw e;
|
|
553
562
|
}
|
|
554
|
-
return renderElement({ type: fn
|
|
563
|
+
return renderElement({ ...el, type: fn });
|
|
555
564
|
}
|
|
556
565
|
if (typeof type === "function") {
|
|
557
566
|
if (isClassComponent(type)) {
|
|
@@ -563,7 +572,9 @@ function renderElement(el) {
|
|
|
563
572
|
return renderNode(classFallback(type, instance, error));
|
|
564
573
|
}
|
|
565
574
|
}
|
|
566
|
-
const result = type.__krateClient
|
|
575
|
+
const result = type.__krateClient
|
|
576
|
+
? type({ ...props, children }, undefined, RENDER_CALL, el.key)
|
|
577
|
+
: type({ ...props, children });
|
|
567
578
|
if (isThenable(result))
|
|
568
579
|
throw asyncInSyncRender(`<${componentName(type)}>`);
|
|
569
580
|
return withProviderValue(type, props, () => renderNode(result));
|
|
@@ -666,16 +677,27 @@ const flightIsJSX = (v) => isElement(v) || "__raw" in v;
|
|
|
666
677
|
// actions become references the client chunk turns back into callable
|
|
667
678
|
// proxies; anything JSON and the tag encoding cannot carry faithfully throws
|
|
668
679
|
// with the offending prop path.
|
|
669
|
-
function serializeClientProp(v, path, component) {
|
|
680
|
+
function serializeClientProp(v, path, component, pkg) {
|
|
670
681
|
if (v === undefined)
|
|
671
682
|
return undefined;
|
|
672
683
|
return encodeProp(v, path, {
|
|
673
684
|
isAction: flightIsAction,
|
|
674
685
|
sealBound: sealBoundArgs,
|
|
675
686
|
isJSX: flightIsJSX,
|
|
676
|
-
fail: (p, what, hint) => clientPropError(p, component, what, hint),
|
|
687
|
+
fail: (p, what, hint) => pkg && what === "a function" ? packageFunctionPropError(p, component, pkg) : clientPropError(p, component, what, hint),
|
|
677
688
|
});
|
|
678
689
|
}
|
|
690
|
+
// packageFunctionPropError explains a function handed to a component of a
|
|
691
|
+
// React package without "use client": Krate renders such components with
|
|
692
|
+
// Preact, like client components, so the function (often a component of the
|
|
693
|
+
// app, as in an MDX `components` map) cannot reach it.
|
|
694
|
+
function packageFunctionPropError(path, component, pkg) {
|
|
695
|
+
return new Error(`Prop \`${path}\` passed to <${component}> from the package "${pkg}" is a function. The package has no "use client", ` +
|
|
696
|
+
`but Krate renders the components of React packages in server components with Preact, like client components, ` +
|
|
697
|
+
`so their props must be serializable and cannot hold functions or components of your app. ` +
|
|
698
|
+
`Copy <${component}> into your project (it then renders as a server component with the functions you pass), ` +
|
|
699
|
+
`or render it from a "use client" component of your own that imports those functions itself.`);
|
|
700
|
+
}
|
|
679
701
|
function clientPropError(path, component, what, hint) {
|
|
680
702
|
return new Error(`Prop \`${path}\` passed to client component <${component}> is ${what}, which cannot be sent from a server ` +
|
|
681
703
|
`component to the client. ` +
|
|
@@ -740,7 +762,9 @@ async function clientProps(props, ctx, tree) {
|
|
|
740
762
|
for (const [k, v] of Object.entries(props)) {
|
|
741
763
|
if (k === "key" || k === "children")
|
|
742
764
|
continue;
|
|
743
|
-
|
|
765
|
+
if (!isSlotValue(v))
|
|
766
|
+
await settleThenables(v);
|
|
767
|
+
const sv = isSlotValue(v) ? await slotProp(v, ctx, tree) : serializeClientProp(v, k, ctx.component, ctx.pkg);
|
|
744
768
|
if (sv !== undefined)
|
|
745
769
|
out[k] = sv;
|
|
746
770
|
}
|
|
@@ -836,8 +860,14 @@ export const ISLAND_CLOSE = "<!--/krate-island-->";
|
|
|
836
860
|
// islandOpen is the opening comment of a Preact island: its module, export,
|
|
837
861
|
// chunk and props as JSON. "<", ">" and "--" are escaped (they occur only in
|
|
838
862
|
// strings), so no value can end the comment or open another one.
|
|
839
|
-
function islandOpen(moduleId, exportName, src, props, ids) {
|
|
840
|
-
const
|
|
863
|
+
function islandOpen(moduleId, exportName, src, props, ids, key) {
|
|
864
|
+
const head = { m: moduleId, e: exportName, s: src, i: ids };
|
|
865
|
+
// The React key: the router keeps a keyed island's state by key, not by
|
|
866
|
+
// position, across a refresh (see island-swap.ts).
|
|
867
|
+
if (key != null)
|
|
868
|
+
head.k = key;
|
|
869
|
+
head.p = props;
|
|
870
|
+
const json = JSON.stringify(head)
|
|
841
871
|
.replace(/</g, "\\u003c")
|
|
842
872
|
.replace(/>/g, "\\u003e")
|
|
843
873
|
.replace(/--/g, "-\\u002d");
|
|
@@ -845,22 +875,28 @@ function islandOpen(moduleId, exportName, src, props, ids) {
|
|
|
845
875
|
}
|
|
846
876
|
// islandIdPrefix names the next island of a component in the render that is
|
|
847
877
|
// running: a hash of its module and export, and how many islands of that
|
|
848
|
-
// component came before it in this document
|
|
878
|
+
// component came before it in this document (for a keyed island, how many
|
|
879
|
+
// before it had its key, and a hash of the key). useId() numbers from 0 inside
|
|
849
880
|
// each island, so the prefix is what keeps ids unique across the page. The
|
|
850
|
-
// router pairs the n-th island of a component in the live page with
|
|
851
|
-
// one in the new markup,
|
|
852
|
-
//
|
|
881
|
+
// router pairs the n-th unkeyed island of a component in the live page with
|
|
882
|
+
// the n-th one in the new markup, and a keyed one with the one of the same
|
|
883
|
+
// key, so a page that a navigation swaps in never reuses the prefix of an
|
|
884
|
+
// island the swap keeps.
|
|
853
885
|
const looseIslands = new Map();
|
|
854
|
-
function
|
|
855
|
-
|
|
886
|
+
function fnv36(s) {
|
|
887
|
+
let h = 0x811C9DC5;
|
|
888
|
+
for (let i = 0; i < s.length; i++)
|
|
889
|
+
h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0;
|
|
890
|
+
return h.toString(36).padStart(7, "0");
|
|
891
|
+
}
|
|
892
|
+
function islandIdPrefix(moduleId, exportName, key) {
|
|
893
|
+
const component = moduleId + "#" + exportName;
|
|
856
894
|
const scope = currentRenderScope();
|
|
857
895
|
const seen = scope ? (scope.islands ?? (scope.islands = new Map())) : looseIslands;
|
|
858
|
-
const
|
|
859
|
-
seen.
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
h = Math.imul(h ^ key.charCodeAt(i), 0x01000193) >>> 0;
|
|
863
|
-
return h.toString(36).padStart(7, "0") + "_" + n;
|
|
896
|
+
const counter = key == null ? component : component + "\u0000" + key;
|
|
897
|
+
const n = seen.get(counter) ?? 0;
|
|
898
|
+
seen.set(counter, n + 1);
|
|
899
|
+
return fnv36(component) + "_" + (key == null ? "" : "k" + fnv36(key) + "_") + n;
|
|
864
900
|
}
|
|
865
901
|
const warnedUncloneable = new Set();
|
|
866
902
|
// RENDER_CALL is the third argument the renderer passes when it renders a
|
|
@@ -887,16 +923,16 @@ function warnUncloneable(component, tree) {
|
|
|
887
923
|
console.warn(`[krate] <${component} asChild> received a child rendered to HTML, so it cannot merge its props and handlers ` +
|
|
888
924
|
`into it. Pass a single element or a component that renders one (not raw HTML) as the child.`);
|
|
889
925
|
}
|
|
890
|
-
function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
|
|
926
|
+
function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate, pkg) {
|
|
891
927
|
const out = {};
|
|
892
928
|
for (const key of Object.keys(ns)) {
|
|
893
929
|
const v = ns[key];
|
|
894
930
|
const isComponentName = /^[A-Z]/.test(key);
|
|
895
931
|
if (isComponentName && typeof v === "function") {
|
|
896
|
-
out[key] = clientBoundary(moduleId, `${exportName}.${key}`, src, v, render, hydrate);
|
|
932
|
+
out[key] = clientBoundary(moduleId, `${exportName}.${key}`, src, v, render, hydrate, false, pkg);
|
|
897
933
|
}
|
|
898
934
|
else if (isComponentName && v && typeof v === "object" && !Array.isArray(v)) {
|
|
899
|
-
out[key] = wrapClientNamespace(moduleId, `${exportName}.${key}`, src, v, render, hydrate);
|
|
935
|
+
out[key] = wrapClientNamespace(moduleId, `${exportName}.${key}`, src, v, render, hydrate, pkg);
|
|
900
936
|
}
|
|
901
937
|
else {
|
|
902
938
|
out[key] = v;
|
|
@@ -921,11 +957,12 @@ function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
|
|
|
921
957
|
* always travel as a tree, with a server component at the top of a child run
|
|
922
958
|
* to the element it renders, so the component's Slot can clone it. A
|
|
923
959
|
* namespace export (Radix's Dialog) is wrapped member by member. With `flight` the children always travel as a
|
|
924
|
-
* tree (a real-React island rebuilds them as elements, not HTML).
|
|
960
|
+
* tree (a real-React island rebuilds them as elements, not HTML). pkg names
|
|
961
|
+
* the package specifier of a package component (no "use client"), for errors.
|
|
925
962
|
*/
|
|
926
|
-
export function clientBoundary(moduleId, exportName, src, impl, render, hydrate = true, flight = false) {
|
|
963
|
+
export function clientBoundary(moduleId, exportName, src, impl, render, hydrate = true, flight = false, pkg) {
|
|
927
964
|
if (impl && typeof impl === "object" && !Array.isArray(impl)) {
|
|
928
|
-
return wrapClientNamespace(moduleId, exportName, src, impl, render, hydrate);
|
|
965
|
+
return wrapClientNamespace(moduleId, exportName, src, impl, render, hydrate, pkg);
|
|
929
966
|
}
|
|
930
967
|
if (typeof impl !== "function")
|
|
931
968
|
return impl;
|
|
@@ -933,17 +970,19 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
|
|
|
933
970
|
// Called by user code, the boundary fails here and now. An async function
|
|
934
971
|
// would hand back a rejected promise the caller never awaits, and that
|
|
935
972
|
// unhandled rejection would take the renderer process down.
|
|
936
|
-
const Boundary = (props, vals, from) => {
|
|
973
|
+
const Boundary = (props, vals, from, key) => {
|
|
937
974
|
if (from !== RENDER_CALL)
|
|
938
975
|
throw clientCallError(exportName, name);
|
|
939
|
-
return renderBoundary(props, vals);
|
|
976
|
+
return renderBoundary(props, vals, key);
|
|
940
977
|
};
|
|
941
|
-
const renderBoundary = async (props, vals) => {
|
|
978
|
+
const renderBoundary = async (props, vals, elementKey) => {
|
|
979
|
+
// A key is not a prop (React leaves it out of props too).
|
|
980
|
+
const { children, key: propKey, ...rest } = props || {};
|
|
981
|
+
const key = elementKey ?? (propKey != null ? String(propKey) : undefined);
|
|
942
982
|
// Taken before the first await, so islands number in render order.
|
|
943
|
-
const ids = islandIdPrefix(moduleId, exportName);
|
|
944
|
-
const { children, ...rest } = props || {};
|
|
983
|
+
const ids = islandIdPrefix(moduleId, exportName, key);
|
|
945
984
|
const slots = [];
|
|
946
|
-
const slotCtx = { hydrate: false, component: name, slots, vals };
|
|
985
|
+
const slotCtx = { hydrate: false, component: name, slots, vals, pkg };
|
|
947
986
|
const data = await clientProps(rest, slotCtx, flight);
|
|
948
987
|
const hasChildren = children != null && !(Array.isArray(children) && children.length === 0);
|
|
949
988
|
let hydrates = hydrate || slotCtx.hydrate;
|
|
@@ -984,9 +1023,10 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
|
|
|
984
1023
|
// element of its own; a Preact island hydrates the nodes between its two
|
|
985
1024
|
// comments in place.
|
|
986
1025
|
if (!flight)
|
|
987
|
-
return raw(islandOpen(moduleId, exportName, src, data, ids) + html + ISLAND_CLOSE);
|
|
1026
|
+
return raw(islandOpen(moduleId, exportName, src, data, ids, key) + html + ISLAND_CLOSE);
|
|
1027
|
+
const keyAttr = key != null ? ` data-key="${escapeHTML(key)}"` : "";
|
|
988
1028
|
return raw(propsScript(data) +
|
|
989
|
-
`<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
|
|
1029
|
+
`<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}"${keyAttr} ` +
|
|
990
1030
|
`data-src="${escapeHTML(src)}">${html}</krate-island>`);
|
|
991
1031
|
};
|
|
992
1032
|
Object.defineProperty(Boundary, "name", { value: name });
|