@krate/runtime 0.5.0-beta.1 → 0.5.0-beta.2
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.js +2 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +60 -12
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/dev-overlay.js +10 -10
- package/dist/dom.d.ts +8 -0
- package/dist/dom.js +28 -0
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +4 -4
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +10 -10
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +5 -5
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +254 -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/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +27 -0
- package/dist/router.js +59 -4
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +23 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +146 -788
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +12 -1
- package/dist/server.js +42 -6
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.js +63 -8
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +29 -1
package/dist/ssr-core.js
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
// Shared SSR rendering core. The Node sidecar (server-renderer.ts) and the
|
|
2
|
+
// portable server handler (server-handler.ts) both render pages and regions
|
|
3
|
+
// through it, so ISR/region caching, query tracking and render signals behave
|
|
4
|
+
// the same wherever Krate runs. It has no node:fs/node:vm/node:http imports:
|
|
5
|
+
// module loading is injected by the host.
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
+
import { jsx, renderToStringAsync } from "./server.js";
|
|
8
|
+
import { sha256Hex as portableSha256Hex } from "./sha256.js";
|
|
9
|
+
import { isNotFoundSignal, accessDeniedStatus, parseCookieHeader, redirectTarget, thenable, thenableRecord, } from "./request-context.js";
|
|
10
|
+
import { HEAD_CLOSE, HEAD_OPEN, takeHead } from "./head-tags.js";
|
|
11
|
+
import { metadataHeadTags } from "./metadata.js";
|
|
12
|
+
import { SegmentedLRU } from "./segmented-lru.js";
|
|
13
|
+
import { cacheRuntime, routeDataTag, withCacheScope, } from "./cache-scope.js";
|
|
14
|
+
// ISR Cache (variant-aware, SWR, persisted)
|
|
15
|
+
// A page's cache key is the route plus its per-request variant (params +
|
|
16
|
+
// query). Two dynamic-route requests (e.g. /video/a and /video/b) render
|
|
17
|
+
// different HTML, so they must never share a cache slot.
|
|
18
|
+
export function variantKey(req) {
|
|
19
|
+
const enc = (v) => Object.keys(v).sort().map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(v[k])}`).join("&");
|
|
20
|
+
const params = req.params ? enc(req.params) : "";
|
|
21
|
+
const query = req.query ? enc(req.query) : "";
|
|
22
|
+
let key = req.route;
|
|
23
|
+
if (params)
|
|
24
|
+
key += "?" + params;
|
|
25
|
+
if (query)
|
|
26
|
+
key += "#" + query;
|
|
27
|
+
return key;
|
|
28
|
+
}
|
|
29
|
+
export function newQueryTracker() {
|
|
30
|
+
return { keys: new Set(), all: false };
|
|
31
|
+
}
|
|
32
|
+
export function trackedQuery(query, t) {
|
|
33
|
+
const target = { ...(query || {}) };
|
|
34
|
+
const note = (prop) => {
|
|
35
|
+
if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor")
|
|
36
|
+
t.keys.add(prop);
|
|
37
|
+
};
|
|
38
|
+
return new Proxy(target, {
|
|
39
|
+
get(obj, prop, recv) {
|
|
40
|
+
note(prop);
|
|
41
|
+
return Reflect.get(obj, prop, recv);
|
|
42
|
+
},
|
|
43
|
+
has(obj, prop) {
|
|
44
|
+
note(prop);
|
|
45
|
+
return Reflect.has(obj, prop);
|
|
46
|
+
},
|
|
47
|
+
ownKeys(obj) {
|
|
48
|
+
t.all = true;
|
|
49
|
+
return Reflect.ownKeys(obj);
|
|
50
|
+
},
|
|
51
|
+
getOwnPropertyDescriptor(obj, prop) {
|
|
52
|
+
note(prop);
|
|
53
|
+
return Reflect.getOwnPropertyDescriptor(obj, prop);
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export class ISRCache {
|
|
58
|
+
constructor(maxSize = 512) {
|
|
59
|
+
this.byTag = new Map();
|
|
60
|
+
this.revalidationIntervals = new Map(); // route -> seconds
|
|
61
|
+
this.cache = new SegmentedLRU(maxSize);
|
|
62
|
+
}
|
|
63
|
+
setRevalidation(route, seconds) {
|
|
64
|
+
this.revalidationIntervals.set(route, seconds);
|
|
65
|
+
}
|
|
66
|
+
// get counts as a use: an entry hit once is promoted out of probation.
|
|
67
|
+
get(key) {
|
|
68
|
+
return this.cache.get(key);
|
|
69
|
+
}
|
|
70
|
+
set(key, entry) {
|
|
71
|
+
const old = this.cache.peek(key);
|
|
72
|
+
if (old)
|
|
73
|
+
this.unindex(key, old);
|
|
74
|
+
for (const [k, e] of this.cache.set(key, entry))
|
|
75
|
+
this.unindex(k, e);
|
|
76
|
+
for (const t of entry.tags || []) {
|
|
77
|
+
let keys = this.byTag.get(t);
|
|
78
|
+
if (!keys)
|
|
79
|
+
this.byTag.set(t, (keys = new Set()));
|
|
80
|
+
keys.add(key);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
unindex(key, entry) {
|
|
84
|
+
for (const t of entry.tags || []) {
|
|
85
|
+
const keys = this.byTag.get(t);
|
|
86
|
+
if (keys) {
|
|
87
|
+
keys.delete(key);
|
|
88
|
+
if (keys.size === 0)
|
|
89
|
+
this.byTag.delete(t);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
delete(key) {
|
|
94
|
+
const entry = this.cache.peek(key);
|
|
95
|
+
if (!entry)
|
|
96
|
+
return false;
|
|
97
|
+
this.cache.delete(key);
|
|
98
|
+
this.unindex(key, entry);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
get size() {
|
|
102
|
+
return this.cache.size;
|
|
103
|
+
}
|
|
104
|
+
isStale(key) {
|
|
105
|
+
const entry = this.cache.peek(key);
|
|
106
|
+
const route = key.split("?")[0].split("#")[0];
|
|
107
|
+
let interval = this.revalidationIntervals.get(route) || 0;
|
|
108
|
+
if (entry && entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval)) {
|
|
109
|
+
interval = entry.revalidate;
|
|
110
|
+
}
|
|
111
|
+
if (!entry || !interval)
|
|
112
|
+
return false;
|
|
113
|
+
return (Date.now() - entry.timestamp) / 1000 > interval;
|
|
114
|
+
}
|
|
115
|
+
// deleteRoute removes every variant of a route (used by revalidation/invalidation).
|
|
116
|
+
deleteRoute(route) {
|
|
117
|
+
let n = 0;
|
|
118
|
+
for (const key of this.cache.keys()) {
|
|
119
|
+
if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
|
|
120
|
+
if (this.delete(key))
|
|
121
|
+
n++;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return n;
|
|
125
|
+
}
|
|
126
|
+
// deleteVariant removes one params variant of a route (every query variant
|
|
127
|
+
// of it), e.g. /blog/[slug] with {slug: "a"} for revalidatePath("/blog/a").
|
|
128
|
+
deleteVariant(route, params) {
|
|
129
|
+
const base = variantKey({ route, params });
|
|
130
|
+
let n = 0;
|
|
131
|
+
for (const key of this.cache.keys()) {
|
|
132
|
+
if (key === base || key.startsWith(base + "#")) {
|
|
133
|
+
if (this.delete(key))
|
|
134
|
+
n++;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return n;
|
|
138
|
+
}
|
|
139
|
+
// deleteTags removes every entry whose render read one of tags.
|
|
140
|
+
deleteTags(tags) {
|
|
141
|
+
let n = 0;
|
|
142
|
+
for (const t of tags) {
|
|
143
|
+
const keys = this.byTag.get(t);
|
|
144
|
+
if (!keys)
|
|
145
|
+
continue;
|
|
146
|
+
for (const key of [...keys]) {
|
|
147
|
+
if (this.delete(key))
|
|
148
|
+
n++;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return n;
|
|
152
|
+
}
|
|
153
|
+
// entriesForRoute returns a snapshot of the cached variants for a route so a
|
|
154
|
+
// background refresh can iterate them without mutating during iteration.
|
|
155
|
+
entriesForRoute(route) {
|
|
156
|
+
const out = [];
|
|
157
|
+
for (const [key, entry] of this.cache.entries()) {
|
|
158
|
+
if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
|
|
159
|
+
out.push([key, entry]);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
serialize() {
|
|
165
|
+
return {
|
|
166
|
+
entries: this.cache.entries().map(([key, entry]) => ({ key, ...entry })),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
hydrate(data) {
|
|
170
|
+
if (!data || !Array.isArray(data.entries))
|
|
171
|
+
return;
|
|
172
|
+
for (const e of data.entries) {
|
|
173
|
+
if (e && typeof e.key === "string" && typeof e.html === "string") {
|
|
174
|
+
this.set(e.key, {
|
|
175
|
+
html: e.html,
|
|
176
|
+
timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
|
|
177
|
+
params: e.params && typeof e.params === "object" ? e.params : undefined,
|
|
178
|
+
query: e.query && typeof e.query === "object" ? e.query : undefined,
|
|
179
|
+
tags: Array.isArray(e.tags) ? e.tags.filter((t) => typeof t === "string") : undefined,
|
|
180
|
+
revalidate: typeof e.revalidate === "number" ? e.revalidate : undefined,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** The in-process IsrStore: a bounded map with a tag index. */
|
|
187
|
+
export class MemoryIsrStore {
|
|
188
|
+
constructor(maxSize = 512) {
|
|
189
|
+
this.cache = new ISRCache(maxSize);
|
|
190
|
+
}
|
|
191
|
+
get(key) {
|
|
192
|
+
return this.cache.get(key);
|
|
193
|
+
}
|
|
194
|
+
set(key, entry) {
|
|
195
|
+
this.cache.set(key, entry);
|
|
196
|
+
}
|
|
197
|
+
deleteRoute(route) {
|
|
198
|
+
return this.cache.deleteRoute(route);
|
|
199
|
+
}
|
|
200
|
+
deleteVariant(route, params) {
|
|
201
|
+
return this.cache.deleteVariant(route, params);
|
|
202
|
+
}
|
|
203
|
+
deleteTags(tags) {
|
|
204
|
+
return this.cache.deleteTags(tags);
|
|
205
|
+
}
|
|
206
|
+
entriesForRoute(route) {
|
|
207
|
+
return this.cache.entriesForRoute(route);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Splits the document <title> out of rendered page html (see takeHead for the
|
|
212
|
+
* head tags that come with it).
|
|
213
|
+
*/
|
|
214
|
+
export function takeHeadTitle(html) {
|
|
215
|
+
const split = takeHead(html);
|
|
216
|
+
return { title: split.title, html: split.html };
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The metadata chain of a page module: the layouts the build bundled with it
|
|
220
|
+
* (root first) and the page itself. null unless some segment exports a
|
|
221
|
+
* generateMetadata function; literal metadata is baked into the page at build
|
|
222
|
+
* time and needs no request-time work.
|
|
223
|
+
*/
|
|
224
|
+
function metadataSegmentsOf(mod) {
|
|
225
|
+
const layouts = Array.isArray(mod.__krateMetadata) ? mod.__krateMetadata : [];
|
|
226
|
+
const segments = [...layouts, { mod, file: "page", files: mod.__krateMetadataFiles }];
|
|
227
|
+
return segments.some((s) => s.mod && typeof s.mod.generateMetadata === "function") ? segments : null;
|
|
228
|
+
}
|
|
229
|
+
export function createSSRCore(opts) {
|
|
230
|
+
const sha256Hex = opts.sha256Hex || portableSha256Hex;
|
|
231
|
+
// errorDigest is the short id tying the sanitized error a visitor sees to the
|
|
232
|
+
// full error in the server log. The Go server computes the same hash
|
|
233
|
+
// (build/segmentserve.go errorDigest).
|
|
234
|
+
function errorDigest(message, stack) {
|
|
235
|
+
return sha256Hex(message + "\n" + stack).slice(0, 10);
|
|
236
|
+
}
|
|
237
|
+
function describeFailure(err) {
|
|
238
|
+
const message = (err && err.message) || String(err);
|
|
239
|
+
const stack = (err && typeof err.stack === "string" && err.stack) || "";
|
|
240
|
+
return { error: message, stack, digest: errorDigest(message, stack) };
|
|
241
|
+
}
|
|
242
|
+
// pageQueryReads remembers, per route+params variant, which query keys renders
|
|
243
|
+
// have read ("all" when a render enumerated the whole query).
|
|
244
|
+
const pageQueryReads = new Map();
|
|
245
|
+
function pageBaseKey(req) {
|
|
246
|
+
return variantKey({ route: req.route, params: req.params });
|
|
247
|
+
}
|
|
248
|
+
function hasQuery(req) {
|
|
249
|
+
return !!req.query && Object.keys(req.query).length > 0;
|
|
250
|
+
}
|
|
251
|
+
// pageKey is the ISR cache key for a request: params, plus only the query keys
|
|
252
|
+
// previous renders of this variant read. It returns null while no render has
|
|
253
|
+
// shown what the page reads (a restart, or the record was evicted) and the
|
|
254
|
+
// request carries a query: the stored entries cannot be matched to it safely,
|
|
255
|
+
// so it has to render.
|
|
256
|
+
function pageKey(req) {
|
|
257
|
+
const base = pageBaseKey(req);
|
|
258
|
+
const reads = pageQueryReads.get(base);
|
|
259
|
+
if (!reads)
|
|
260
|
+
return hasQuery(req) ? null : base;
|
|
261
|
+
// Looked up variants keep their record when others are evicted.
|
|
262
|
+
pageQueryReads.delete(base);
|
|
263
|
+
pageQueryReads.set(base, reads);
|
|
264
|
+
if (reads === "all")
|
|
265
|
+
return variantKey(req);
|
|
266
|
+
const picked = {};
|
|
267
|
+
for (const k of [...reads].sort()) {
|
|
268
|
+
if (req.query && Object.prototype.hasOwnProperty.call(req.query, k))
|
|
269
|
+
picked[k] = req.query[k];
|
|
270
|
+
}
|
|
271
|
+
return variantKey({ route: req.route, params: req.params, query: picked });
|
|
272
|
+
}
|
|
273
|
+
// The map is keyed by params, which a client chooses, so it is bounded like
|
|
274
|
+
// the cache it describes. Losing an entry only costs one extra render, which
|
|
275
|
+
// records the reads again.
|
|
276
|
+
const PAGE_QUERY_READS_MAX = Math.max(4 * (opts.maxCacheSize && opts.maxCacheSize > 0 ? opts.maxCacheSize : 512), 1024);
|
|
277
|
+
// mergeReads folds the query keys one render read into what was known. A
|
|
278
|
+
// render that read no query key records an empty set: its entry is valid for
|
|
279
|
+
// every query string.
|
|
280
|
+
function mergeReads(cur, t) {
|
|
281
|
+
if (t.all || cur === "all")
|
|
282
|
+
return "all";
|
|
283
|
+
return new Set([...(cur || []), ...t.keys]);
|
|
284
|
+
}
|
|
285
|
+
function recordQueryReads(req, t) {
|
|
286
|
+
const base = pageBaseKey(req);
|
|
287
|
+
const cur = mergeReads(pageQueryReads.get(base), t);
|
|
288
|
+
pageQueryReads.delete(base);
|
|
289
|
+
pageQueryReads.set(base, cur);
|
|
290
|
+
if (pageQueryReads.size > PAGE_QUERY_READS_MAX) {
|
|
291
|
+
const oldest = pageQueryReads.keys().next().value;
|
|
292
|
+
if (oldest !== undefined)
|
|
293
|
+
pageQueryReads.delete(oldest);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// ISR cache size and the render timeout are configurable via the compiler
|
|
297
|
+
// (ssr.maxCacheSize / ssr.timeout), which exports them to the sidecar env.
|
|
298
|
+
const isrStore = opts.isrStore || new MemoryIsrStore(opts.maxCacheSize && opts.maxCacheSize > 0 ? opts.maxCacheSize : 512);
|
|
299
|
+
// pageIntervals remembers each ISR page's revalidate window (seconds).
|
|
300
|
+
const pageIntervals = new Map();
|
|
301
|
+
// entryStale: the entry is older than its page window, or than the smaller
|
|
302
|
+
// window one of its data reads declared.
|
|
303
|
+
function entryStale(key, entry) {
|
|
304
|
+
const route = key.split("?")[0].split("#")[0];
|
|
305
|
+
let interval = pageIntervals.get(route) || 0;
|
|
306
|
+
if (entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval))
|
|
307
|
+
interval = entry.revalidate;
|
|
308
|
+
if (!interval)
|
|
309
|
+
return false;
|
|
310
|
+
return (Date.now() - entry.timestamp) / 1000 > interval;
|
|
311
|
+
}
|
|
312
|
+
// renderTimeoutMs bounds a single renderToString call so one pathological page
|
|
313
|
+
// cannot pin the sidecar. 0 disables the bound.
|
|
314
|
+
const renderTimeoutMs = opts.timeoutMs !== undefined ? opts.timeoutMs : 5000;
|
|
315
|
+
// Partial Prerendering: cache dynamic regions on non-ISR pages with this
|
|
316
|
+
// window (overridable per region via `export const revalidate`).
|
|
317
|
+
const pprEnabled = !!opts.ppr;
|
|
318
|
+
const pprRevalidate = opts.pprRevalidate && opts.pprRevalidate > 0 ? opts.pprRevalidate : 60;
|
|
319
|
+
// withRenderTimeout rejects if p does not settle within renderTimeoutMs. The
|
|
320
|
+
// underlying render keeps running (JS cannot cancel it), but the request fails
|
|
321
|
+
// fast rather than hanging.
|
|
322
|
+
function withRenderTimeout(p) {
|
|
323
|
+
if (renderTimeoutMs <= 0)
|
|
324
|
+
return p;
|
|
325
|
+
return new Promise((resolve, reject) => {
|
|
326
|
+
const timer = setTimeout(() => reject(new Error(`render timed out after ${renderTimeoutMs}ms`)), renderTimeoutMs);
|
|
327
|
+
p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
// Renderer
|
|
331
|
+
const manifest = opts.manifest;
|
|
332
|
+
function findPage(route) {
|
|
333
|
+
if (!manifest)
|
|
334
|
+
return undefined;
|
|
335
|
+
// Try exact match first, then strip trailing slash
|
|
336
|
+
let page = manifest.pages.find((p) => p.route === route);
|
|
337
|
+
if (!page && route !== "/") {
|
|
338
|
+
page = manifest.pages.find((p) => p.route === route + "/");
|
|
339
|
+
}
|
|
340
|
+
if (!page && route.endsWith("/")) {
|
|
341
|
+
page = manifest.pages.find((p) => p.route === route.slice(0, -1));
|
|
342
|
+
}
|
|
343
|
+
return page;
|
|
344
|
+
}
|
|
345
|
+
// Request scope for server components: headers()/cookies() from
|
|
346
|
+
// @krate/runtime/server read it through the global store symbol, so it works
|
|
347
|
+
// no matter which copy of the runtime a page bundle resolved.
|
|
348
|
+
const requestStore = (() => {
|
|
349
|
+
const key = Symbol.for("krate.request.store");
|
|
350
|
+
const g = globalThis;
|
|
351
|
+
if (!g[key])
|
|
352
|
+
g[key] = new AsyncLocalStorage();
|
|
353
|
+
return g[key];
|
|
354
|
+
})();
|
|
355
|
+
function requestContextFor(req, tracker) {
|
|
356
|
+
const h = new Headers();
|
|
357
|
+
for (const [k, v] of Object.entries(req.headers || {})) {
|
|
358
|
+
if (typeof v === "string") {
|
|
359
|
+
try {
|
|
360
|
+
h.set(k, v);
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
// skip header names the WHATWG Headers class rejects
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
url: req.url || req.route,
|
|
369
|
+
method: req.method || "GET",
|
|
370
|
+
headers: h,
|
|
371
|
+
cookies: parseCookieHeader(h.get("cookie")),
|
|
372
|
+
params: { ...(req.params || {}) },
|
|
373
|
+
searchParams: tracker ? trackedQuery(req.query, tracker) : { ...(req.query || {}) },
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function withRequest(req, fn, tracker) {
|
|
377
|
+
return requestStore.run(requestContextFor(req, tracker), fn);
|
|
378
|
+
}
|
|
379
|
+
// renderSignal maps notFound()/redirect() thrown during a render to a response.
|
|
380
|
+
function renderSignal(err) {
|
|
381
|
+
if (isNotFoundSignal(err))
|
|
382
|
+
return { html: "", status: 404, notFound: true };
|
|
383
|
+
const denied = accessDeniedStatus(err);
|
|
384
|
+
if (denied)
|
|
385
|
+
return { html: "", status: denied, denied };
|
|
386
|
+
const to = redirectTarget(err);
|
|
387
|
+
if (to)
|
|
388
|
+
return { html: "", status: 307, redirect: to };
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
function buildProps(req, tracker) {
|
|
392
|
+
// Page-level data fetching (getStaticProps/getServerSideProps) has been
|
|
393
|
+
// removed; per-request data is provided by server components (@server),
|
|
394
|
+
// runtime components (@runtime), and middleware instead. Dynamic-route
|
|
395
|
+
// params and query parameters extracted by the Go server are forwarded so
|
|
396
|
+
// `({ params }) => ...` pages receive their real values at render time.
|
|
397
|
+
// params and searchParams are plain objects that can also be awaited, so
|
|
398
|
+
// both `params.slug` and Next.js 15's `const { slug } = await params` work.
|
|
399
|
+
// The Go server always forwards params (empty for static routes); a direct
|
|
400
|
+
// request without them keeps params undefined, as before.
|
|
401
|
+
const props = {};
|
|
402
|
+
if (req.params)
|
|
403
|
+
props.params = thenableRecord(req.params);
|
|
404
|
+
if (tracker) {
|
|
405
|
+
// Reads through the view are recorded; awaiting it resolves to another
|
|
406
|
+
// tracked view so `const { page } = await searchParams` records "page".
|
|
407
|
+
const view = trackedQuery(req.query, tracker);
|
|
408
|
+
props.searchParams = thenable(view, () => trackedQuery(req.query, tracker));
|
|
409
|
+
if (req.query)
|
|
410
|
+
props.query = trackedQuery(req.query, tracker);
|
|
411
|
+
return props;
|
|
412
|
+
}
|
|
413
|
+
props.searchParams = thenableRecord(req.query);
|
|
414
|
+
if (req.query)
|
|
415
|
+
props.query = req.query;
|
|
416
|
+
return props;
|
|
417
|
+
}
|
|
418
|
+
// renderFresh renders a page component and - for ISR pages - stores the result.
|
|
419
|
+
// Extracted so background revalidation shares exactly the same render path.
|
|
420
|
+
async function renderFresh(page, req) {
|
|
421
|
+
try {
|
|
422
|
+
const mod = await opts.loadPageModule(page);
|
|
423
|
+
const Component = mod.default;
|
|
424
|
+
if (!Component) {
|
|
425
|
+
return { html: "", status: 500 };
|
|
426
|
+
}
|
|
427
|
+
// The render runs in a cache scope that records the tags / revalidate
|
|
428
|
+
// windows its data reads declared (fetch next options, unstable_cache).
|
|
429
|
+
// Async server components (and plain sync pages) render through
|
|
430
|
+
// renderToStringAsync inside the request scope. The timeout bounds slow
|
|
431
|
+
// awaits (fetch); a page that blocks synchronously still blocks the loop.
|
|
432
|
+
const tracker = newQueryTracker();
|
|
433
|
+
const segments = metadataSegmentsOf(mod);
|
|
434
|
+
const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, async () => {
|
|
435
|
+
const props = buildProps(req, tracker);
|
|
436
|
+
if (!segments)
|
|
437
|
+
return renderToStringAsync(jsx(Component, props));
|
|
438
|
+
// generateMetadata runs next to the render, in the same request
|
|
439
|
+
// and cache scope: its fetches share the data cache with the
|
|
440
|
+
// page's, and the tags it declares are recorded on the entry.
|
|
441
|
+
const [head, body] = await Promise.all([
|
|
442
|
+
metadataHeadTags(segments, { params: props.params ?? thenableRecord({}), searchParams: props.searchParams }),
|
|
443
|
+
renderToStringAsync(jsx(Component, props)),
|
|
444
|
+
]);
|
|
445
|
+
return head ? HEAD_OPEN + head + HEAD_CLOSE + body : body;
|
|
446
|
+
}, tracker)));
|
|
447
|
+
const response = {
|
|
448
|
+
html,
|
|
449
|
+
status: 200,
|
|
450
|
+
noStore: scope.noStore || invalidated,
|
|
451
|
+
};
|
|
452
|
+
// An uncacheable read (no-store) keeps the render out of the ISR cache, and
|
|
453
|
+
// a revalidation that landed mid-render means the HTML may be stale.
|
|
454
|
+
if (page.mode === "isr" && !scope.noStore && !invalidated) {
|
|
455
|
+
recordQueryReads(req, tracker);
|
|
456
|
+
await isrStore.set(pageKey(req), {
|
|
457
|
+
html,
|
|
458
|
+
timestamp: Date.now(),
|
|
459
|
+
params: req.params,
|
|
460
|
+
query: req.query,
|
|
461
|
+
tags: scope.tags.size ? [...scope.tags] : undefined,
|
|
462
|
+
revalidate: scope.revalidate || undefined,
|
|
463
|
+
});
|
|
464
|
+
opts.onIsrChange?.(false);
|
|
465
|
+
}
|
|
466
|
+
return response;
|
|
467
|
+
}
|
|
468
|
+
catch (err) {
|
|
469
|
+
const signal = renderSignal(err);
|
|
470
|
+
if (signal)
|
|
471
|
+
return signal;
|
|
472
|
+
const failure = describeFailure(err);
|
|
473
|
+
console.error(`[krate] Error rendering ${req.route} (digest ${failure.digest}):`, err);
|
|
474
|
+
return { html: "", status: 500, ...failure };
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// Single-flight background revalidation for stale-while-revalidate. While a
|
|
478
|
+
// revalidation for a given variant is in flight, concurrent requests share the
|
|
479
|
+
// same promise instead of stampeding the renderer.
|
|
480
|
+
const inFlightRevalidations = new Map();
|
|
481
|
+
function revalidateInBackground(page, req) {
|
|
482
|
+
const key = pageKey(req) ?? variantKey(req);
|
|
483
|
+
if (inFlightRevalidations.has(key))
|
|
484
|
+
return;
|
|
485
|
+
const p = (async () => {
|
|
486
|
+
try {
|
|
487
|
+
const rendered = await renderFresh(page, req);
|
|
488
|
+
if (rendered.status === 200) {
|
|
489
|
+
console.log(`[krate-ssr] Revalidated ${key} (SWR)`);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
catch (err) {
|
|
493
|
+
console.error(`[krate-ssr] SWR revalidation failed ${key}:`, err.message);
|
|
494
|
+
}
|
|
495
|
+
finally {
|
|
496
|
+
inFlightRevalidations.delete(key);
|
|
497
|
+
}
|
|
498
|
+
})();
|
|
499
|
+
inFlightRevalidations.set(key, p);
|
|
500
|
+
opts.background?.(p);
|
|
501
|
+
}
|
|
502
|
+
// Time-based ISR regeneration: re-render every cached variant of a route while
|
|
503
|
+
// keeping the entries in place. This is the non-destructive counterpart of
|
|
504
|
+
// /__krate/ssr/revalidate (which clears a route). The Go server's periodic ISR
|
|
505
|
+
// timer calls this so cached pages stay fresh without evicting dynamic
|
|
506
|
+
// variants - eviction would turn a request that should be a HIT into a MISS.
|
|
507
|
+
const inFlightRouteRefreshes = new Map();
|
|
508
|
+
function refreshRouteVariants(page) {
|
|
509
|
+
const running = inFlightRouteRefreshes.get(page.route);
|
|
510
|
+
if (running)
|
|
511
|
+
return running;
|
|
512
|
+
const p = (async () => {
|
|
513
|
+
try {
|
|
514
|
+
const variants = await isrStore.entriesForRoute(page.route);
|
|
515
|
+
let refreshed = 0;
|
|
516
|
+
for (const [key, entry] of variants) {
|
|
517
|
+
// A variant rendered within its own window is still fresh; re-rendering
|
|
518
|
+
// it on every tick would multiply the render load by the variant count
|
|
519
|
+
// and replace an entry a request has only just produced.
|
|
520
|
+
if (!entryStale(key, entry))
|
|
521
|
+
continue;
|
|
522
|
+
const req = {
|
|
523
|
+
route: page.route,
|
|
524
|
+
url: page.route,
|
|
525
|
+
method: "GET",
|
|
526
|
+
headers: {},
|
|
527
|
+
params: entry.params,
|
|
528
|
+
query: entry.query,
|
|
529
|
+
};
|
|
530
|
+
const rendered = await renderFresh(page, req);
|
|
531
|
+
if (rendered.status === 200)
|
|
532
|
+
refreshed++;
|
|
533
|
+
}
|
|
534
|
+
return refreshed;
|
|
535
|
+
}
|
|
536
|
+
finally {
|
|
537
|
+
inFlightRouteRefreshes.delete(page.route);
|
|
538
|
+
}
|
|
539
|
+
})();
|
|
540
|
+
inFlightRouteRefreshes.set(page.route, p);
|
|
541
|
+
return p;
|
|
542
|
+
}
|
|
543
|
+
async function renderPage(req) {
|
|
544
|
+
const page = findPage(req.route);
|
|
545
|
+
if (!page) {
|
|
546
|
+
return { html: "", status: 404, notFound: true };
|
|
547
|
+
}
|
|
548
|
+
// ISR: serve from cache with stale-while-revalidate.
|
|
549
|
+
if (page.mode === "isr") {
|
|
550
|
+
const interval = page.revalidate || 60;
|
|
551
|
+
pageIntervals.set(page.route, interval);
|
|
552
|
+
const key = pageKey(req);
|
|
553
|
+
const cached = key === null ? undefined : await isrStore.get(key);
|
|
554
|
+
if (key !== null && cached && !entryStale(key, cached)) {
|
|
555
|
+
return {
|
|
556
|
+
html: cached.html,
|
|
557
|
+
status: 200,
|
|
558
|
+
cached: true,
|
|
559
|
+
cacheStatus: "hit",
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
if (cached) {
|
|
563
|
+
// Entry is stale: serve it immediately and refresh in the background so
|
|
564
|
+
// the next request (and any concurrent ones) get fresh HTML. No stampede:
|
|
565
|
+
// revalidateInBackground is single-flight per variant key.
|
|
566
|
+
revalidateInBackground(page, req);
|
|
567
|
+
return {
|
|
568
|
+
html: cached.html,
|
|
569
|
+
status: 200,
|
|
570
|
+
cached: true,
|
|
571
|
+
cacheStatus: "stale",
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
const response = await renderFresh(page, req);
|
|
576
|
+
if (page.mode === "isr")
|
|
577
|
+
response.cacheStatus = "miss";
|
|
578
|
+
return response;
|
|
579
|
+
}
|
|
580
|
+
// Region rendering (static-first)
|
|
581
|
+
// The Go server owns the page: it serves the build-time static shell with the
|
|
582
|
+
// <!-suspense:ID-> markers and baked fallbacks, then asks the sidecar to render
|
|
583
|
+
// ONLY the page's dynamic regions. Each region is rendered by its compiled
|
|
584
|
+
// runtime component bundle (server-components/<Name>.runtime.js - an IIFE that
|
|
585
|
+
// defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
|
|
586
|
+
// so nothing is re-derived at request time.
|
|
587
|
+
function regionProps(region, req) {
|
|
588
|
+
const props = { ...(region.props || {}) };
|
|
589
|
+
if (req.params && Object.keys(req.params).length > 0)
|
|
590
|
+
props.params = req.params;
|
|
591
|
+
if (req.query && Object.keys(req.query).length > 0)
|
|
592
|
+
props.query = req.query;
|
|
593
|
+
return props;
|
|
594
|
+
}
|
|
595
|
+
// Bounded like the page cache, and with the same segmented eviction: a
|
|
596
|
+
// client minting params variants cannot push out the regions hit twice.
|
|
597
|
+
const REGION_CACHE_MAX = opts.maxCacheSize && opts.maxCacheSize > 0 ? opts.maxCacheSize : 512;
|
|
598
|
+
const regionCache = new SegmentedLRU(REGION_CACHE_MAX);
|
|
599
|
+
const inFlightRegionRevalidations = new Map();
|
|
600
|
+
function paramsKeyOf(params) {
|
|
601
|
+
return variantKey({ route: "", params });
|
|
602
|
+
}
|
|
603
|
+
function regionCacheGet(key) {
|
|
604
|
+
return regionCache.get(key);
|
|
605
|
+
}
|
|
606
|
+
function regionCacheSet(key, html, page, req, scope) {
|
|
607
|
+
regionCache.set(key, {
|
|
608
|
+
html,
|
|
609
|
+
timestamp: Date.now(),
|
|
610
|
+
route: page.route,
|
|
611
|
+
paramsKey: paramsKeyOf(req.params),
|
|
612
|
+
tags: scope && scope.tags.size ? [...scope.tags] : undefined,
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
// invalidateRegions removes region entries for a route (optionally one params
|
|
616
|
+
// variant) and/or entries whose render read one of tags.
|
|
617
|
+
function invalidateRegions(route, params, tags) {
|
|
618
|
+
const pkey = params ? paramsKeyOf(params) : null;
|
|
619
|
+
let n = 0;
|
|
620
|
+
for (const [key, e] of regionCache.entries()) {
|
|
621
|
+
const routeHit = route !== null && e.route === route && (pkey === null || e.paramsKey === pkey);
|
|
622
|
+
const tagHit = tags.length > 0 && !!e.tags && e.tags.some((t) => tags.includes(t));
|
|
623
|
+
if (routeHit || tagHit) {
|
|
624
|
+
regionCache.delete(key);
|
|
625
|
+
n++;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return n;
|
|
629
|
+
}
|
|
630
|
+
function clearRegionCache() {
|
|
631
|
+
regionCache.clear();
|
|
632
|
+
}
|
|
633
|
+
function clearRegionCacheForRoute(route) {
|
|
634
|
+
const prefix = route + "::";
|
|
635
|
+
for (const key of regionCache.keys()) {
|
|
636
|
+
if (key.startsWith(prefix))
|
|
637
|
+
regionCache.delete(key);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
// regionQueryReads is pageQueryReads for regions: which query keys renders of
|
|
641
|
+
// a region have read. A server component reads props.query through a tracking
|
|
642
|
+
// view; a runtime-bundle region gets the same view as an object (its wrapper
|
|
643
|
+
// only parses props when it is handed JSON), so neither is keyed by the whole
|
|
644
|
+
// query unless it enumerates it.
|
|
645
|
+
const regionQueryReads = new Map();
|
|
646
|
+
function regionBaseKey(page, regionId, req) {
|
|
647
|
+
return variantKey({ route: page.route + "::" + regionId, params: req.params });
|
|
648
|
+
}
|
|
649
|
+
// regionCacheKey is the cache key of a region render, or null when no render
|
|
650
|
+
// has shown which query keys the region reads and the request has a query.
|
|
651
|
+
function regionCacheKey(page, region, req) {
|
|
652
|
+
const base = regionBaseKey(page, region.id, req);
|
|
653
|
+
const reads = regionQueryReads.get(base);
|
|
654
|
+
if (!reads)
|
|
655
|
+
return hasQuery(req) ? null : base;
|
|
656
|
+
regionQueryReads.delete(base);
|
|
657
|
+
regionQueryReads.set(base, reads);
|
|
658
|
+
if (reads === "all")
|
|
659
|
+
return variantKey({ route: page.route + "::" + region.id, params: req.params, query: req.query });
|
|
660
|
+
const picked = {};
|
|
661
|
+
for (const k of [...reads].sort()) {
|
|
662
|
+
if (req.query && Object.prototype.hasOwnProperty.call(req.query, k))
|
|
663
|
+
picked[k] = req.query[k];
|
|
664
|
+
}
|
|
665
|
+
return variantKey({ route: page.route + "::" + region.id, params: req.params, query: picked });
|
|
666
|
+
}
|
|
667
|
+
// A region is not handed props.query when the query is empty, so a render of
|
|
668
|
+
// such a request cannot show what the region reads from it: only renders that
|
|
669
|
+
// had a query teach the cache. A bare request still caches (under the base
|
|
670
|
+
// key, which is right for any request that carries none of the keys the
|
|
671
|
+
// region reads), and a request with a query renders until a render of its own
|
|
672
|
+
// has recorded the reads.
|
|
673
|
+
function recordRegionQueryReads(page, regionId, req, t) {
|
|
674
|
+
if (!hasQuery(req))
|
|
675
|
+
return;
|
|
676
|
+
const base = regionBaseKey(page, regionId, req);
|
|
677
|
+
const cur = mergeReads(regionQueryReads.get(base), t);
|
|
678
|
+
regionQueryReads.delete(base);
|
|
679
|
+
regionQueryReads.set(base, cur);
|
|
680
|
+
if (regionQueryReads.size > PAGE_QUERY_READS_MAX) {
|
|
681
|
+
const oldest = regionQueryReads.keys().next().value;
|
|
682
|
+
if (oldest !== undefined)
|
|
683
|
+
regionQueryReads.delete(oldest);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
// regionInterval resolves a region's cache window: its own revalidate directive
|
|
687
|
+
// wins, else the page's ISR cadence; non-ISR pages with no directive are 0.
|
|
688
|
+
function regionInterval(page, region) {
|
|
689
|
+
if (region.revalidate && region.revalidate > 0)
|
|
690
|
+
return region.revalidate;
|
|
691
|
+
if (page.mode === "isr")
|
|
692
|
+
return page.revalidate || 60;
|
|
693
|
+
if (pprEnabled)
|
|
694
|
+
return pprRevalidate;
|
|
695
|
+
return 0;
|
|
696
|
+
}
|
|
697
|
+
async function renderRegionFresh(page, region, req, tracker) {
|
|
698
|
+
if (region.serverExport) {
|
|
699
|
+
const out = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderServerExport(page, region, req, tracker), tracker)));
|
|
700
|
+
return { html: out.result, scope: out.scope, invalidated: out.invalidated };
|
|
701
|
+
}
|
|
702
|
+
const render = opts.loadRuntimeRenderer(region.bundlePath);
|
|
703
|
+
const out = await withRenderTimeout(withCacheScope(page.route, () => render(runtimeProps(region, req, tracker))));
|
|
704
|
+
return { html: out.result, scope: out.scope, invalidated: out.invalidated };
|
|
705
|
+
}
|
|
706
|
+
// runtimeProps are the props of a runtime-bundle region. The baked props are
|
|
707
|
+
// handed over as a copy (the bundle may mutate what it gets, and the manifest
|
|
708
|
+
// must not change), and the query as a tracking view so the cache learns
|
|
709
|
+
// which keys the region reads. Without a tracker the props go as JSON.
|
|
710
|
+
function runtimeProps(region, req, tracker) {
|
|
711
|
+
const props = regionProps(region, req);
|
|
712
|
+
if (!tracker)
|
|
713
|
+
return JSON.stringify(props);
|
|
714
|
+
const hasQ = "query" in props;
|
|
715
|
+
delete props.query;
|
|
716
|
+
const copy = JSON.parse(JSON.stringify(props));
|
|
717
|
+
if (hasQ)
|
|
718
|
+
copy.query = trackedQuery(req.query, tracker);
|
|
719
|
+
return copy;
|
|
720
|
+
}
|
|
721
|
+
function regionCacheable(r) {
|
|
722
|
+
return !r.scope.noStore && !r.invalidated;
|
|
723
|
+
}
|
|
724
|
+
// renderServerExport renders an async server component region with the page's
|
|
725
|
+
// own server bundle, which exports the component under region.serverExport.
|
|
726
|
+
async function renderServerExport(page, region, req, tracker) {
|
|
727
|
+
const mod = await opts.loadPageModule(page);
|
|
728
|
+
const Comp = mod[region.serverExport];
|
|
729
|
+
if (typeof Comp !== "function") {
|
|
730
|
+
throw new Error(`server bundle for ${page.route} does not export ${region.serverExport}`);
|
|
731
|
+
}
|
|
732
|
+
const props = regionProps(region, req);
|
|
733
|
+
if (props.params && typeof props.params === "object")
|
|
734
|
+
props.params = thenableRecord(props.params);
|
|
735
|
+
if (tracker && props.query)
|
|
736
|
+
props.query = trackedQuery(req.query, tracker);
|
|
737
|
+
return renderToStringAsync(jsx(Comp, props));
|
|
738
|
+
}
|
|
739
|
+
function revalidateRegionInBackground(page, region, req, key) {
|
|
740
|
+
if (inFlightRegionRevalidations.has(key))
|
|
741
|
+
return;
|
|
742
|
+
const p = (async () => {
|
|
743
|
+
try {
|
|
744
|
+
const tracker = newQueryTracker();
|
|
745
|
+
const r = await renderRegionFresh(page, region, req, tracker);
|
|
746
|
+
if (regionCacheable(r)) {
|
|
747
|
+
recordRegionQueryReads(page, region.id, req, tracker);
|
|
748
|
+
regionCacheSet(regionCacheKey(page, region, req), r.html, page, req, r.scope);
|
|
749
|
+
}
|
|
750
|
+
console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
|
|
751
|
+
}
|
|
752
|
+
catch (err) {
|
|
753
|
+
console.error(`[krate-ssr] Region SWR revalidation failed ${key}:`, err.message);
|
|
754
|
+
}
|
|
755
|
+
finally {
|
|
756
|
+
inFlightRegionRevalidations.delete(key);
|
|
757
|
+
}
|
|
758
|
+
})();
|
|
759
|
+
inFlightRegionRevalidations.set(key, p);
|
|
760
|
+
opts.background?.(p);
|
|
761
|
+
}
|
|
762
|
+
// renderRegion renders one region, applying region-level ISR caching for ISR
|
|
763
|
+
// pages. Returns an NDJSON frame.
|
|
764
|
+
async function renderRegion(page, region, req) {
|
|
765
|
+
const frame = await renderRegionFrame(page, region, req);
|
|
766
|
+
// A server component region may render <Head> children: they move to the
|
|
767
|
+
// head of the response, like the page region's. The caches keep the html
|
|
768
|
+
// as rendered, so a hit is split the same way.
|
|
769
|
+
if (region.serverExport && frame.type === "region" && typeof frame.html === "string" && frame.html !== "") {
|
|
770
|
+
applyHead(frame, frame.html);
|
|
771
|
+
}
|
|
772
|
+
return frame;
|
|
773
|
+
}
|
|
774
|
+
async function renderRegionFrame(page, region, req) {
|
|
775
|
+
if (!region.bundlePath && !region.serverExport) {
|
|
776
|
+
return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle", fatal: !!page.serverComponents };
|
|
777
|
+
}
|
|
778
|
+
const key = regionCacheKey(page, region, req);
|
|
779
|
+
const interval = regionInterval(page, region);
|
|
780
|
+
const cacheable = interval > 0;
|
|
781
|
+
if (cacheable && key !== null) {
|
|
782
|
+
const cached = regionCacheGet(key);
|
|
783
|
+
const stale = cached && (Date.now() - cached.timestamp) / 1000 > interval;
|
|
784
|
+
if (cached && !stale) {
|
|
785
|
+
return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "hit" };
|
|
786
|
+
}
|
|
787
|
+
if (cached) {
|
|
788
|
+
revalidateRegionInBackground(page, region, req, key);
|
|
789
|
+
return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "stale" };
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
try {
|
|
793
|
+
const tracker = newQueryTracker();
|
|
794
|
+
const r = await renderRegionFresh(page, region, req, tracker);
|
|
795
|
+
const html = r.html;
|
|
796
|
+
if (cacheable && regionCacheable(r)) {
|
|
797
|
+
// The key is computed after the render: it has shown which query keys
|
|
798
|
+
// the region reads.
|
|
799
|
+
recordRegionQueryReads(page, region.id, req, tracker);
|
|
800
|
+
regionCacheSet(regionCacheKey(page, region, req), html, page, req, r.scope);
|
|
801
|
+
}
|
|
802
|
+
const frame = { type: "region", id: region.id, status: 200, html };
|
|
803
|
+
if (cacheable)
|
|
804
|
+
frame.cacheStatus = "miss";
|
|
805
|
+
if (r.scope.noStore || r.invalidated)
|
|
806
|
+
frame.noStore = true;
|
|
807
|
+
return frame;
|
|
808
|
+
}
|
|
809
|
+
catch (err) {
|
|
810
|
+
const signal = renderSignal(err);
|
|
811
|
+
if (signal) {
|
|
812
|
+
const frame = { type: "region", id: region.id, status: signal.status, html: "" };
|
|
813
|
+
if (signal.notFound)
|
|
814
|
+
frame.notFound = true;
|
|
815
|
+
if (signal.denied)
|
|
816
|
+
frame.denied = signal.denied;
|
|
817
|
+
if (signal.redirect)
|
|
818
|
+
frame.redirect = signal.redirect;
|
|
819
|
+
return frame;
|
|
820
|
+
}
|
|
821
|
+
const failure = describeFailure(err);
|
|
822
|
+
console.error(`[krate-ssr] Region render failed ${page.route}::${region.id} (digest ${failure.digest}):`, err);
|
|
823
|
+
// A server component region has no meaningful baked content, so its
|
|
824
|
+
// failure is fatal for the response (the Go server answers 500).
|
|
825
|
+
return { type: "error", id: region.id, status: 500, ...failure, fatal: !!(region.serverExport || page.serverComponents) };
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
// applyHead sets frame.html to html without its <Head> content and carries
|
|
829
|
+
// the title and head tags on the frame.
|
|
830
|
+
function applyHead(frame, html) {
|
|
831
|
+
const split = takeHead(html);
|
|
832
|
+
frame.html = split.html;
|
|
833
|
+
if (split.title !== "")
|
|
834
|
+
frame.title = split.title;
|
|
835
|
+
if (split.head !== "")
|
|
836
|
+
frame.head = split.head;
|
|
837
|
+
}
|
|
838
|
+
// renderPageRegion renders a coarse whole-page region (SSR/ISR pages whose
|
|
839
|
+
// entire body is request-time dynamic). It reuses renderPage so the page-level
|
|
840
|
+
// variant-aware ISR cache, stale-while-revalidate, and revalidation all apply.
|
|
841
|
+
// Returns an NDJSON region frame; the Go server splices html into the shell at
|
|
842
|
+
// the "page" marker and keeps the baked body when the render fails.
|
|
843
|
+
async function renderPageRegion(page, id, req) {
|
|
844
|
+
const result = await renderPage(req);
|
|
845
|
+
const frame = {
|
|
846
|
+
type: "region",
|
|
847
|
+
id,
|
|
848
|
+
kind: "page",
|
|
849
|
+
status: result.status || 200,
|
|
850
|
+
html: result.html || "",
|
|
851
|
+
};
|
|
852
|
+
if (result.cacheStatus)
|
|
853
|
+
frame.cacheStatus = result.cacheStatus;
|
|
854
|
+
if (result.notFound)
|
|
855
|
+
frame.notFound = true;
|
|
856
|
+
if (result.denied)
|
|
857
|
+
frame.denied = result.denied;
|
|
858
|
+
if (result.redirect)
|
|
859
|
+
frame.redirect = result.redirect;
|
|
860
|
+
if (result.error)
|
|
861
|
+
frame.error = result.error;
|
|
862
|
+
if (result.digest)
|
|
863
|
+
frame.digest = result.digest;
|
|
864
|
+
if (result.stack)
|
|
865
|
+
frame.stack = result.stack;
|
|
866
|
+
if (result.noStore)
|
|
867
|
+
frame.noStore = true;
|
|
868
|
+
if (page.serverComponents && frame.status >= 500)
|
|
869
|
+
frame.fatal = true;
|
|
870
|
+
// The page's <Head> children (title, meta, link, script) render in place;
|
|
871
|
+
// they move to the head of the response, so they are taken out of the body
|
|
872
|
+
// html rather than shown twice. The host replaces/merges them into the
|
|
873
|
+
// baked head (Go: build/headmerge.go, portable handler: head-tags.ts).
|
|
874
|
+
applyHead(frame, result.html || "");
|
|
875
|
+
return frame;
|
|
876
|
+
}
|
|
877
|
+
function stringList(v) {
|
|
878
|
+
return Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
|
|
879
|
+
}
|
|
880
|
+
// applyInternalOp applies one internal operation to this process's caches.
|
|
881
|
+
async function applyInternalOp(op, payload) {
|
|
882
|
+
switch (op) {
|
|
883
|
+
case "revalidate-route": {
|
|
884
|
+
const targetRoute = String(payload.route || "");
|
|
885
|
+
await isrStore.deleteRoute(targetRoute);
|
|
886
|
+
clearRegionCacheForRoute(targetRoute);
|
|
887
|
+
cacheRuntime().invalidate({});
|
|
888
|
+
opts.onIsrChange?.(true);
|
|
889
|
+
const page = findPage(targetRoute);
|
|
890
|
+
if (page) {
|
|
891
|
+
await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
|
|
892
|
+
}
|
|
893
|
+
return { ok: true };
|
|
894
|
+
}
|
|
895
|
+
case "refresh-route": {
|
|
896
|
+
const targetRoute = String(payload.route || "");
|
|
897
|
+
const page = findPage(targetRoute);
|
|
898
|
+
const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
|
|
899
|
+
clearRegionCacheForRoute(targetRoute);
|
|
900
|
+
return { ok: true, refreshed };
|
|
901
|
+
}
|
|
902
|
+
case "cache-invalidate": {
|
|
903
|
+
const tags = stringList(payload.tags);
|
|
904
|
+
const targets = Array.isArray(payload.targets)
|
|
905
|
+
? payload.targets.filter((t) => t && typeof t.route === "string")
|
|
906
|
+
: [];
|
|
907
|
+
// Path targets also drop the data their renders cached (implicit tag).
|
|
908
|
+
const dataTags = tags.concat(targets.map((t) => routeDataTag(t.route)));
|
|
909
|
+
const { dataEntries: localEntries } = cacheRuntime().invalidate({ tags: dataTags });
|
|
910
|
+
const dataEntries = localEntries + (await cacheRuntime().invalidateShared(dataTags));
|
|
911
|
+
let isrEntries = 0;
|
|
912
|
+
let regionEntries = 0;
|
|
913
|
+
for (const t of targets) {
|
|
914
|
+
const params = t.params && typeof t.params === "object" ? t.params : null;
|
|
915
|
+
isrEntries += params ? await isrStore.deleteVariant(t.route, params) : await isrStore.deleteRoute(t.route);
|
|
916
|
+
regionEntries += invalidateRegions(t.route, params, []);
|
|
917
|
+
}
|
|
918
|
+
if (tags.length) {
|
|
919
|
+
isrEntries += await isrStore.deleteTags(tags);
|
|
920
|
+
regionEntries += invalidateRegions(null, null, tags);
|
|
921
|
+
}
|
|
922
|
+
if (isrEntries > 0)
|
|
923
|
+
opts.onIsrChange?.(true);
|
|
924
|
+
return { ok: true, isrEntries, regionEntries, dataEntries };
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
return {
|
|
929
|
+
isrStore,
|
|
930
|
+
findPage,
|
|
931
|
+
renderPage,
|
|
932
|
+
renderRegion,
|
|
933
|
+
renderPageRegion,
|
|
934
|
+
applyInternalOp,
|
|
935
|
+
devInvalidate(route) {
|
|
936
|
+
void isrStore.deleteRoute(route);
|
|
937
|
+
clearRegionCache();
|
|
938
|
+
},
|
|
939
|
+
};
|
|
940
|
+
}
|