@krate/runtime 0.3.0-beta.5 → 0.3.0-beta.6
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/server-renderer.js +368 -180
- package/package.json +1 -1
package/dist/server-renderer.js
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
import http from "node:http";
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
|
+
import vm from "node:vm";
|
|
6
7
|
import { pathToFileURL } from "node:url";
|
|
7
|
-
import { renderToString
|
|
8
|
+
import { renderToString } from "./server.js";
|
|
8
9
|
// Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
|
|
9
10
|
// Must be called BEFORE the first write for it to take effect.
|
|
10
11
|
function setupStream(res) {
|
|
@@ -13,9 +14,23 @@ function setupStream(res) {
|
|
|
13
14
|
socket.setNoDelay(true);
|
|
14
15
|
}
|
|
15
16
|
}
|
|
16
|
-
// ── ISR Cache
|
|
17
|
+
// ── ISR Cache (variant-aware, SWR, persisted) ────────────────────────────────
|
|
18
|
+
// A page's cache key is the route plus its per-request variant (params +
|
|
19
|
+
// query). Two dynamic-route requests (e.g. /video/a and /video/b) render
|
|
20
|
+
// different HTML, so they must never share a cache slot.
|
|
21
|
+
function variantKey(req) {
|
|
22
|
+
const enc = (v) => Object.keys(v).sort().map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(v[k])}`).join("&");
|
|
23
|
+
const params = req.params ? enc(req.params) : "";
|
|
24
|
+
const query = req.query ? enc(req.query) : "";
|
|
25
|
+
let key = req.route;
|
|
26
|
+
if (params)
|
|
27
|
+
key += "?" + params;
|
|
28
|
+
if (query)
|
|
29
|
+
key += "#" + query;
|
|
30
|
+
return key;
|
|
31
|
+
}
|
|
17
32
|
class ISRCache {
|
|
18
|
-
constructor(maxSize =
|
|
33
|
+
constructor(maxSize = 512) {
|
|
19
34
|
this.cache = new Map();
|
|
20
35
|
this.revalidationIntervals = new Map(); // route → seconds
|
|
21
36
|
this.maxSize = maxSize;
|
|
@@ -23,26 +38,91 @@ class ISRCache {
|
|
|
23
38
|
setRevalidation(route, seconds) {
|
|
24
39
|
this.revalidationIntervals.set(route, seconds);
|
|
25
40
|
}
|
|
26
|
-
get(
|
|
27
|
-
return this.cache.get(
|
|
41
|
+
get(key) {
|
|
42
|
+
return this.cache.get(key);
|
|
28
43
|
}
|
|
29
|
-
set(
|
|
44
|
+
set(key, entry) {
|
|
30
45
|
if (this.cache.size >= this.maxSize) {
|
|
31
46
|
const oldest = this.cache.keys().next().value;
|
|
32
47
|
if (oldest)
|
|
33
48
|
this.cache.delete(oldest);
|
|
34
49
|
}
|
|
35
|
-
this.cache.set(
|
|
50
|
+
this.cache.set(key, entry);
|
|
36
51
|
}
|
|
37
|
-
isStale(
|
|
38
|
-
const entry = this.cache.get(
|
|
52
|
+
isStale(key) {
|
|
53
|
+
const entry = this.cache.get(key);
|
|
54
|
+
const route = key.split("?")[0].split("#")[0];
|
|
39
55
|
const interval = this.revalidationIntervals.get(route);
|
|
40
56
|
if (!entry || !interval)
|
|
41
57
|
return false;
|
|
42
58
|
return (Date.now() - entry.timestamp) / 1000 > interval;
|
|
43
59
|
}
|
|
44
|
-
|
|
45
|
-
|
|
60
|
+
// deleteRoute removes every variant of a route (used by revalidation/invalidation).
|
|
61
|
+
deleteRoute(route) {
|
|
62
|
+
for (const key of [...this.cache.keys()]) {
|
|
63
|
+
if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
|
|
64
|
+
this.cache.delete(key);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
serialize() {
|
|
69
|
+
return {
|
|
70
|
+
entries: [...this.cache.entries()].map(([key, entry]) => ({ key, ...entry })),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
hydrate(data) {
|
|
74
|
+
if (!data || !Array.isArray(data.entries))
|
|
75
|
+
return;
|
|
76
|
+
for (const e of data.entries) {
|
|
77
|
+
if (e && typeof e.key === "string" && typeof e.html === "string") {
|
|
78
|
+
this.cache.set(e.key, {
|
|
79
|
+
html: e.html,
|
|
80
|
+
timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
|
|
81
|
+
headHTML: e.headHTML,
|
|
82
|
+
scriptHTML: e.scriptHTML,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const isrCache = new ISRCache();
|
|
89
|
+
// ISR cache persistence — survives renderer restarts so a bounce doesn't
|
|
90
|
+
// cold-render every ISR variant. Written debounced (coalesced) to the build
|
|
91
|
+
// output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
|
|
92
|
+
let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
|
|
93
|
+
let persistTimer = null;
|
|
94
|
+
function isrCachePath() {
|
|
95
|
+
return isrCacheFile || path.join(root, "dist", ".krate", "isr-cache.json");
|
|
96
|
+
}
|
|
97
|
+
function scheduleIsrPersist() {
|
|
98
|
+
if (persistTimer)
|
|
99
|
+
clearTimeout(persistTimer);
|
|
100
|
+
persistTimer = setTimeout(() => {
|
|
101
|
+
persistTimer = null;
|
|
102
|
+
try {
|
|
103
|
+
const data = isrCache.serialize();
|
|
104
|
+
const file = isrCachePath();
|
|
105
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
106
|
+
fs.writeFileSync(file, JSON.stringify(data));
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
console.error("[krate-ssr] ISR cache persist failed:", err.message);
|
|
110
|
+
}
|
|
111
|
+
}, 1000);
|
|
112
|
+
}
|
|
113
|
+
function loadIsrCache() {
|
|
114
|
+
try {
|
|
115
|
+
const file = isrCachePath();
|
|
116
|
+
if (fs.existsSync(file)) {
|
|
117
|
+
const data = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
118
|
+
isrCache.hydrate(data);
|
|
119
|
+
const n = isrCache.cache.size;
|
|
120
|
+
if (n > 0)
|
|
121
|
+
console.log(`[krate-ssr] Loaded ${n} persisted ISR entries`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
console.error("[krate-ssr] ISR cache load failed:", err.message);
|
|
46
126
|
}
|
|
47
127
|
}
|
|
48
128
|
// ── Page Module Loader ───────────────────────────────────────────────────────
|
|
@@ -74,7 +154,6 @@ async function loadPageModule(page) {
|
|
|
74
154
|
}
|
|
75
155
|
}
|
|
76
156
|
// ── Renderer ─────────────────────────────────────────────────────────────────
|
|
77
|
-
const isrCache = new ISRCache();
|
|
78
157
|
let manifest = null;
|
|
79
158
|
let projectRoot = "";
|
|
80
159
|
function findPage(route) {
|
|
@@ -90,46 +169,30 @@ function findPage(route) {
|
|
|
90
169
|
}
|
|
91
170
|
return page;
|
|
92
171
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
}
|
|
172
|
+
function buildProps(req) {
|
|
173
|
+
// Page-level data fetching (getStaticProps/getServerSideProps) has been
|
|
174
|
+
// removed; per-request data is provided by server components (@server),
|
|
175
|
+
// runtime components (@runtime), and middleware instead. Dynamic-route
|
|
176
|
+
// params and query parameters extracted by the Go server are forwarded so
|
|
177
|
+
// `({ params }) => ...` pages receive their real values at render time.
|
|
178
|
+
const props = {};
|
|
179
|
+
if (req.params)
|
|
180
|
+
props.params = req.params;
|
|
181
|
+
if (req.query)
|
|
182
|
+
props.query = req.query;
|
|
183
|
+
return props;
|
|
184
|
+
}
|
|
185
|
+
// renderFresh renders a page component and — for ISR pages — stores the result.
|
|
186
|
+
// Extracted so background revalidation shares exactly the same render path.
|
|
187
|
+
async function renderFresh(page, req) {
|
|
112
188
|
try {
|
|
113
189
|
const mod = await loadPageModule(page);
|
|
114
|
-
// Page-level data fetching (getStaticProps/getServerSideProps) has been
|
|
115
|
-
// removed; per-request data is provided by server components (@server),
|
|
116
|
-
// runtime components (@runtime), and middleware instead. Dynamic-route
|
|
117
|
-
// params and query parameters extracted by the Go server are forwarded so
|
|
118
|
-
// `({ params }) => ...` pages receive their real values at render time.
|
|
119
|
-
const props = {};
|
|
120
|
-
if (req.params)
|
|
121
|
-
props.params = req.params;
|
|
122
|
-
if (req.query)
|
|
123
|
-
props.query = req.query;
|
|
124
|
-
// Get the default export (the component)
|
|
125
190
|
const Component = mod.default;
|
|
126
191
|
if (!Component) {
|
|
127
192
|
return { html: "", status: 500 };
|
|
128
193
|
}
|
|
129
|
-
|
|
130
|
-
const jsxNode = Component(props);
|
|
194
|
+
const jsxNode = Component(buildProps(req));
|
|
131
195
|
const html = renderToString(jsxNode);
|
|
132
|
-
// Extract head/script content from the render
|
|
133
196
|
const headHTML = extractHeadHTML(html);
|
|
134
197
|
const scriptHTML = extractScriptHTML(html);
|
|
135
198
|
const response = {
|
|
@@ -138,14 +201,14 @@ async function renderPage(req) {
|
|
|
138
201
|
headHTML,
|
|
139
202
|
scriptHTML,
|
|
140
203
|
};
|
|
141
|
-
// ISR: cache the result
|
|
142
204
|
if (page.mode === "isr") {
|
|
143
|
-
isrCache.set(
|
|
205
|
+
isrCache.set(variantKey(req), {
|
|
144
206
|
html,
|
|
145
207
|
timestamp: Date.now(),
|
|
146
208
|
headHTML,
|
|
147
209
|
scriptHTML,
|
|
148
210
|
});
|
|
211
|
+
scheduleIsrPersist();
|
|
149
212
|
}
|
|
150
213
|
return response;
|
|
151
214
|
}
|
|
@@ -154,6 +217,205 @@ async function renderPage(req) {
|
|
|
154
217
|
return { html: "", status: 500 };
|
|
155
218
|
}
|
|
156
219
|
}
|
|
220
|
+
// Single-flight background revalidation for stale-while-revalidate. While a
|
|
221
|
+
// revalidation for a given variant is in flight, concurrent requests share the
|
|
222
|
+
// same promise instead of stampeding the renderer.
|
|
223
|
+
const inFlightRevalidations = new Map();
|
|
224
|
+
function revalidateInBackground(page, req) {
|
|
225
|
+
const key = variantKey(req);
|
|
226
|
+
if (inFlightRevalidations.has(key))
|
|
227
|
+
return;
|
|
228
|
+
const p = (async () => {
|
|
229
|
+
try {
|
|
230
|
+
const rendered = await renderFresh(page, req);
|
|
231
|
+
if (rendered.status === 200) {
|
|
232
|
+
console.log(`[krate-ssr] Revalidated ${key} (SWR)`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
console.error(`[krate-ssr] SWR revalidation failed ${key}:`, err.message);
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
inFlightRevalidations.delete(key);
|
|
240
|
+
}
|
|
241
|
+
})();
|
|
242
|
+
inFlightRevalidations.set(key, p);
|
|
243
|
+
}
|
|
244
|
+
async function renderPage(req) {
|
|
245
|
+
const page = findPage(req.route);
|
|
246
|
+
if (!page) {
|
|
247
|
+
return { html: "", status: 404, notFound: true };
|
|
248
|
+
}
|
|
249
|
+
// ISR: serve from cache with stale-while-revalidate.
|
|
250
|
+
if (page.mode === "isr") {
|
|
251
|
+
const interval = page.revalidate || 60;
|
|
252
|
+
isrCache.setRevalidation(page.route, interval);
|
|
253
|
+
const key = variantKey(req);
|
|
254
|
+
const cached = isrCache.get(key);
|
|
255
|
+
if (cached && !isrCache.isStale(key)) {
|
|
256
|
+
return {
|
|
257
|
+
html: cached.html,
|
|
258
|
+
status: 200,
|
|
259
|
+
headHTML: cached.headHTML,
|
|
260
|
+
scriptHTML: cached.scriptHTML,
|
|
261
|
+
cached: true,
|
|
262
|
+
cacheStatus: "hit",
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
if (cached) {
|
|
266
|
+
// Entry is stale: serve it immediately and refresh in the background so
|
|
267
|
+
// the next request (and any concurrent ones) get fresh HTML. No stampede:
|
|
268
|
+
// revalidateInBackground is single-flight per variant key.
|
|
269
|
+
revalidateInBackground(page, req);
|
|
270
|
+
return {
|
|
271
|
+
html: cached.html,
|
|
272
|
+
status: 200,
|
|
273
|
+
headHTML: cached.headHTML,
|
|
274
|
+
scriptHTML: cached.scriptHTML,
|
|
275
|
+
cached: true,
|
|
276
|
+
cacheStatus: "stale",
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const response = await renderFresh(page, req);
|
|
281
|
+
if (page.mode === "isr")
|
|
282
|
+
response.cacheStatus = "miss";
|
|
283
|
+
return response;
|
|
284
|
+
}
|
|
285
|
+
// ── Region rendering (static-first) ──────────────────────────────────────────
|
|
286
|
+
//
|
|
287
|
+
// The Go server owns the page: it serves the build-time static shell with the
|
|
288
|
+
// <!—suspense:ID—> markers and baked fallbacks, then asks the sidecar to render
|
|
289
|
+
// ONLY the page's dynamic regions. Each region is rendered by its compiled
|
|
290
|
+
// runtime component bundle (server-components/<Name>.runtime.js — an IIFE that
|
|
291
|
+
// defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
|
|
292
|
+
// so nothing is re-derived at request time.
|
|
293
|
+
const runtimeBundleCache = new Map();
|
|
294
|
+
// loadRuntimeRenderer loads a compiled runtime component bundle and returns its
|
|
295
|
+
// __krate_render(propsJSON) function. Bundles are cached by bundle path.
|
|
296
|
+
function loadRuntimeRenderer(relPath) {
|
|
297
|
+
const cached = runtimeBundleCache.get(relPath);
|
|
298
|
+
if (cached)
|
|
299
|
+
return cached;
|
|
300
|
+
const abs = path.resolve(root, "dist", relPath);
|
|
301
|
+
const code = fs.readFileSync(abs, "utf-8");
|
|
302
|
+
const ctx = vm.createContext({ console });
|
|
303
|
+
vm.runInContext(code, ctx, { filename: relPath });
|
|
304
|
+
const render = vm.runInContext("typeof globalThis.__krate_render === 'function' ? globalThis.__krate_render : typeof __krate_render === 'function' ? __krate_render : null", ctx);
|
|
305
|
+
if (typeof render !== "function") {
|
|
306
|
+
throw new Error(`Runtime bundle ${relPath} does not expose __krate_render`);
|
|
307
|
+
}
|
|
308
|
+
runtimeBundleCache.set(relPath, render);
|
|
309
|
+
return render;
|
|
310
|
+
}
|
|
311
|
+
function regionProps(region, req) {
|
|
312
|
+
const props = { ...(region.props || {}) };
|
|
313
|
+
if (req.params && Object.keys(req.params).length > 0)
|
|
314
|
+
props.params = req.params;
|
|
315
|
+
if (req.query && Object.keys(req.query).length > 0)
|
|
316
|
+
props.query = req.query;
|
|
317
|
+
return props;
|
|
318
|
+
}
|
|
319
|
+
// Region ISR cache: region-level stale-while-revalidate, separate from the
|
|
320
|
+
// page ISR cache. Region HTML only depends on the baked props, so it is fully
|
|
321
|
+
// determined by (route, region id, variant) and cacheable like a page variant.
|
|
322
|
+
const regionCache = new Map();
|
|
323
|
+
const regionRevalidation = new Map();
|
|
324
|
+
const inFlightRegionRevalidations = new Map();
|
|
325
|
+
function regionCacheKey(page, regionId, req) {
|
|
326
|
+
return variantKey({ route: page.route + "::" + regionId, params: req.params, query: req.query });
|
|
327
|
+
}
|
|
328
|
+
function renderRegionFresh(region, req) {
|
|
329
|
+
const render = loadRuntimeRenderer(region.bundlePath);
|
|
330
|
+
return render(JSON.stringify(regionProps(region, req)));
|
|
331
|
+
}
|
|
332
|
+
function revalidateRegionInBackground(page, region, req, key) {
|
|
333
|
+
if (inFlightRegionRevalidations.has(key))
|
|
334
|
+
return;
|
|
335
|
+
const p = (async () => {
|
|
336
|
+
try {
|
|
337
|
+
const html = renderRegionFresh(region, req);
|
|
338
|
+
regionCache.set(key, { html, timestamp: Date.now() });
|
|
339
|
+
console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
console.error(`[krate-ssr] Region SWR revalidation failed ${key}:`, err.message);
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
inFlightRegionRevalidations.delete(key);
|
|
346
|
+
}
|
|
347
|
+
})();
|
|
348
|
+
inFlightRegionRevalidations.set(key, p);
|
|
349
|
+
}
|
|
350
|
+
// renderRegion renders one region, applying region-level ISR caching for ISR
|
|
351
|
+
// pages. Returns an NDJSON frame.
|
|
352
|
+
async function renderRegion(page, region, req) {
|
|
353
|
+
if (!region.bundlePath) {
|
|
354
|
+
return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle" };
|
|
355
|
+
}
|
|
356
|
+
const key = regionCacheKey(page, region.id, req);
|
|
357
|
+
if (page.mode === "isr") {
|
|
358
|
+
const interval = page.revalidate || 60;
|
|
359
|
+
regionRevalidation.set(key, interval);
|
|
360
|
+
const cached = regionCache.get(key);
|
|
361
|
+
const stale = cached && (Date.now() - cached.timestamp) / 1000 > interval;
|
|
362
|
+
if (cached && !stale) {
|
|
363
|
+
return { type: "region", id: region.id, status: 200, html: cached.html, cached: true };
|
|
364
|
+
}
|
|
365
|
+
if (cached) {
|
|
366
|
+
revalidateRegionInBackground(page, region, req, key);
|
|
367
|
+
return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "stale" };
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
const html = renderRegionFresh(region, req);
|
|
372
|
+
if (page.mode === "isr") {
|
|
373
|
+
regionCache.set(key, { html, timestamp: Date.now() });
|
|
374
|
+
}
|
|
375
|
+
const frame = { type: "region", id: region.id, status: 200, html };
|
|
376
|
+
if (page.mode === "isr")
|
|
377
|
+
frame.cacheStatus = "miss";
|
|
378
|
+
return frame;
|
|
379
|
+
}
|
|
380
|
+
catch (err) {
|
|
381
|
+
console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err.message);
|
|
382
|
+
return { type: "error", id: region.id, status: 500, error: err.message };
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
function writeJsonLine(res, obj) {
|
|
386
|
+
res.write(JSON.stringify(obj) + "\n");
|
|
387
|
+
}
|
|
388
|
+
// renderPageRegion renders a coarse whole-page region (SSR/ISR pages whose
|
|
389
|
+
// entire body is request-time dynamic). It reuses renderPage so the page-level
|
|
390
|
+
// variant-aware ISR cache, stale-while-revalidate, and revalidation all apply.
|
|
391
|
+
// Returns an NDJSON region frame; the Go server splices html into the shell at
|
|
392
|
+
// the "page" marker and keeps the baked body when the render fails.
|
|
393
|
+
async function renderPageRegion(page, id, req) {
|
|
394
|
+
const result = await renderPage(req);
|
|
395
|
+
const frame = {
|
|
396
|
+
type: "region",
|
|
397
|
+
id,
|
|
398
|
+
kind: "page",
|
|
399
|
+
status: result.status || 200,
|
|
400
|
+
html: result.html || "",
|
|
401
|
+
};
|
|
402
|
+
if (result.cacheStatus)
|
|
403
|
+
frame.cacheStatus = result.cacheStatus;
|
|
404
|
+
if (result.notFound)
|
|
405
|
+
frame.notFound = true;
|
|
406
|
+
if (result.redirect)
|
|
407
|
+
frame.redirect = result.redirect;
|
|
408
|
+
// Title swap: the Go server replaces the baked <title> with the freshly
|
|
409
|
+
// rendered one so params-driven pages update the browser tab.
|
|
410
|
+
const title = extractTitle(result.html);
|
|
411
|
+
if (title !== "")
|
|
412
|
+
frame.title = title;
|
|
413
|
+
return frame;
|
|
414
|
+
}
|
|
415
|
+
function extractTitle(html) {
|
|
416
|
+
const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
417
|
+
return match ? match[1].trim() : "";
|
|
418
|
+
}
|
|
157
419
|
function extractHeadHTML(html) {
|
|
158
420
|
const match = html.match(/<!--head-start-->(.*?)<!--head-end-->/s);
|
|
159
421
|
return match ? match[1] : "";
|
|
@@ -185,6 +447,14 @@ else {
|
|
|
185
447
|
console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
|
|
186
448
|
}
|
|
187
449
|
}
|
|
450
|
+
loadIsrCache();
|
|
451
|
+
function parseBody(req) {
|
|
452
|
+
return new Promise((resolve) => {
|
|
453
|
+
let body = "";
|
|
454
|
+
req.on("data", (chunk) => (body += chunk));
|
|
455
|
+
req.on("end", () => resolve(body));
|
|
456
|
+
});
|
|
457
|
+
}
|
|
188
458
|
const server = http.createServer(async (req, res) => {
|
|
189
459
|
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
190
460
|
const route = url.pathname;
|
|
@@ -196,21 +466,14 @@ const server = http.createServer(async (req, res) => {
|
|
|
196
466
|
}
|
|
197
467
|
// ISR revalidation endpoint (called by Go server in background)
|
|
198
468
|
if (route === "/__krate/ssr/revalidate" && req.method === "POST") {
|
|
199
|
-
|
|
200
|
-
for await (const chunk of req)
|
|
201
|
-
body += chunk;
|
|
469
|
+
const body = await parseBody(req);
|
|
202
470
|
try {
|
|
203
471
|
const { route: targetRoute } = JSON.parse(body);
|
|
204
|
-
isrCache.
|
|
205
|
-
// Trigger re-render
|
|
472
|
+
isrCache.deleteRoute(targetRoute);
|
|
473
|
+
// Trigger re-render of the base variant.
|
|
206
474
|
const page = findPage(targetRoute);
|
|
207
475
|
if (page) {
|
|
208
|
-
await
|
|
209
|
-
route: targetRoute,
|
|
210
|
-
url: targetRoute,
|
|
211
|
-
method: "GET",
|
|
212
|
-
headers: {},
|
|
213
|
-
});
|
|
476
|
+
await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
|
|
214
477
|
}
|
|
215
478
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
216
479
|
res.end(JSON.stringify({ ok: true }));
|
|
@@ -223,13 +486,11 @@ const server = http.createServer(async (req, res) => {
|
|
|
223
486
|
}
|
|
224
487
|
// Module cache invalidation (called on file change in dev mode)
|
|
225
488
|
if (route === "/__krate/ssr/invalidate" && req.method === "POST") {
|
|
226
|
-
|
|
227
|
-
for await (const chunk of req)
|
|
228
|
-
body += chunk;
|
|
489
|
+
const body = await parseBody(req);
|
|
229
490
|
try {
|
|
230
491
|
const { route: targetRoute, source, bundlePath } = JSON.parse(body);
|
|
231
|
-
// Invalidate ISR cache for this route
|
|
232
|
-
isrCache.
|
|
492
|
+
// Invalidate ISR cache for this route (all variants)
|
|
493
|
+
isrCache.deleteRoute(targetRoute);
|
|
233
494
|
// Invalidate module cache for the source file or bundle
|
|
234
495
|
const key = bundlePath || source;
|
|
235
496
|
if (key && moduleCache.has(key)) {
|
|
@@ -245,12 +506,21 @@ const server = http.createServer(async (req, res) => {
|
|
|
245
506
|
}
|
|
246
507
|
return;
|
|
247
508
|
}
|
|
248
|
-
// ── /__krate/
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
509
|
+
// ── /__krate/regions — render ONLY a page's dynamic regions ───────────────
|
|
510
|
+
// One NDJSON frame per region, written as its own chunk so the Go server
|
|
511
|
+
// forwards each region progressively and splices it into the static shell.
|
|
512
|
+
// The Go server sends the splice markers it parsed from the shell; the
|
|
513
|
+
// sidecar renders each one (a component region from the manifest, or a
|
|
514
|
+
// coarse "page" region that renders the whole page component for SSR/ISR).
|
|
515
|
+
if (route === "/__krate/regions" && req.method === "POST") {
|
|
516
|
+
res.writeHead(200, {
|
|
517
|
+
"Content-Type": "application/x-ndjson; charset=utf-8",
|
|
518
|
+
"Cache-Control": "no-store",
|
|
519
|
+
"X-Content-Type-Options": "nosniff",
|
|
520
|
+
});
|
|
521
|
+
setupStream(res);
|
|
253
522
|
try {
|
|
523
|
+
const body = await parseBody(req);
|
|
254
524
|
const parsed = JSON.parse(body);
|
|
255
525
|
const renderReq = {
|
|
256
526
|
route: parsed.route,
|
|
@@ -259,73 +529,43 @@ const server = http.createServer(async (req, res) => {
|
|
|
259
529
|
headers: parsed.headers || {},
|
|
260
530
|
params: parsed.params,
|
|
261
531
|
query: parsed.query,
|
|
532
|
+
regions: parsed.regions,
|
|
262
533
|
};
|
|
263
534
|
const page = findPage(renderReq.route);
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
res
|
|
267
|
-
"Content-Type": "text/html; charset=utf-8",
|
|
268
|
-
"Transfer-Encoding": "chunked",
|
|
269
|
-
"X-Content-Type-Options": "nosniff",
|
|
270
|
-
});
|
|
271
|
-
setupStream(res);
|
|
272
|
-
const mod = await loadPageModule(page);
|
|
273
|
-
const Component = mod.default;
|
|
274
|
-
if (!Component) {
|
|
275
|
-
res.end();
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
// Per-request props (dynamic-route params + query) for both phases.
|
|
279
|
-
const props = {};
|
|
280
|
-
if (renderReq.params)
|
|
281
|
-
props.params = renderReq.params;
|
|
282
|
-
if (renderReq.query)
|
|
283
|
-
props.query = renderReq.query;
|
|
284
|
-
// Phase 1: Render with empty props → Suspense shows fallback
|
|
285
|
-
resetBoundaryCounter();
|
|
286
|
-
setStreamingResolved(false);
|
|
287
|
-
const fallbackJsx = Component(props);
|
|
288
|
-
const fallbackHtml = renderToString(fallbackJsx);
|
|
289
|
-
res.write(fallbackHtml);
|
|
290
|
-
// Phase 2: Re-render with resolved props (no data-fetching needed)
|
|
291
|
-
resetBoundaryCounter();
|
|
292
|
-
setStreamingResolved(true);
|
|
293
|
-
const resolvedJsx = Component(props);
|
|
294
|
-
const resolvedHtml = renderToString(resolvedJsx);
|
|
295
|
-
setStreamingResolved(false);
|
|
296
|
-
// Extract resolved content per Suspense boundary from markers
|
|
297
|
-
const resolvedMap = {};
|
|
298
|
-
const markerRe = /<!--suspense-resolved:(\d+)-->([\s\S]*?)<!--\/suspense-resolved:\1-->/g;
|
|
299
|
-
let m;
|
|
300
|
-
while ((m = markerRe.exec(resolvedHtml)) !== null) {
|
|
301
|
-
resolvedMap[m[1]] = m[2];
|
|
302
|
-
}
|
|
303
|
-
// Send targeted replacement script — only replaces fallback spans, preserves surrounding HTML
|
|
304
|
-
const script = `<script>(function(){var m=${JSON.stringify(resolvedMap)};Object.keys(m).forEach(function(id){var s=document.querySelector('span[data-suspense="'+id+'"]');if(s)s.outerHTML=m[id]});var t=document.querySelectorAll('template[data-suspense]');t.forEach(function(el){el.remove()})})()</script>`;
|
|
305
|
-
res.write(script);
|
|
535
|
+
if (!page) {
|
|
536
|
+
writeJsonLine(res, { type: "error", status: 404, error: "no such page" });
|
|
537
|
+
writeJsonLine(res, { type: "end", count: 0 });
|
|
306
538
|
res.end();
|
|
307
539
|
return;
|
|
308
540
|
}
|
|
309
|
-
//
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
"
|
|
314
|
-
});
|
|
315
|
-
res.end(JSON.stringify(result));
|
|
316
|
-
}
|
|
317
|
-
catch (err) {
|
|
318
|
-
console.error("[krate-ssr] Error in /__krate/render:", err.message);
|
|
319
|
-
if (res.headersSent) {
|
|
320
|
-
// Headers already sent (e.g. streaming mode) — write error inline
|
|
321
|
-
res.write(`<script>console.error("[krate-ssr]",${JSON.stringify(err.message)})</script>`);
|
|
322
|
-
res.end();
|
|
541
|
+
// Explicit splice list from Go wins. When absent (older Go server or
|
|
542
|
+
// direct calls), fall back to the manifest's component regions.
|
|
543
|
+
let regions = renderReq.regions || [];
|
|
544
|
+
if (regions.length === 0) {
|
|
545
|
+
regions = (manifest?.regions?.[page.route] || []).map((r) => ({ id: r.id, kind: "component" }));
|
|
323
546
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
547
|
+
for (const r of regions) {
|
|
548
|
+
if (r.kind === "page") {
|
|
549
|
+
writeJsonLine(res, await renderPageRegion(page, r.id, renderReq));
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
|
|
553
|
+
if (region) {
|
|
554
|
+
writeJsonLine(res, await renderRegion(page, region, renderReq));
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
// Unknown region id — keep the baked content by sending no frame.
|
|
558
|
+
writeJsonLine(res, { type: "skip", id: r.id });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
327
561
|
}
|
|
562
|
+
writeJsonLine(res, { type: "end", count: regions.length });
|
|
328
563
|
}
|
|
564
|
+
catch (err) {
|
|
565
|
+
console.error("[krate-ssr] Error in /__krate/regions:", err.message);
|
|
566
|
+
writeJsonLine(res, { type: "error", status: 500, error: err.message });
|
|
567
|
+
}
|
|
568
|
+
res.end();
|
|
329
569
|
return;
|
|
330
570
|
}
|
|
331
571
|
// ── Direct page requests (non-proxied) ──────────────────────────────────
|
|
@@ -375,64 +615,12 @@ const server = http.createServer(async (req, res) => {
|
|
|
375
615
|
}
|
|
376
616
|
return;
|
|
377
617
|
}
|
|
378
|
-
// Streaming SSR: two-phase render for direct requests
|
|
379
|
-
const streamingPage = manifest?.pages?.find((p) => p.route === route);
|
|
380
|
-
if (streamingPage?.mode === "streaming") {
|
|
381
|
-
try {
|
|
382
|
-
const mod = await loadPageModule(streamingPage);
|
|
383
|
-
const Component = mod.default;
|
|
384
|
-
if (!Component) {
|
|
385
|
-
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
386
|
-
res.end("<html><body><h1>500</h1></body></html>");
|
|
387
|
-
return;
|
|
388
|
-
}
|
|
389
|
-
res.writeHead(200, {
|
|
390
|
-
"Content-Type": "text/html; charset=utf-8",
|
|
391
|
-
"Transfer-Encoding": "chunked",
|
|
392
|
-
"X-Content-Type-Options": "nosniff",
|
|
393
|
-
});
|
|
394
|
-
setupStream(res);
|
|
395
|
-
// Phase 1: fallback
|
|
396
|
-
resetBoundaryCounter();
|
|
397
|
-
setStreamingResolved(false);
|
|
398
|
-
const fallbackHtml = renderToString(Component({}));
|
|
399
|
-
res.write(fallbackHtml);
|
|
400
|
-
// Phase 2: re-render with resolved props (no data-fetching needed)
|
|
401
|
-
resetBoundaryCounter();
|
|
402
|
-
setStreamingResolved(true);
|
|
403
|
-
const resolvedHtml = renderToString(Component({}));
|
|
404
|
-
setStreamingResolved(false);
|
|
405
|
-
// Extract resolved content per Suspense boundary from markers
|
|
406
|
-
const resolvedMap = {};
|
|
407
|
-
const markerRe = /<!--suspense-resolved:(\d+)-->([\s\S]*?)<!--\/suspense-resolved:\1-->/g;
|
|
408
|
-
let m;
|
|
409
|
-
while ((m = markerRe.exec(resolvedHtml)) !== null) {
|
|
410
|
-
resolvedMap[m[1]] = m[2];
|
|
411
|
-
}
|
|
412
|
-
const script = `<script>(function(){var m=${JSON.stringify(resolvedMap)};Object.keys(m).forEach(function(id){var s=document.querySelector('span[data-suspense="'+id+'"]');if(s)s.outerHTML=m[id]});var t=document.querySelectorAll('template[data-suspense]');t.forEach(function(el){el.remove()})})()</script>`;
|
|
413
|
-
res.write(script);
|
|
414
|
-
res.end();
|
|
415
|
-
return;
|
|
416
|
-
}
|
|
417
|
-
catch (err) {
|
|
418
|
-
console.error("[krate-ssr] Error in streaming direct render:", err.message);
|
|
419
|
-
if (res.headersSent) {
|
|
420
|
-
res.write(`<script>console.error("[krate-ssr]",${JSON.stringify(err.message)})</script>`);
|
|
421
|
-
res.end();
|
|
422
|
-
}
|
|
423
|
-
else {
|
|
424
|
-
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
425
|
-
res.end("<html><body><h1>Internal Server Error</h1></body></html>");
|
|
426
|
-
}
|
|
427
|
-
return;
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
618
|
// Regular SSR/ISR response
|
|
431
619
|
const headers_extra = {
|
|
432
620
|
"Content-Type": "text/html; charset=utf-8",
|
|
433
621
|
};
|
|
434
622
|
if (result.cached) {
|
|
435
|
-
headers_extra["X-Krate-Cache"] = "HIT";
|
|
623
|
+
headers_extra["X-Krate-Cache"] = result.cacheStatus === "stale" ? "STALE" : "HIT";
|
|
436
624
|
}
|
|
437
625
|
res.writeHead(result.status, headers_extra);
|
|
438
626
|
res.end(result.html);
|
package/package.json
CHANGED