@krate/runtime 0.3.0-beta.4 → 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.
@@ -164,8 +164,10 @@ declare global {
164
164
  interface DOMAttributes {
165
165
  children?: unknown[] | unknown;
166
166
  key?: string | number;
167
- /** Assigns the mounted DOM element. Pass a mutable holder (`ref={myRef}`) or a callback (`ref={el => ...}`). */
168
- ref?: ((el: Element) => void) | Element | null;
167
+ /** Assigns the mounted DOM element. Pass a mutable holder (`ref={myRef}`), a callback (`ref={el => ...}`), or an element. */
168
+ ref?: ((el: Element) => void) | {
169
+ current: Element | null;
170
+ } | Element | null;
169
171
  slot?: string;
170
172
  style?: CSSProperties | string;
171
173
  part?: string;
@@ -611,7 +613,9 @@ declare global {
611
613
  interface SVGAttributes extends AriaAttributes {
612
614
  children?: unknown[] | unknown;
613
615
  key?: string | number;
614
- ref?: ((el: Element) => void) | Element | null;
616
+ ref?: ((el: Element) => void) | {
617
+ current: Element | null;
618
+ } | Element | null;
615
619
  style?: CSSProperties | string;
616
620
  class?: string;
617
621
  className?: string;
@@ -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, setStreamingResolved, resetBoundaryCounter } from "./server.js";
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 = 128) {
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(route) {
27
- return this.cache.get(route);
41
+ get(key) {
42
+ return this.cache.get(key);
28
43
  }
29
- set(route, entry) {
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(route, entry);
50
+ this.cache.set(key, entry);
36
51
  }
37
- isStale(route) {
38
- const entry = this.cache.get(route);
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
- delete(route) {
45
- this.cache.delete(route);
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,41 +169,30 @@ function findPage(route) {
90
169
  }
91
170
  return page;
92
171
  }
93
- async function renderPage(req) {
94
- const page = findPage(req.route);
95
- if (!page) {
96
- return { html: "", status: 404, notFound: true };
97
- }
98
- // ISR: serve from cache if available and not stale
99
- if (page.mode === "isr") {
100
- isrCache.setRevalidation(page.route, page.revalidate || 60);
101
- const cached = isrCache.get(page.route);
102
- if (cached && !isrCache.isStale(page.route)) {
103
- return {
104
- html: cached.html,
105
- status: 200,
106
- headHTML: cached.headHTML,
107
- scriptHTML: cached.scriptHTML,
108
- cached: true,
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. The default export
117
- // is rendered here with no injected page props.
118
- const props = {};
119
- // Get the default export (the component)
120
190
  const Component = mod.default;
121
191
  if (!Component) {
122
192
  return { html: "", status: 500 };
123
193
  }
124
- // Render the component to HTML
125
- const jsxNode = Component(props);
194
+ const jsxNode = Component(buildProps(req));
126
195
  const html = renderToString(jsxNode);
127
- // Extract head/script content from the render
128
196
  const headHTML = extractHeadHTML(html);
129
197
  const scriptHTML = extractScriptHTML(html);
130
198
  const response = {
@@ -133,14 +201,14 @@ async function renderPage(req) {
133
201
  headHTML,
134
202
  scriptHTML,
135
203
  };
136
- // ISR: cache the result
137
204
  if (page.mode === "isr") {
138
- isrCache.set(page.route, {
205
+ isrCache.set(variantKey(req), {
139
206
  html,
140
207
  timestamp: Date.now(),
141
208
  headHTML,
142
209
  scriptHTML,
143
210
  });
211
+ scheduleIsrPersist();
144
212
  }
145
213
  return response;
146
214
  }
@@ -149,6 +217,205 @@ async function renderPage(req) {
149
217
  return { html: "", status: 500 };
150
218
  }
151
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
+ }
152
419
  function extractHeadHTML(html) {
153
420
  const match = html.match(/<!--head-start-->(.*?)<!--head-end-->/s);
154
421
  return match ? match[1] : "";
@@ -180,6 +447,14 @@ else {
180
447
  console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
181
448
  }
182
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
+ }
183
458
  const server = http.createServer(async (req, res) => {
184
459
  const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
185
460
  const route = url.pathname;
@@ -191,21 +466,14 @@ const server = http.createServer(async (req, res) => {
191
466
  }
192
467
  // ISR revalidation endpoint (called by Go server in background)
193
468
  if (route === "/__krate/ssr/revalidate" && req.method === "POST") {
194
- let body = "";
195
- for await (const chunk of req)
196
- body += chunk;
469
+ const body = await parseBody(req);
197
470
  try {
198
471
  const { route: targetRoute } = JSON.parse(body);
199
- isrCache.delete(targetRoute);
200
- // Trigger re-render
472
+ isrCache.deleteRoute(targetRoute);
473
+ // Trigger re-render of the base variant.
201
474
  const page = findPage(targetRoute);
202
475
  if (page) {
203
- await renderPage({
204
- route: targetRoute,
205
- url: targetRoute,
206
- method: "GET",
207
- headers: {},
208
- });
476
+ await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
209
477
  }
210
478
  res.writeHead(200, { "Content-Type": "application/json" });
211
479
  res.end(JSON.stringify({ ok: true }));
@@ -218,13 +486,11 @@ const server = http.createServer(async (req, res) => {
218
486
  }
219
487
  // Module cache invalidation (called on file change in dev mode)
220
488
  if (route === "/__krate/ssr/invalidate" && req.method === "POST") {
221
- let body = "";
222
- for await (const chunk of req)
223
- body += chunk;
489
+ const body = await parseBody(req);
224
490
  try {
225
491
  const { route: targetRoute, source, bundlePath } = JSON.parse(body);
226
- // Invalidate ISR cache for this route
227
- isrCache.delete(targetRoute);
492
+ // Invalidate ISR cache for this route (all variants)
493
+ isrCache.deleteRoute(targetRoute);
228
494
  // Invalidate module cache for the source file or bundle
229
495
  const key = bundlePath || source;
230
496
  if (key && moduleCache.has(key)) {
@@ -240,12 +506,21 @@ const server = http.createServer(async (req, res) => {
240
506
  }
241
507
  return;
242
508
  }
243
- // ── /__krate/render — called by Go server for SSR/ISR/Streaming ──────────
244
- if (route === "/__krate/render" && req.method === "POST") {
245
- let body = "";
246
- for await (const chunk of req)
247
- body += chunk;
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);
248
522
  try {
523
+ const body = await parseBody(req);
249
524
  const parsed = JSON.parse(body);
250
525
  const renderReq = {
251
526
  route: parsed.route,
@@ -254,67 +529,43 @@ const server = http.createServer(async (req, res) => {
254
529
  headers: parsed.headers || {},
255
530
  params: parsed.params,
256
531
  query: parsed.query,
532
+ regions: parsed.regions,
257
533
  };
258
534
  const page = findPage(renderReq.route);
259
- // Streaming mode: two-phase render for real Suspense fallback
260
- if (page?.mode === "streaming") {
261
- res.writeHead(200, {
262
- "Content-Type": "text/html; charset=utf-8",
263
- "Transfer-Encoding": "chunked",
264
- "X-Content-Type-Options": "nosniff",
265
- });
266
- setupStream(res);
267
- const mod = await loadPageModule(page);
268
- const Component = mod.default;
269
- if (!Component) {
270
- res.end();
271
- return;
272
- }
273
- // Phase 1: Render with empty props → Suspense shows fallback
274
- resetBoundaryCounter();
275
- setStreamingResolved(false);
276
- const fallbackJsx = Component({});
277
- const fallbackHtml = renderToString(fallbackJsx);
278
- res.write(fallbackHtml);
279
- // Phase 2: Re-render with resolved props (no data-fetching needed)
280
- resetBoundaryCounter();
281
- setStreamingResolved(true);
282
- const resolvedJsx = Component({});
283
- const resolvedHtml = renderToString(resolvedJsx);
284
- setStreamingResolved(false);
285
- // Extract resolved content per Suspense boundary from markers
286
- const resolvedMap = {};
287
- const markerRe = /<!--suspense-resolved:(\d+)-->([\s\S]*?)<!--\/suspense-resolved:\1-->/g;
288
- let m;
289
- while ((m = markerRe.exec(resolvedHtml)) !== null) {
290
- resolvedMap[m[1]] = m[2];
291
- }
292
- // Send targeted replacement script — only replaces fallback spans, preserves surrounding HTML
293
- 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>`;
294
- res.write(script);
535
+ if (!page) {
536
+ writeJsonLine(res, { type: "error", status: 404, error: "no such page" });
537
+ writeJsonLine(res, { type: "end", count: 0 });
295
538
  res.end();
296
539
  return;
297
540
  }
298
- // SSR/ISR: standard single-phase render
299
- const result = await renderPage(renderReq);
300
- // Return JSON response
301
- res.writeHead(result.status, {
302
- "Content-Type": "application/json; charset=utf-8",
303
- });
304
- res.end(JSON.stringify(result));
305
- }
306
- catch (err) {
307
- console.error("[krate-ssr] Error in /__krate/render:", err.message);
308
- if (res.headersSent) {
309
- // Headers already sent (e.g. streaming mode) — write error inline
310
- res.write(`<script>console.error("[krate-ssr]",${JSON.stringify(err.message)})</script>`);
311
- 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" }));
312
546
  }
313
- else {
314
- res.writeHead(500, { "Content-Type": "application/json" });
315
- res.end(JSON.stringify({ html: "", status: 500 }));
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
+ }
316
561
  }
562
+ writeJsonLine(res, { type: "end", count: regions.length });
317
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();
318
569
  return;
319
570
  }
320
571
  // ── Direct page requests (non-proxied) ──────────────────────────────────
@@ -364,64 +615,12 @@ const server = http.createServer(async (req, res) => {
364
615
  }
365
616
  return;
366
617
  }
367
- // Streaming SSR: two-phase render for direct requests
368
- const streamingPage = manifest?.pages?.find((p) => p.route === route);
369
- if (streamingPage?.mode === "streaming") {
370
- try {
371
- const mod = await loadPageModule(streamingPage);
372
- const Component = mod.default;
373
- if (!Component) {
374
- res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
375
- res.end("<html><body><h1>500</h1></body></html>");
376
- return;
377
- }
378
- res.writeHead(200, {
379
- "Content-Type": "text/html; charset=utf-8",
380
- "Transfer-Encoding": "chunked",
381
- "X-Content-Type-Options": "nosniff",
382
- });
383
- setupStream(res);
384
- // Phase 1: fallback
385
- resetBoundaryCounter();
386
- setStreamingResolved(false);
387
- const fallbackHtml = renderToString(Component({}));
388
- res.write(fallbackHtml);
389
- // Phase 2: re-render with resolved props (no data-fetching needed)
390
- resetBoundaryCounter();
391
- setStreamingResolved(true);
392
- const resolvedHtml = renderToString(Component({}));
393
- setStreamingResolved(false);
394
- // Extract resolved content per Suspense boundary from markers
395
- const resolvedMap = {};
396
- const markerRe = /<!--suspense-resolved:(\d+)-->([\s\S]*?)<!--\/suspense-resolved:\1-->/g;
397
- let m;
398
- while ((m = markerRe.exec(resolvedHtml)) !== null) {
399
- resolvedMap[m[1]] = m[2];
400
- }
401
- 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>`;
402
- res.write(script);
403
- res.end();
404
- return;
405
- }
406
- catch (err) {
407
- console.error("[krate-ssr] Error in streaming direct render:", err.message);
408
- if (res.headersSent) {
409
- res.write(`<script>console.error("[krate-ssr]",${JSON.stringify(err.message)})</script>`);
410
- res.end();
411
- }
412
- else {
413
- res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
414
- res.end("<html><body><h1>Internal Server Error</h1></body></html>");
415
- }
416
- return;
417
- }
418
- }
419
618
  // Regular SSR/ISR response
420
619
  const headers_extra = {
421
620
  "Content-Type": "text/html; charset=utf-8",
422
621
  };
423
622
  if (result.cached) {
424
- headers_extra["X-Krate-Cache"] = "HIT";
623
+ headers_extra["X-Krate-Cache"] = result.cacheStatus === "stale" ? "STALE" : "HIT";
425
624
  }
426
625
  res.writeHead(result.status, headers_extra);
427
626
  res.end(result.html);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.3.0-beta.4",
3
+ "version": "0.3.0-beta.6",
4
4
  "description": "Client-side runtime for Krate — signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",