@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.4

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.
Files changed (105) hide show
  1. package/dist/action-context.d.ts +56 -0
  2. package/dist/action-context.js +73 -0
  3. package/dist/action-context.test.d.ts +1 -0
  4. package/dist/action-context.test.js +47 -0
  5. package/dist/actions.d.ts +120 -0
  6. package/dist/actions.js +550 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +417 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/cache-scope.d.ts +118 -0
  12. package/dist/cache-scope.js +311 -0
  13. package/dist/cache.d.ts +55 -0
  14. package/dist/cache.js +155 -0
  15. package/dist/cache.test.d.ts +1 -0
  16. package/dist/cache.test.js +217 -0
  17. package/dist/class-component.d.ts +66 -0
  18. package/dist/class-component.js +633 -0
  19. package/dist/class-component.test.d.ts +1 -0
  20. package/dist/class-component.test.js +411 -0
  21. package/dist/context.d.ts +13 -0
  22. package/dist/context.js +58 -32
  23. package/dist/context.test.d.ts +1 -0
  24. package/dist/context.test.js +57 -0
  25. package/dist/derived.test.d.ts +1 -0
  26. package/dist/derived.test.js +140 -0
  27. package/dist/discrete.test.d.ts +1 -0
  28. package/dist/discrete.test.js +100 -0
  29. package/dist/dom.d.ts +55 -0
  30. package/dist/dom.js +414 -63
  31. package/dist/effects.d.ts +88 -0
  32. package/dist/effects.js +790 -0
  33. package/dist/effects.test.d.ts +1 -0
  34. package/dist/effects.test.js +485 -0
  35. package/dist/events.d.ts +58 -0
  36. package/dist/events.js +503 -0
  37. package/dist/events.test.d.ts +1 -0
  38. package/dist/events.test.js +447 -0
  39. package/dist/index.d.ts +14 -4
  40. package/dist/index.js +9 -3
  41. package/dist/jsx-types.d.ts +2 -0
  42. package/dist/krate-hydrate-lite.js +7 -1
  43. package/dist/krate-hydrate.js +7 -1
  44. package/dist/krate-runtime.js +7 -1
  45. package/dist/krate-suspense.js +2 -0
  46. package/dist/lanes.test.d.ts +1 -0
  47. package/dist/lanes.test.js +59 -0
  48. package/dist/list.d.ts +20 -0
  49. package/dist/list.js +466 -0
  50. package/dist/list.test.d.ts +1 -0
  51. package/dist/list.test.js +344 -0
  52. package/dist/optimistic-lanes.test.d.ts +1 -0
  53. package/dist/optimistic-lanes.test.js +45 -0
  54. package/dist/portal.d.ts +47 -0
  55. package/dist/portal.js +189 -0
  56. package/dist/portal.test.d.ts +1 -0
  57. package/dist/portal.test.js +99 -0
  58. package/dist/react-effects.test.d.ts +1 -0
  59. package/dist/react-effects.test.js +96 -0
  60. package/dist/react-suspense.test.d.ts +1 -0
  61. package/dist/react-suspense.test.js +194 -0
  62. package/dist/react.d.ts +132 -32
  63. package/dist/react.js +335 -81
  64. package/dist/react.test.js +12 -2
  65. package/dist/reconcile.js +13 -0
  66. package/dist/refs.d.ts +33 -0
  67. package/dist/refs.js +142 -0
  68. package/dist/refs.test.d.ts +1 -0
  69. package/dist/refs.test.js +257 -0
  70. package/dist/request-context.d.ts +62 -0
  71. package/dist/request-context.js +107 -0
  72. package/dist/resource.js +20 -1
  73. package/dist/router-layout.test.d.ts +1 -0
  74. package/dist/router-layout.test.js +179 -0
  75. package/dist/router-lite.d.ts +25 -0
  76. package/dist/router-lite.js +73 -0
  77. package/dist/router-nav.test.d.ts +1 -0
  78. package/dist/router-nav.test.js +399 -0
  79. package/dist/router-slots.test.d.ts +1 -0
  80. package/dist/router-slots.test.js +144 -0
  81. package/dist/router.d.ts +66 -2
  82. package/dist/router.js +1535 -650
  83. package/dist/server-async.test.d.ts +1 -0
  84. package/dist/server-async.test.js +174 -0
  85. package/dist/server-renderer.js +494 -119
  86. package/dist/server.d.ts +27 -1
  87. package/dist/server.js +187 -1
  88. package/dist/server.test.js +20 -0
  89. package/dist/signal-lanes.test.d.ts +1 -0
  90. package/dist/signal-lanes.test.js +32 -0
  91. package/dist/signal.d.ts +186 -1
  92. package/dist/signal.js +896 -66
  93. package/dist/slots.d.ts +22 -0
  94. package/dist/slots.js +134 -0
  95. package/dist/slots.test.d.ts +1 -0
  96. package/dist/slots.test.js +169 -0
  97. package/dist/snapshots.test.d.ts +1 -0
  98. package/dist/snapshots.test.js +208 -0
  99. package/dist/suspense-actions.test.d.ts +1 -0
  100. package/dist/suspense-actions.test.js +72 -0
  101. package/dist/suspense.d.ts +220 -0
  102. package/dist/suspense.js +901 -0
  103. package/dist/suspense.test.d.ts +1 -0
  104. package/dist/suspense.test.js +518 -0
  105. package/package.json +5 -1
@@ -6,7 +6,30 @@ import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import vm from "node:vm";
8
8
  import { pathToFileURL } from "node:url";
9
- import { renderToString } from "./server.js";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { timingSafeEqual } from "node:crypto";
11
+ import { jsx, renderToStringAsync } from "./server.js";
12
+ import { isNotFoundSignal, parseCookieHeader, redirectTarget, thenableRecord, } from "./request-context.js";
13
+ import { cacheRuntime, installRenderStore, patchFetch, routeDataTag, withCacheScope, } from "./cache-scope.js";
14
+ // Render cache scopes (tags / revalidate windows read during a render) and the
15
+ // Next-style fetch data cache. Installed once per process; page bundles share
16
+ // the state through globalThis.
17
+ installRenderStore(new AsyncLocalStorage());
18
+ patchFetch();
19
+ // Shared secret for the mutating internal endpoints (/__krate/ssr/revalidate,
20
+ // /refresh, /invalidate, /cache-invalidate). Krate passes it from the Go host;
21
+ // a renderer started by hand without it keeps the endpoints open.
22
+ const INTERNAL_SECRET = process.env.KRATE_INTERNAL_SECRET || "";
23
+ function internalAuthorized(req) {
24
+ if (!INTERNAL_SECRET)
25
+ return true;
26
+ const got = req.headers["x-krate-internal"];
27
+ if (typeof got !== "string")
28
+ return false;
29
+ const a = Buffer.from(got);
30
+ const b = Buffer.from(INTERNAL_SECRET);
31
+ return a.length === b.length && timingSafeEqual(a, b);
32
+ }
10
33
  // Cluster across cores: page/region rendering is independent per request, so N
11
34
  // workers scale it past a single core. Krate sets KRATE_SSR_WORKERS from
12
35
  // ssr.rendererWorkers. Region/ISR caches are per-worker and ISR disk persistence
@@ -14,13 +37,63 @@ import { renderToString } from "./server.js";
14
37
  const SSR_WORKERS = Math.max(1, parseInt(process.env.KRATE_SSR_WORKERS || "1", 10) || 1);
15
38
  const isClusterPrimary = SSR_WORKERS > 1 && cluster.isPrimary;
16
39
  if (isClusterPrimary) {
40
+ // Node leaves scheduling to the OS on Windows (SCHED_NONE), where one
41
+ // worker tends to accept every connection. Round-robin keeps clustered
42
+ // caches - and therefore revalidation fan-out - reachable on every platform.
43
+ cluster.schedulingPolicy = cluster.SCHED_RR;
17
44
  for (let i = 0; i < SSR_WORKERS; i++)
18
45
  cluster.fork();
46
+ // Restart a worker that dies, after a short delay, but give up when they
47
+ // keep dying (a port that stays unbindable, a broken bundle) instead of
48
+ // forking forever. The delay also gives a briefly busy port time to free up.
49
+ const exits = [];
19
50
  cluster.on("exit", (worker) => {
20
51
  console.log(`[krate-ssr] worker ${worker.process.pid} exited; restarting`);
21
- cluster.fork();
52
+ const now = Date.now();
53
+ exits.push(now);
54
+ while (exits.length && now - exits[0] > 60000)
55
+ exits.shift();
56
+ if (exits.length > 100) {
57
+ console.error("[krate-ssr] workers keep exiting; giving up");
58
+ process.exit(1);
59
+ }
60
+ setTimeout(() => cluster.fork(), 100);
22
61
  });
23
62
  console.log(`[krate-ssr] primary supervising ${SSR_WORKERS} workers`);
63
+ const broadcasts = new Map();
64
+ const finish = (id) => {
65
+ const b = broadcasts.get(id);
66
+ if (!b || b.remaining.size > 0)
67
+ return;
68
+ broadcasts.delete(id);
69
+ if (b.origin.isConnected())
70
+ b.origin.send({ type: "krate:bcast-done", id, results: b.results });
71
+ };
72
+ cluster.on("message", (worker, msg) => {
73
+ if (!msg || typeof msg !== "object")
74
+ return;
75
+ if (msg.type === "krate:bcast") {
76
+ const live = Object.values(cluster.workers || {}).filter((w) => w && w.isConnected());
77
+ broadcasts.set(msg.id, { origin: worker, remaining: new Set(live.map((w) => w.id)), results: [] });
78
+ for (const w of live)
79
+ w.send({ type: "krate:apply", id: msg.id, op: msg.op, payload: msg.payload });
80
+ finish(msg.id);
81
+ }
82
+ else if (msg.type === "krate:applied") {
83
+ const b = broadcasts.get(msg.id);
84
+ if (!b)
85
+ return;
86
+ b.results.push(msg.result);
87
+ b.remaining.delete(worker.id);
88
+ finish(msg.id);
89
+ }
90
+ });
91
+ cluster.on("exit", (worker) => {
92
+ for (const [id, b] of broadcasts) {
93
+ if (b.remaining.delete(worker.id))
94
+ finish(id);
95
+ }
96
+ });
24
97
  }
25
98
  // Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
26
99
  // Must be called BEFORE the first write for it to take effect.
@@ -48,6 +121,7 @@ function variantKey(req) {
48
121
  class ISRCache {
49
122
  constructor(maxSize = 512) {
50
123
  this.cache = new Map();
124
+ this.byTag = new Map();
51
125
  this.revalidationIntervals = new Map(); // route → seconds
52
126
  this.maxSize = maxSize;
53
127
  }
@@ -58,28 +132,87 @@ class ISRCache {
58
132
  return this.cache.get(key);
59
133
  }
60
134
  set(key, entry) {
135
+ if (this.cache.has(key))
136
+ this.delete(key);
61
137
  if (this.cache.size >= this.maxSize) {
62
138
  const oldest = this.cache.keys().next().value;
63
139
  if (oldest)
64
- this.cache.delete(oldest);
140
+ this.delete(oldest);
65
141
  }
66
142
  this.cache.set(key, entry);
143
+ for (const t of entry.tags || []) {
144
+ let keys = this.byTag.get(t);
145
+ if (!keys)
146
+ this.byTag.set(t, (keys = new Set()));
147
+ keys.add(key);
148
+ }
149
+ }
150
+ delete(key) {
151
+ const entry = this.cache.get(key);
152
+ if (!entry)
153
+ return false;
154
+ this.cache.delete(key);
155
+ for (const t of entry.tags || []) {
156
+ const keys = this.byTag.get(t);
157
+ if (keys) {
158
+ keys.delete(key);
159
+ if (keys.size === 0)
160
+ this.byTag.delete(t);
161
+ }
162
+ }
163
+ return true;
164
+ }
165
+ get size() {
166
+ return this.cache.size;
67
167
  }
68
168
  isStale(key) {
69
169
  const entry = this.cache.get(key);
70
170
  const route = key.split("?")[0].split("#")[0];
71
- const interval = this.revalidationIntervals.get(route);
171
+ let interval = this.revalidationIntervals.get(route) || 0;
172
+ if (entry && entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval)) {
173
+ interval = entry.revalidate;
174
+ }
72
175
  if (!entry || !interval)
73
176
  return false;
74
177
  return (Date.now() - entry.timestamp) / 1000 > interval;
75
178
  }
76
179
  // deleteRoute removes every variant of a route (used by revalidation/invalidation).
77
180
  deleteRoute(route) {
181
+ let n = 0;
78
182
  for (const key of [...this.cache.keys()]) {
79
183
  if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
80
- this.cache.delete(key);
184
+ if (this.delete(key))
185
+ n++;
81
186
  }
82
187
  }
188
+ return n;
189
+ }
190
+ // deleteVariant removes one params variant of a route (every query variant
191
+ // of it), e.g. /blog/[slug] with {slug: "a"} for revalidatePath("/blog/a").
192
+ deleteVariant(route, params) {
193
+ const base = variantKey({ route, params });
194
+ let n = 0;
195
+ for (const key of [...this.cache.keys()]) {
196
+ if (key === base || key.startsWith(base + "#")) {
197
+ if (this.delete(key))
198
+ n++;
199
+ }
200
+ }
201
+ return n;
202
+ }
203
+ // deleteTags removes every entry whose render read one of tags.
204
+ deleteTags(tags) {
205
+ let n = 0;
206
+ for (const t of tags) {
207
+ const keys = this.byTag.get(t);
208
+ if (!keys)
209
+ continue;
210
+ for (const key of [...keys]) {
211
+ if (this.delete(key))
212
+ n++;
213
+ }
214
+ }
215
+ return n;
83
216
  }
84
217
  // entriesForRoute returns a snapshot of the cached variants for a route so a
85
218
  // background refresh can iterate them without mutating during iteration.
@@ -102,11 +235,13 @@ class ISRCache {
102
235
  return;
103
236
  for (const e of data.entries) {
104
237
  if (e && typeof e.key === "string" && typeof e.html === "string") {
105
- this.cache.set(e.key, {
238
+ this.set(e.key, {
106
239
  html: e.html,
107
240
  timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
108
241
  params: e.params && typeof e.params === "object" ? e.params : undefined,
109
242
  query: e.query && typeof e.query === "object" ? e.query : undefined,
243
+ tags: Array.isArray(e.tags) ? e.tags.filter((t) => typeof t === "string") : undefined,
244
+ revalidate: typeof e.revalidate === "number" ? e.revalidate : undefined,
110
245
  });
111
246
  }
112
247
  }
@@ -141,6 +276,23 @@ let persistTimer = null;
141
276
  function isrCachePath() {
142
277
  return isrCacheFile || path.join(root, "dist", ".krate", "isr-cache.json");
143
278
  }
279
+ function persistIsrNow() {
280
+ if (SSR_WORKERS > 1)
281
+ return;
282
+ if (persistTimer) {
283
+ clearTimeout(persistTimer);
284
+ persistTimer = null;
285
+ }
286
+ try {
287
+ const data = isrCache.serialize();
288
+ const file = isrCachePath();
289
+ fs.mkdirSync(path.dirname(file), { recursive: true });
290
+ fs.writeFileSync(file, JSON.stringify(data));
291
+ }
292
+ catch (err) {
293
+ console.error("[krate-ssr] ISR cache persist failed:", err.message);
294
+ }
295
+ }
144
296
  function scheduleIsrPersist() {
145
297
  // Clustered: multiple workers would race on the same cache file; keep the ISR
146
298
  // cache in memory only.
@@ -148,18 +300,7 @@ function scheduleIsrPersist() {
148
300
  return;
149
301
  if (persistTimer)
150
302
  clearTimeout(persistTimer);
151
- persistTimer = setTimeout(() => {
152
- persistTimer = null;
153
- try {
154
- const data = isrCache.serialize();
155
- const file = isrCachePath();
156
- fs.mkdirSync(path.dirname(file), { recursive: true });
157
- fs.writeFileSync(file, JSON.stringify(data));
158
- }
159
- catch (err) {
160
- console.error("[krate-ssr] ISR cache persist failed:", err.message);
161
- }
162
- }, 1000);
303
+ persistTimer = setTimeout(persistIsrNow, 1000);
163
304
  }
164
305
  function loadIsrCache() {
165
306
  try {
@@ -167,7 +308,7 @@ function loadIsrCache() {
167
308
  if (fs.existsSync(file)) {
168
309
  const data = JSON.parse(fs.readFileSync(file, "utf-8"));
169
310
  isrCache.hydrate(data);
170
- const n = isrCache.cache.size;
311
+ const n = isrCache.size;
171
312
  if (n > 0)
172
313
  console.log(`[krate-ssr] Loaded ${n} persisted ISR entries`);
173
314
  }
@@ -220,15 +361,63 @@ function findPage(route) {
220
361
  }
221
362
  return page;
222
363
  }
364
+ // Request scope for server components: headers()/cookies() from
365
+ // @krate/runtime/server read it through the global store symbol, so it works
366
+ // no matter which copy of the runtime a page bundle resolved.
367
+ const requestStore = (() => {
368
+ const key = Symbol.for("krate.request.store");
369
+ const g = globalThis;
370
+ if (!g[key])
371
+ g[key] = new AsyncLocalStorage();
372
+ return g[key];
373
+ })();
374
+ function requestContextFor(req) {
375
+ const h = new Headers();
376
+ for (const [k, v] of Object.entries(req.headers || {})) {
377
+ if (typeof v === "string") {
378
+ try {
379
+ h.set(k, v);
380
+ }
381
+ catch {
382
+ // skip header names the WHATWG Headers class rejects
383
+ }
384
+ }
385
+ }
386
+ return {
387
+ url: req.url || req.route,
388
+ method: req.method || "GET",
389
+ headers: h,
390
+ cookies: parseCookieHeader(h.get("cookie")),
391
+ params: { ...(req.params || {}) },
392
+ searchParams: { ...(req.query || {}) },
393
+ };
394
+ }
395
+ function withRequest(req, fn) {
396
+ return requestStore.run(requestContextFor(req), fn);
397
+ }
398
+ // renderSignal maps notFound()/redirect() thrown during a render to a response.
399
+ function renderSignal(err) {
400
+ if (isNotFoundSignal(err))
401
+ return { html: "", status: 404, notFound: true };
402
+ const to = redirectTarget(err);
403
+ if (to)
404
+ return { html: "", status: 307, redirect: to };
405
+ return null;
406
+ }
223
407
  function buildProps(req) {
224
408
  // Page-level data fetching (getStaticProps/getServerSideProps) has been
225
409
  // removed; per-request data is provided by server components (@server),
226
410
  // runtime components (@runtime), and middleware instead. Dynamic-route
227
411
  // params and query parameters extracted by the Go server are forwarded so
228
412
  // `({ params }) => ...` pages receive their real values at render time.
413
+ // params and searchParams are plain objects that can also be awaited, so
414
+ // both `params.slug` and Next.js 15's `const { slug } = await params` work.
415
+ // The Go server always forwards params (empty for static routes); a direct
416
+ // request without them keeps params undefined, as before.
229
417
  const props = {};
230
418
  if (req.params)
231
- props.params = req.params;
419
+ props.params = thenableRecord(req.params);
420
+ props.searchParams = thenableRecord(req.query);
232
421
  if (req.query)
233
422
  props.query = req.query;
234
423
  return props;
@@ -242,29 +431,37 @@ async function renderFresh(page, req) {
242
431
  if (!Component) {
243
432
  return { html: "", status: 500 };
244
433
  }
245
- const jsxNode = Component(buildProps(req));
246
- // Bound the render. renderToString is synchronous, so a page that blocks
247
- // would block the sidecar's event loop regardless; the timeout still
248
- // protects the request path when rendering is async (suspense/resource).
249
- const html = await withRenderTimeout(Promise.resolve(renderToString(jsxNode)));
434
+ // The render runs in a cache scope that records the tags / revalidate
435
+ // windows its data reads declared (fetch next options, unstable_cache).
436
+ // Async server components (and plain sync pages) render through
437
+ // renderToStringAsync inside the request scope. The timeout bounds slow
438
+ // awaits (fetch); a page that blocks synchronously still blocks the loop.
439
+ const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderToStringAsync(jsx(Component, buildProps(req))))));
250
440
  const response = {
251
441
  html,
252
442
  status: 200,
253
443
  };
254
- if (page.mode === "isr") {
444
+ // An uncacheable read (no-store) keeps the render out of the ISR cache, and
445
+ // a revalidation that landed mid-render means the HTML may be stale.
446
+ if (page.mode === "isr" && !scope.noStore && !invalidated) {
255
447
  isrCache.set(variantKey(req), {
256
448
  html,
257
449
  timestamp: Date.now(),
258
450
  params: req.params,
259
451
  query: req.query,
452
+ tags: scope.tags.size ? [...scope.tags] : undefined,
453
+ revalidate: scope.revalidate || undefined,
260
454
  });
261
455
  scheduleIsrPersist();
262
456
  }
263
457
  return response;
264
458
  }
265
459
  catch (err) {
460
+ const signal = renderSignal(err);
461
+ if (signal)
462
+ return signal;
266
463
  console.error(`[krate] Error rendering ${req.route}:`, err);
267
- return { html: "", status: 500 };
464
+ return { html: "", status: 500, error: (err && err.message) || String(err) };
268
465
  }
269
466
  }
270
467
  // Single-flight background revalidation for stale-while-revalidate. While a
@@ -380,7 +577,15 @@ function loadRuntimeRenderer(relPath) {
380
577
  return cached;
381
578
  const abs = path.resolve(root, "dist", relPath);
382
579
  const code = fs.readFileSync(abs, "utf-8");
383
- const ctx = vm.createContext({ console });
580
+ // Runtime components get the host's fetch (looked up per call, so a cache
581
+ // layer that wraps globalThis.fetch later still applies) and the web
582
+ // primitives that go with it.
583
+ const ctx = vm.createContext({
584
+ console,
585
+ fetch: (...args) => globalThis.fetch(...args),
586
+ Headers, Request, Response, URL, URLSearchParams, TextEncoder, TextDecoder,
587
+ setTimeout, clearTimeout, queueMicrotask, structuredClone, AbortController,
588
+ });
384
589
  vm.runInContext(code, ctx, { filename: relPath });
385
590
  const render = vm.runInContext("typeof globalThis.__krate_render === 'function' ? globalThis.__krate_render : typeof __krate_render === 'function' ? __krate_render : null", ctx);
386
591
  if (typeof render !== "function") {
@@ -397,22 +602,43 @@ function regionProps(region, req) {
397
602
  props.query = req.query;
398
603
  return props;
399
604
  }
400
- // Region ISR cache: region-level stale-while-revalidate, separate from the
401
- // page ISR cache. Region HTML only depends on the baked props, so it is fully
402
- // determined by (route, region id, variant) and cacheable like a page variant.
403
605
  const regionCache = new Map();
404
606
  const regionRevalidation = new Map();
405
607
  const inFlightRegionRevalidations = new Map();
406
608
  // Region cache is bounded (FIFO eviction) so a long-lived sidecar cannot grow
407
609
  // without limit across many dynamic region variants.
408
610
  const REGION_CACHE_MAX = parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512;
409
- function regionCacheSet(key, html) {
611
+ function paramsKeyOf(params) {
612
+ return variantKey({ route: "", params });
613
+ }
614
+ function regionCacheSet(key, html, page, req, scope) {
410
615
  if (regionCache.size >= REGION_CACHE_MAX && !regionCache.has(key)) {
411
616
  const oldest = regionCache.keys().next().value;
412
617
  if (oldest !== undefined)
413
618
  regionCache.delete(oldest);
414
619
  }
415
- regionCache.set(key, { html, timestamp: Date.now() });
620
+ regionCache.set(key, {
621
+ html,
622
+ timestamp: Date.now(),
623
+ route: page.route,
624
+ paramsKey: paramsKeyOf(req.params),
625
+ tags: scope && scope.tags.size ? [...scope.tags] : undefined,
626
+ });
627
+ }
628
+ // invalidateRegions removes region entries for a route (optionally one params
629
+ // variant) and/or entries whose render read one of tags.
630
+ function invalidateRegions(route, params, tags) {
631
+ const pkey = params ? paramsKeyOf(params) : null;
632
+ let n = 0;
633
+ for (const [key, e] of Array.from(regionCache.entries())) {
634
+ const routeHit = route !== null && e.route === route && (pkey === null || e.paramsKey === pkey);
635
+ const tagHit = tags.length > 0 && !!e.tags && e.tags.some((t) => tags.includes(t));
636
+ if (routeHit || tagHit) {
637
+ regionCache.delete(key);
638
+ n++;
639
+ }
640
+ }
641
+ return n;
416
642
  }
417
643
  function clearRegionCache() {
418
644
  regionCache.clear();
@@ -439,17 +665,39 @@ function regionInterval(page, region) {
439
665
  return pprRevalidate;
440
666
  return 0;
441
667
  }
442
- function renderRegionFresh(region, req) {
668
+ async function renderRegionFresh(page, region, req) {
669
+ if (region.serverExport) {
670
+ const out = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderServerExport(page, region, req))));
671
+ return { html: out.result, scope: out.scope, invalidated: out.invalidated };
672
+ }
443
673
  const render = loadRuntimeRenderer(region.bundlePath);
444
- return withRenderTimeout(Promise.resolve().then(() => render(JSON.stringify(regionProps(region, req)))));
674
+ const out = await withRenderTimeout(withCacheScope(page.route, () => render(JSON.stringify(regionProps(region, req)))));
675
+ return { html: out.result, scope: out.scope, invalidated: out.invalidated };
676
+ }
677
+ function regionCacheable(r) {
678
+ return !r.scope.noStore && !r.invalidated;
679
+ }
680
+ // renderServerExport renders an async server component region with the page's
681
+ // own server bundle, which exports the component under region.serverExport.
682
+ async function renderServerExport(page, region, req) {
683
+ const mod = await loadPageModule(page);
684
+ const Comp = mod[region.serverExport];
685
+ if (typeof Comp !== "function") {
686
+ throw new Error(`server bundle for ${page.route} does not export ${region.serverExport}`);
687
+ }
688
+ const props = regionProps(region, req);
689
+ if (props.params && typeof props.params === "object")
690
+ props.params = thenableRecord(props.params);
691
+ return renderToStringAsync(jsx(Comp, props));
445
692
  }
446
693
  function revalidateRegionInBackground(page, region, req, key) {
447
694
  if (inFlightRegionRevalidations.has(key))
448
695
  return;
449
696
  const p = (async () => {
450
697
  try {
451
- const html = await renderRegionFresh(region, req);
452
- regionCacheSet(key, html);
698
+ const r = await renderRegionFresh(page, region, req);
699
+ if (regionCacheable(r))
700
+ regionCacheSet(key, r.html, page, req, r.scope);
453
701
  console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
454
702
  }
455
703
  catch (err) {
@@ -464,8 +712,8 @@ function revalidateRegionInBackground(page, region, req, key) {
464
712
  // renderRegion renders one region, applying region-level ISR caching for ISR
465
713
  // pages. Returns an NDJSON frame.
466
714
  async function renderRegion(page, region, req) {
467
- if (!region.bundlePath) {
468
- return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle" };
715
+ if (!region.bundlePath && !region.serverExport) {
716
+ return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle", fatal: !!page.serverComponents };
469
717
  }
470
718
  const key = regionCacheKey(page, region.id, req);
471
719
  const interval = regionInterval(page, region);
@@ -483,9 +731,10 @@ async function renderRegion(page, region, req) {
483
731
  }
484
732
  }
485
733
  try {
486
- const html = await renderRegionFresh(region, req);
487
- if (cacheable) {
488
- regionCacheSet(key, html);
734
+ const r = await renderRegionFresh(page, region, req);
735
+ const html = r.html;
736
+ if (cacheable && regionCacheable(r)) {
737
+ regionCacheSet(key, html, page, req, r.scope);
489
738
  }
490
739
  const frame = { type: "region", id: region.id, status: 200, html };
491
740
  if (cacheable)
@@ -493,8 +742,19 @@ async function renderRegion(page, region, req) {
493
742
  return frame;
494
743
  }
495
744
  catch (err) {
496
- console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err.message);
497
- return { type: "error", id: region.id, status: 500, error: err.message };
745
+ const signal = renderSignal(err);
746
+ if (signal) {
747
+ const frame = { type: "region", id: region.id, status: signal.status, html: "" };
748
+ if (signal.notFound)
749
+ frame.notFound = true;
750
+ if (signal.redirect)
751
+ frame.redirect = signal.redirect;
752
+ return frame;
753
+ }
754
+ console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err);
755
+ // A server component region has no meaningful baked content, so its
756
+ // failure is fatal for the response (the Go server answers 500).
757
+ return { type: "error", id: region.id, status: 500, error: (err && err.message) || String(err), fatal: !!(region.serverExport || page.serverComponents) };
498
758
  }
499
759
  }
500
760
  function writeJsonLine(res, obj) {
@@ -520,6 +780,10 @@ async function renderPageRegion(page, id, req) {
520
780
  frame.notFound = true;
521
781
  if (result.redirect)
522
782
  frame.redirect = result.redirect;
783
+ if (result.error)
784
+ frame.error = result.error;
785
+ if (page.serverComponents && frame.status >= 500)
786
+ frame.fatal = true;
523
787
  // Title swap: the Go server replaces the baked <title> with the freshly
524
788
  // rendered one so params-driven pages update the browser tab.
525
789
  const title = extractTitle(result.html);
@@ -531,6 +795,133 @@ function extractTitle(html) {
531
795
  const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
532
796
  return match ? match[1].trim() : "";
533
797
  }
798
+ const INTERNAL_OPS = {
799
+ "/__krate/ssr/revalidate": "revalidate-route",
800
+ "/__krate/ssr/refresh": "refresh-route",
801
+ "/__krate/ssr/invalidate": "dev-invalidate",
802
+ "/__krate/ssr/cache-invalidate": "cache-invalidate",
803
+ };
804
+ function stringList(v) {
805
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
806
+ }
807
+ // applyInternalOp applies one internal operation to this process's caches.
808
+ async function applyInternalOp(op, payload) {
809
+ switch (op) {
810
+ case "revalidate-route": {
811
+ const targetRoute = String(payload.route || "");
812
+ isrCache.deleteRoute(targetRoute);
813
+ clearRegionCacheForRoute(targetRoute);
814
+ cacheRuntime().invalidate({});
815
+ persistIsrNow();
816
+ const page = findPage(targetRoute);
817
+ if (page) {
818
+ await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
819
+ }
820
+ return { ok: true };
821
+ }
822
+ case "refresh-route": {
823
+ const targetRoute = String(payload.route || "");
824
+ const page = findPage(targetRoute);
825
+ const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
826
+ clearRegionCacheForRoute(targetRoute);
827
+ return { ok: true, refreshed };
828
+ }
829
+ case "dev-invalidate": {
830
+ const { route: targetRoute, source, bundlePath } = payload;
831
+ // Invalidate ISR cache for this route (all variants)
832
+ isrCache.deleteRoute(targetRoute);
833
+ // Invalidate module cache for the source file or bundle
834
+ const key = bundlePath || source;
835
+ if (key && moduleCache.has(key)) {
836
+ moduleCache.delete(key);
837
+ console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
838
+ }
839
+ // Runtime component bundles are recompiled in place on a dev rebuild, but
840
+ // their render functions are cached for the process lifetime. Clear them
841
+ // so the next region render picks up the new code. Bundles are tiny and
842
+ // re-read on demand, so clearing all of them is cheap and avoids tracking
843
+ // which component maps to which route here.
844
+ runtimeBundleCache.clear();
845
+ clearRegionCache();
846
+ return { ok: true };
847
+ }
848
+ case "cache-invalidate": {
849
+ const tags = stringList(payload.tags);
850
+ const targets = Array.isArray(payload.targets)
851
+ ? payload.targets.filter((t) => t && typeof t.route === "string")
852
+ : [];
853
+ // Path targets also drop the data their renders cached (implicit tag).
854
+ const dataTags = tags.concat(targets.map((t) => routeDataTag(t.route)));
855
+ const { dataEntries } = cacheRuntime().invalidate({ tags: dataTags });
856
+ let isrEntries = 0;
857
+ let regionEntries = 0;
858
+ for (const t of targets) {
859
+ const params = t.params && typeof t.params === "object" ? t.params : null;
860
+ isrEntries += params ? isrCache.deleteVariant(t.route, params) : isrCache.deleteRoute(t.route);
861
+ regionEntries += invalidateRegions(t.route, params, []);
862
+ }
863
+ if (tags.length) {
864
+ isrEntries += isrCache.deleteTags(tags);
865
+ regionEntries += invalidateRegions(null, null, tags);
866
+ }
867
+ if (isrEntries > 0)
868
+ persistIsrNow();
869
+ return { ok: true, isrEntries, regionEntries, dataEntries };
870
+ }
871
+ }
872
+ }
873
+ // Cluster fan-out (worker side). broadcastInternalOp resolves with one result
874
+ // per live worker once every worker applied the operation.
875
+ let broadcastSeq = 0;
876
+ const broadcastWaiters = new Map();
877
+ if (cluster.isWorker) {
878
+ process.on("message", async (msg) => {
879
+ if (!msg || typeof msg !== "object")
880
+ return;
881
+ if (msg.type === "krate:apply") {
882
+ let result;
883
+ try {
884
+ result = await applyInternalOp(msg.op, msg.payload || {});
885
+ }
886
+ catch (err) {
887
+ result = { ok: false, error: err && err.message ? err.message : String(err) };
888
+ }
889
+ process.send({ type: "krate:applied", id: msg.id, result });
890
+ }
891
+ else if (msg.type === "krate:bcast-done") {
892
+ const done = broadcastWaiters.get(msg.id);
893
+ if (done) {
894
+ broadcastWaiters.delete(msg.id);
895
+ done(Array.isArray(msg.results) ? msg.results : []);
896
+ }
897
+ }
898
+ });
899
+ }
900
+ function broadcastInternalOp(op, payload) {
901
+ if (!cluster.isWorker || typeof process.send !== "function") {
902
+ return applyInternalOp(op, payload).then((r) => [r]);
903
+ }
904
+ const id = `${process.pid}-${++broadcastSeq}`;
905
+ return new Promise((resolve) => {
906
+ broadcastWaiters.set(id, resolve);
907
+ process.send({ type: "krate:bcast", id, op, payload });
908
+ });
909
+ }
910
+ function mergeOpResults(op, results) {
911
+ const failed = results.filter((r) => r && r.ok === false);
912
+ if (failed.length > 0) {
913
+ throw new Error(failed.map((r) => r.error).join("; "));
914
+ }
915
+ const out = { ok: true, workers: results.length };
916
+ if (op === "refresh-route")
917
+ out.refreshed = results.reduce((n, r) => n + (r.refreshed || 0), 0);
918
+ if (op === "cache-invalidate") {
919
+ for (const k of ["isrEntries", "regionEntries", "dataEntries"]) {
920
+ out[k] = results.reduce((n, r) => n + (r[k] || 0), 0);
921
+ }
922
+ }
923
+ return out;
924
+ }
534
925
  // HTTP Server
535
926
  const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
536
927
  const manifestPath = process.env.KRATE_MANIFEST || "";
@@ -571,70 +962,29 @@ const server = http.createServer(async (req, res) => {
571
962
  res.end(JSON.stringify({ ok: true, pages: manifest?.pages?.length || 0 }));
572
963
  return;
573
964
  }
574
- // ISR revalidation endpoint (called by Go server in background)
575
- if (route === "/__krate/ssr/revalidate" && req.method === "POST") {
576
- const body = await parseBody(req);
577
- try {
578
- const { route: targetRoute } = JSON.parse(body);
579
- isrCache.deleteRoute(targetRoute);
580
- clearRegionCacheForRoute(targetRoute);
581
- // Trigger re-render of the base variant.
582
- const page = findPage(targetRoute);
583
- if (page) {
584
- await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
585
- }
586
- res.writeHead(200, { "Content-Type": "application/json" });
587
- res.end(JSON.stringify({ ok: true }));
588
- }
589
- catch (err) {
590
- res.writeHead(500, { "Content-Type": "application/json" });
591
- res.end(JSON.stringify({ error: err.message }));
592
- }
593
- return;
594
- }
595
- // ISR background refresh endpoint (called by the Go server on each route's
596
- // revalidation cadence). Unlike /__krate/ssr/revalidate this is
597
- // non-destructive: it re-renders every cached variant in place, so cached
598
- // dynamic variants stay fresh instead of being evicted (which would make the
599
- // next request a MISS rather than a HIT).
600
- if (route === "/__krate/ssr/refresh" && req.method === "POST") {
601
- const body = await parseBody(req);
602
- try {
603
- const { route: targetRoute } = JSON.parse(body);
604
- const page = findPage(targetRoute);
605
- const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
606
- clearRegionCacheForRoute(targetRoute);
607
- res.writeHead(200, { "Content-Type": "application/json" });
608
- res.end(JSON.stringify({ ok: true, refreshed }));
965
+ // Mutating internal endpoints. Each requires the host's shared secret and is
966
+ // applied on every clustered worker before the response is sent.
967
+ // /__krate/ssr/revalidate {route} clear a route, re-render its base variant
968
+ // /__krate/ssr/refresh {route} re-render cached variants in place (ISR timer)
969
+ // /__krate/ssr/invalidate {route, source, bundlePath} dev module reload
970
+ // /__krate/ssr/cache-invalidate {targets:[{route, params?}], tags:[]} on-demand revalidation
971
+ const internalOp = INTERNAL_OPS[route];
972
+ if (internalOp) {
973
+ if (req.method !== "POST") {
974
+ res.writeHead(405, { "Content-Type": "application/json", Allow: "POST" });
975
+ res.end(JSON.stringify({ error: "method not allowed" }));
976
+ return;
609
977
  }
610
- catch (err) {
611
- res.writeHead(500, { "Content-Type": "application/json" });
612
- res.end(JSON.stringify({ error: err.message }));
978
+ if (!internalAuthorized(req)) {
979
+ res.writeHead(403, { "Content-Type": "application/json" });
980
+ res.end(JSON.stringify({ error: "forbidden" }));
981
+ return;
613
982
  }
614
- return;
615
- }
616
- // Module cache invalidation (called on file change in dev mode)
617
- if (route === "/__krate/ssr/invalidate" && req.method === "POST") {
618
- const body = await parseBody(req);
619
983
  try {
620
- const { route: targetRoute, source, bundlePath } = JSON.parse(body);
621
- // Invalidate ISR cache for this route (all variants)
622
- isrCache.deleteRoute(targetRoute);
623
- // Invalidate module cache for the source file or bundle
624
- const key = bundlePath || source;
625
- if (key && moduleCache.has(key)) {
626
- moduleCache.delete(key);
627
- console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
628
- }
629
- // Runtime component bundles are recompiled in place on a dev rebuild, but
630
- // their render functions are cached for the process lifetime. Clear them
631
- // so the next region render picks up the new code. Bundles are tiny and
632
- // re-read on demand, so clearing all of them is cheap and avoids tracking
633
- // which component maps to which route here.
634
- runtimeBundleCache.clear();
635
- clearRegionCache();
984
+ const payload = JSON.parse((await parseBody(req)) || "{}");
985
+ const results = await broadcastInternalOp(internalOp, payload);
636
986
  res.writeHead(200, { "Content-Type": "application/json" });
637
- res.end(JSON.stringify({ ok: true }));
987
+ res.end(JSON.stringify(mergeOpResults(internalOp, results)));
638
988
  }
639
989
  catch (err) {
640
990
  res.writeHead(500, { "Content-Type": "application/json" });
@@ -680,20 +1030,19 @@ const server = http.createServer(async (req, res) => {
680
1030
  if (regions.length === 0) {
681
1031
  regions = (manifest?.regions?.[page.route] || []).map((r) => ({ id: r.id, kind: "component" }));
682
1032
  }
683
- for (const r of regions) {
684
- if (r.kind === "page") {
685
- writeJsonLine(res, await renderPageRegion(page, r.id, renderReq));
686
- }
687
- else {
688
- const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
689
- if (region) {
690
- writeJsonLine(res, await renderRegion(page, region, renderReq));
691
- }
692
- else {
693
- // Unknown region id - keep the baked content by sending no frame.
694
- writeJsonLine(res, { type: "skip", id: r.id });
695
- }
696
- }
1033
+ // Start every region render at once (async server components await
1034
+ // I/O, so they overlap), then write the frames in document order.
1035
+ const pending = regions.map((r) => {
1036
+ if (r.kind === "page")
1037
+ return renderPageRegion(page, r.id, renderReq);
1038
+ const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
1039
+ if (region)
1040
+ return renderRegion(page, region, renderReq);
1041
+ // Unknown region id - keep the baked content by sending no frame.
1042
+ return Promise.resolve({ type: "skip", id: r.id });
1043
+ });
1044
+ for (const p of pending) {
1045
+ writeJsonLine(res, await p);
697
1046
  }
698
1047
  writeJsonLine(res, { type: "end", count: regions.length });
699
1048
  }
@@ -733,7 +1082,7 @@ const server = http.createServer(async (req, res) => {
733
1082
  return;
734
1083
  }
735
1084
  if (result.redirect) {
736
- res.writeHead(302, { Location: result.redirect });
1085
+ res.writeHead(result.status === 307 ? 307 : 302, { Location: result.redirect });
737
1086
  res.end();
738
1087
  return;
739
1088
  }
@@ -765,6 +1114,32 @@ if (isClusterPrimary) {
765
1114
  // The primary only supervises; workers own the listening socket.
766
1115
  }
767
1116
  else {
1117
+ // The port was free when Go chose it, but a bind can still fail with
1118
+ // EADDRINUSE: any socket holding that local port blocks the wildcard bind,
1119
+ // including a short-lived outgoing connection. A clustered worker exits
1120
+ // quietly so the primary respawns it after a delay (listening again after a
1121
+ // failed cluster listen trips a Node assertion on Windows); a standalone
1122
+ // server retries the bind for a few seconds.
1123
+ let bindRetries = 100;
1124
+ server.on("error", (err) => {
1125
+ if (err.code === "EADDRINUSE") {
1126
+ if (cluster.isWorker)
1127
+ process.exit(1);
1128
+ if (bindRetries-- > 0) {
1129
+ setTimeout(() => {
1130
+ try {
1131
+ server.close();
1132
+ }
1133
+ catch {
1134
+ // not listening yet
1135
+ }
1136
+ server.listen(PORT);
1137
+ }, 100);
1138
+ return;
1139
+ }
1140
+ }
1141
+ throw err;
1142
+ });
768
1143
  server.listen(PORT, () => {
769
1144
  console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
770
1145
  });