@krate/runtime 0.5.0-alpha.3 → 0.5.0-beta.1

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 (76) hide show
  1. package/dist/action-context.d.ts +14 -3
  2. package/dist/action-context.js +70 -4
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +101 -5
  6. package/dist/actions.test.js +87 -1
  7. package/dist/cache-scope.d.ts +118 -0
  8. package/dist/cache-scope.js +314 -0
  9. package/dist/cache.d.ts +55 -0
  10. package/dist/cache.js +155 -0
  11. package/dist/cache.test.d.ts +1 -0
  12. package/dist/cache.test.js +233 -0
  13. package/dist/class-helpers.d.ts +4 -4
  14. package/dist/class-helpers.js +357 -32
  15. package/dist/class-helpers.test.d.ts +1 -0
  16. package/dist/class-helpers.test.js +169 -0
  17. package/dist/context.d.ts +16 -2
  18. package/dist/context.js +44 -3
  19. package/dist/dev-overlay.js +75 -2
  20. package/dist/dev-overlay.test.js +22 -0
  21. package/dist/dom.d.ts +7 -0
  22. package/dist/dom.js +69 -3
  23. package/dist/effects.js +74 -3
  24. package/dist/error-overlay.js +4 -4
  25. package/dist/hook-args.d.ts +7 -0
  26. package/dist/hook-args.js +10 -0
  27. package/dist/htmlspec-attributes.d.ts +1 -0
  28. package/dist/htmlspec-attributes.js +159 -0
  29. package/dist/index.d.ts +3 -2
  30. package/dist/index.js +2 -1
  31. package/dist/krate-core.js +2 -0
  32. package/dist/krate-dev.js +65 -2
  33. package/dist/krate-f-actions.js +2 -0
  34. package/dist/krate-f-classes.js +8 -0
  35. package/dist/krate-f-helpers.js +2 -0
  36. package/dist/krate-f-list.js +2 -0
  37. package/dist/krate-f-router-lite.js +2 -0
  38. package/dist/krate-f-router.js +2 -0
  39. package/dist/krate-features.json +239 -0
  40. package/dist/krate-hydrate-lite.js +5 -5
  41. package/dist/krate-hydrate.js +5 -5
  42. package/dist/krate-runtime.js +5 -5
  43. package/dist/patterns.test.d.ts +1 -0
  44. package/dist/patterns.test.js +98 -0
  45. package/dist/portal.d.ts +5 -1
  46. package/dist/portal.js +15 -4
  47. package/dist/reactivity-core.test.d.ts +1 -0
  48. package/dist/reactivity-core.test.js +152 -0
  49. package/dist/reconcile.js +4 -2
  50. package/dist/request-context.d.ts +62 -0
  51. package/dist/request-context.js +107 -0
  52. package/dist/router-layout.test.d.ts +1 -0
  53. package/dist/router-layout.test.js +179 -0
  54. package/dist/router-lite.d.ts +25 -0
  55. package/dist/router-lite.js +73 -0
  56. package/dist/router-nav.test.d.ts +1 -0
  57. package/dist/router-nav.test.js +437 -0
  58. package/dist/router-slots.test.d.ts +1 -0
  59. package/dist/router-slots.test.js +144 -0
  60. package/dist/router-speculation.test.d.ts +1 -0
  61. package/dist/router-speculation.test.js +25 -0
  62. package/dist/router-styles.test.d.ts +1 -0
  63. package/dist/router-styles.test.js +98 -0
  64. package/dist/router.d.ts +66 -2
  65. package/dist/router.js +1617 -648
  66. package/dist/server-async.test.d.ts +1 -0
  67. package/dist/server-async.test.js +194 -0
  68. package/dist/server-renderer.js +556 -132
  69. package/dist/server.d.ts +24 -0
  70. package/dist/server.js +247 -11
  71. package/dist/server.test.js +20 -0
  72. package/dist/signal.d.ts +41 -4
  73. package/dist/signal.js +254 -24
  74. package/dist/slots.d.ts +5 -1
  75. package/dist/slots.js +40 -3
  76. package/package.json +6 -2
@@ -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, thenable, 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,6 +37,10 @@ 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();
19
46
  // Restart a worker that dies, after a short delay, but give up when they
@@ -33,6 +60,40 @@ if (isClusterPrimary) {
33
60
  setTimeout(() => cluster.fork(), 100);
34
61
  });
35
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
+ });
36
97
  }
37
98
  // Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
38
99
  // Must be called BEFORE the first write for it to take effect.
@@ -57,10 +118,70 @@ function variantKey(req) {
57
118
  key += "#" + query;
58
119
  return key;
59
120
  }
121
+ function newQueryTracker() {
122
+ return { keys: new Set(), all: false };
123
+ }
124
+ function trackedQuery(query, t) {
125
+ const target = { ...(query || {}) };
126
+ const note = (prop) => {
127
+ if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor")
128
+ t.keys.add(prop);
129
+ };
130
+ return new Proxy(target, {
131
+ get(obj, prop, recv) {
132
+ note(prop);
133
+ return Reflect.get(obj, prop, recv);
134
+ },
135
+ has(obj, prop) {
136
+ note(prop);
137
+ return Reflect.has(obj, prop);
138
+ },
139
+ ownKeys(obj) {
140
+ t.all = true;
141
+ return Reflect.ownKeys(obj);
142
+ },
143
+ getOwnPropertyDescriptor(obj, prop) {
144
+ note(prop);
145
+ return Reflect.getOwnPropertyDescriptor(obj, prop);
146
+ },
147
+ });
148
+ }
149
+ // pageQueryReads remembers, per route+params variant, which query keys renders
150
+ // have read ("all" when a render enumerated the whole query).
151
+ const pageQueryReads = new Map();
152
+ function pageBaseKey(req) {
153
+ return variantKey({ route: req.route, params: req.params });
154
+ }
155
+ // pageKey is the ISR cache key for a request: params, plus only the query keys
156
+ // previous renders of this variant read.
157
+ function pageKey(req) {
158
+ const reads = pageQueryReads.get(pageBaseKey(req));
159
+ if (!reads)
160
+ return pageBaseKey(req);
161
+ if (reads === "all")
162
+ return variantKey(req);
163
+ const picked = {};
164
+ for (const k of [...reads].sort()) {
165
+ if (req.query && Object.prototype.hasOwnProperty.call(req.query, k))
166
+ picked[k] = req.query[k];
167
+ }
168
+ return variantKey({ route: req.route, params: req.params, query: picked });
169
+ }
170
+ function recordQueryReads(req, t) {
171
+ const base = pageBaseKey(req);
172
+ let cur = pageQueryReads.get(base);
173
+ if (t.all)
174
+ cur = "all";
175
+ else if (t.keys.size > 0 && cur !== "all")
176
+ cur = new Set([...(cur || []), ...t.keys]);
177
+ if (cur)
178
+ pageQueryReads.set(base, cur);
179
+ }
60
180
  class ISRCache {
61
181
  constructor(maxSize = 512) {
62
182
  this.cache = new Map();
63
- this.revalidationIntervals = new Map(); // route → seconds
183
+ this.byTag = new Map();
184
+ this.revalidationIntervals = new Map(); // route -> seconds
64
185
  this.maxSize = maxSize;
65
186
  }
66
187
  setRevalidation(route, seconds) {
@@ -70,28 +191,87 @@ class ISRCache {
70
191
  return this.cache.get(key);
71
192
  }
72
193
  set(key, entry) {
194
+ if (this.cache.has(key))
195
+ this.delete(key);
73
196
  if (this.cache.size >= this.maxSize) {
74
197
  const oldest = this.cache.keys().next().value;
75
198
  if (oldest)
76
- this.cache.delete(oldest);
199
+ this.delete(oldest);
77
200
  }
78
201
  this.cache.set(key, entry);
202
+ for (const t of entry.tags || []) {
203
+ let keys = this.byTag.get(t);
204
+ if (!keys)
205
+ this.byTag.set(t, (keys = new Set()));
206
+ keys.add(key);
207
+ }
208
+ }
209
+ delete(key) {
210
+ const entry = this.cache.get(key);
211
+ if (!entry)
212
+ return false;
213
+ this.cache.delete(key);
214
+ for (const t of entry.tags || []) {
215
+ const keys = this.byTag.get(t);
216
+ if (keys) {
217
+ keys.delete(key);
218
+ if (keys.size === 0)
219
+ this.byTag.delete(t);
220
+ }
221
+ }
222
+ return true;
223
+ }
224
+ get size() {
225
+ return this.cache.size;
79
226
  }
80
227
  isStale(key) {
81
228
  const entry = this.cache.get(key);
82
229
  const route = key.split("?")[0].split("#")[0];
83
- const interval = this.revalidationIntervals.get(route);
230
+ let interval = this.revalidationIntervals.get(route) || 0;
231
+ if (entry && entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval)) {
232
+ interval = entry.revalidate;
233
+ }
84
234
  if (!entry || !interval)
85
235
  return false;
86
236
  return (Date.now() - entry.timestamp) / 1000 > interval;
87
237
  }
88
238
  // deleteRoute removes every variant of a route (used by revalidation/invalidation).
89
239
  deleteRoute(route) {
240
+ let n = 0;
90
241
  for (const key of [...this.cache.keys()]) {
91
242
  if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
92
- this.cache.delete(key);
243
+ if (this.delete(key))
244
+ n++;
245
+ }
246
+ }
247
+ return n;
248
+ }
249
+ // deleteVariant removes one params variant of a route (every query variant
250
+ // of it), e.g. /blog/[slug] with {slug: "a"} for revalidatePath("/blog/a").
251
+ deleteVariant(route, params) {
252
+ const base = variantKey({ route, params });
253
+ let n = 0;
254
+ for (const key of [...this.cache.keys()]) {
255
+ if (key === base || key.startsWith(base + "#")) {
256
+ if (this.delete(key))
257
+ n++;
258
+ }
259
+ }
260
+ return n;
261
+ }
262
+ // deleteTags removes every entry whose render read one of tags.
263
+ deleteTags(tags) {
264
+ let n = 0;
265
+ for (const t of tags) {
266
+ const keys = this.byTag.get(t);
267
+ if (!keys)
268
+ continue;
269
+ for (const key of [...keys]) {
270
+ if (this.delete(key))
271
+ n++;
93
272
  }
94
273
  }
274
+ return n;
95
275
  }
96
276
  // entriesForRoute returns a snapshot of the cached variants for a route so a
97
277
  // background refresh can iterate them without mutating during iteration.
@@ -114,11 +294,13 @@ class ISRCache {
114
294
  return;
115
295
  for (const e of data.entries) {
116
296
  if (e && typeof e.key === "string" && typeof e.html === "string") {
117
- this.cache.set(e.key, {
297
+ this.set(e.key, {
118
298
  html: e.html,
119
299
  timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
120
300
  params: e.params && typeof e.params === "object" ? e.params : undefined,
121
301
  query: e.query && typeof e.query === "object" ? e.query : undefined,
302
+ tags: Array.isArray(e.tags) ? e.tags.filter((t) => typeof t === "string") : undefined,
303
+ revalidate: typeof e.revalidate === "number" ? e.revalidate : undefined,
122
304
  });
123
305
  }
124
306
  }
@@ -151,7 +333,24 @@ function withRenderTimeout(p) {
151
333
  let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
152
334
  let persistTimer = null;
153
335
  function isrCachePath() {
154
- return isrCacheFile || path.join(root, "dist", ".krate", "isr-cache.json");
336
+ return isrCacheFile || path.join(OUT_DIR, ".krate", "isr-cache.json");
337
+ }
338
+ function persistIsrNow() {
339
+ if (SSR_WORKERS > 1)
340
+ return;
341
+ if (persistTimer) {
342
+ clearTimeout(persistTimer);
343
+ persistTimer = null;
344
+ }
345
+ try {
346
+ const data = isrCache.serialize();
347
+ const file = isrCachePath();
348
+ fs.mkdirSync(path.dirname(file), { recursive: true });
349
+ fs.writeFileSync(file, JSON.stringify(data));
350
+ }
351
+ catch (err) {
352
+ console.error("[krate-ssr] ISR cache persist failed:", err.message);
353
+ }
155
354
  }
156
355
  function scheduleIsrPersist() {
157
356
  // Clustered: multiple workers would race on the same cache file; keep the ISR
@@ -160,18 +359,7 @@ function scheduleIsrPersist() {
160
359
  return;
161
360
  if (persistTimer)
162
361
  clearTimeout(persistTimer);
163
- persistTimer = setTimeout(() => {
164
- persistTimer = null;
165
- try {
166
- const data = isrCache.serialize();
167
- const file = isrCachePath();
168
- fs.mkdirSync(path.dirname(file), { recursive: true });
169
- fs.writeFileSync(file, JSON.stringify(data));
170
- }
171
- catch (err) {
172
- console.error("[krate-ssr] ISR cache persist failed:", err.message);
173
- }
174
- }, 1000);
362
+ persistTimer = setTimeout(persistIsrNow, 1000);
175
363
  }
176
364
  function loadIsrCache() {
177
365
  try {
@@ -179,7 +367,7 @@ function loadIsrCache() {
179
367
  if (fs.existsSync(file)) {
180
368
  const data = JSON.parse(fs.readFileSync(file, "utf-8"));
181
369
  isrCache.hydrate(data);
182
- const n = isrCache.cache.size;
370
+ const n = isrCache.size;
183
371
  if (n > 0)
184
372
  console.log(`[krate-ssr] Loaded ${n} persisted ISR entries`);
185
373
  }
@@ -199,7 +387,7 @@ async function loadPageModule(page) {
199
387
  let fileUrl;
200
388
  if (page.bundlePath) {
201
389
  // Pre-compiled bundle: bundlePath is relative to outDir (dist/)
202
- const bundleAbs = path.resolve(root, "dist", page.bundlePath);
390
+ const bundleAbs = path.resolve(OUT_DIR, page.bundlePath);
203
391
  fileUrl = pathToFileURL(bundleAbs).href;
204
392
  }
205
393
  else {
@@ -232,15 +420,72 @@ function findPage(route) {
232
420
  }
233
421
  return page;
234
422
  }
235
- function buildProps(req) {
423
+ // Request scope for server components: headers()/cookies() from
424
+ // @krate/runtime/server read it through the global store symbol, so it works
425
+ // no matter which copy of the runtime a page bundle resolved.
426
+ const requestStore = (() => {
427
+ const key = Symbol.for("krate.request.store");
428
+ const g = globalThis;
429
+ if (!g[key])
430
+ g[key] = new AsyncLocalStorage();
431
+ return g[key];
432
+ })();
433
+ function requestContextFor(req, tracker) {
434
+ const h = new Headers();
435
+ for (const [k, v] of Object.entries(req.headers || {})) {
436
+ if (typeof v === "string") {
437
+ try {
438
+ h.set(k, v);
439
+ }
440
+ catch {
441
+ // skip header names the WHATWG Headers class rejects
442
+ }
443
+ }
444
+ }
445
+ return {
446
+ url: req.url || req.route,
447
+ method: req.method || "GET",
448
+ headers: h,
449
+ cookies: parseCookieHeader(h.get("cookie")),
450
+ params: { ...(req.params || {}) },
451
+ searchParams: tracker ? trackedQuery(req.query, tracker) : { ...(req.query || {}) },
452
+ };
453
+ }
454
+ function withRequest(req, fn, tracker) {
455
+ return requestStore.run(requestContextFor(req, tracker), fn);
456
+ }
457
+ // renderSignal maps notFound()/redirect() thrown during a render to a response.
458
+ function renderSignal(err) {
459
+ if (isNotFoundSignal(err))
460
+ return { html: "", status: 404, notFound: true };
461
+ const to = redirectTarget(err);
462
+ if (to)
463
+ return { html: "", status: 307, redirect: to };
464
+ return null;
465
+ }
466
+ function buildProps(req, tracker) {
236
467
  // Page-level data fetching (getStaticProps/getServerSideProps) has been
237
468
  // removed; per-request data is provided by server components (@server),
238
469
  // runtime components (@runtime), and middleware instead. Dynamic-route
239
470
  // params and query parameters extracted by the Go server are forwarded so
240
471
  // `({ params }) => ...` pages receive their real values at render time.
472
+ // params and searchParams are plain objects that can also be awaited, so
473
+ // both `params.slug` and Next.js 15's `const { slug } = await params` work.
474
+ // The Go server always forwards params (empty for static routes); a direct
475
+ // request without them keeps params undefined, as before.
241
476
  const props = {};
242
477
  if (req.params)
243
- props.params = req.params;
478
+ props.params = thenableRecord(req.params);
479
+ if (tracker) {
480
+ // Reads through the view are recorded; awaiting it resolves to another
481
+ // tracked view so `const { page } = await searchParams` records "page".
482
+ const view = trackedQuery(req.query, tracker);
483
+ props.searchParams = thenable(view, () => trackedQuery(req.query, tracker));
484
+ if (req.query)
485
+ props.query = trackedQuery(req.query, tracker);
486
+ return props;
487
+ }
488
+ props.searchParams = thenableRecord(req.query);
244
489
  if (req.query)
245
490
  props.query = req.query;
246
491
  return props;
@@ -254,29 +499,40 @@ async function renderFresh(page, req) {
254
499
  if (!Component) {
255
500
  return { html: "", status: 500 };
256
501
  }
257
- const jsxNode = Component(buildProps(req));
258
- // Bound the render. renderToString is synchronous, so a page that blocks
259
- // would block the sidecar's event loop regardless; the timeout still
260
- // protects the request path when rendering is async (suspense/resource).
261
- const html = await withRenderTimeout(Promise.resolve(renderToString(jsxNode)));
502
+ // The render runs in a cache scope that records the tags / revalidate
503
+ // windows its data reads declared (fetch next options, unstable_cache).
504
+ // Async server components (and plain sync pages) render through
505
+ // renderToStringAsync inside the request scope. The timeout bounds slow
506
+ // awaits (fetch); a page that blocks synchronously still blocks the loop.
507
+ const tracker = newQueryTracker();
508
+ const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderToStringAsync(jsx(Component, buildProps(req, tracker))), tracker)));
262
509
  const response = {
263
510
  html,
264
511
  status: 200,
512
+ noStore: scope.noStore || invalidated,
265
513
  };
266
- if (page.mode === "isr") {
267
- isrCache.set(variantKey(req), {
514
+ // An uncacheable read (no-store) keeps the render out of the ISR cache, and
515
+ // a revalidation that landed mid-render means the HTML may be stale.
516
+ if (page.mode === "isr" && !scope.noStore && !invalidated) {
517
+ recordQueryReads(req, tracker);
518
+ isrCache.set(pageKey(req), {
268
519
  html,
269
520
  timestamp: Date.now(),
270
521
  params: req.params,
271
522
  query: req.query,
523
+ tags: scope.tags.size ? [...scope.tags] : undefined,
524
+ revalidate: scope.revalidate || undefined,
272
525
  });
273
526
  scheduleIsrPersist();
274
527
  }
275
528
  return response;
276
529
  }
277
530
  catch (err) {
531
+ const signal = renderSignal(err);
532
+ if (signal)
533
+ return signal;
278
534
  console.error(`[krate] Error rendering ${req.route}:`, err);
279
- return { html: "", status: 500 };
535
+ return { html: "", status: 500, error: (err && err.message) || String(err) };
280
536
  }
281
537
  }
282
538
  // Single-flight background revalidation for stale-while-revalidate. While a
@@ -284,7 +540,7 @@ async function renderFresh(page, req) {
284
540
  // same promise instead of stampeding the renderer.
285
541
  const inFlightRevalidations = new Map();
286
542
  function revalidateInBackground(page, req) {
287
- const key = variantKey(req);
543
+ const key = pageKey(req);
288
544
  if (inFlightRevalidations.has(key))
289
545
  return;
290
546
  const p = (async () => {
@@ -348,7 +604,7 @@ async function renderPage(req) {
348
604
  if (page.mode === "isr") {
349
605
  const interval = page.revalidate || 60;
350
606
  isrCache.setRevalidation(page.route, interval);
351
- const key = variantKey(req);
607
+ const key = pageKey(req);
352
608
  const cached = isrCache.get(key);
353
609
  if (cached && !isrCache.isStale(key)) {
354
610
  return {
@@ -390,9 +646,17 @@ function loadRuntimeRenderer(relPath) {
390
646
  const cached = runtimeBundleCache.get(relPath);
391
647
  if (cached)
392
648
  return cached;
393
- const abs = path.resolve(root, "dist", relPath);
649
+ const abs = path.resolve(OUT_DIR, relPath);
394
650
  const code = fs.readFileSync(abs, "utf-8");
395
- const ctx = vm.createContext({ console });
651
+ // Runtime components get the host's fetch (looked up per call, so a cache
652
+ // layer that wraps globalThis.fetch later still applies) and the web
653
+ // primitives that go with it.
654
+ const ctx = vm.createContext({
655
+ console,
656
+ fetch: (...args) => globalThis.fetch(...args),
657
+ Headers, Request, Response, URL, URLSearchParams, TextEncoder, TextDecoder,
658
+ setTimeout, clearTimeout, queueMicrotask, structuredClone, AbortController,
659
+ });
396
660
  vm.runInContext(code, ctx, { filename: relPath });
397
661
  const render = vm.runInContext("typeof globalThis.__krate_render === 'function' ? globalThis.__krate_render : typeof __krate_render === 'function' ? __krate_render : null", ctx);
398
662
  if (typeof render !== "function") {
@@ -409,22 +673,43 @@ function regionProps(region, req) {
409
673
  props.query = req.query;
410
674
  return props;
411
675
  }
412
- // Region ISR cache: region-level stale-while-revalidate, separate from the
413
- // page ISR cache. Region HTML only depends on the baked props, so it is fully
414
- // determined by (route, region id, variant) and cacheable like a page variant.
415
676
  const regionCache = new Map();
416
677
  const regionRevalidation = new Map();
417
678
  const inFlightRegionRevalidations = new Map();
418
679
  // Region cache is bounded (FIFO eviction) so a long-lived sidecar cannot grow
419
680
  // without limit across many dynamic region variants.
420
681
  const REGION_CACHE_MAX = parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512;
421
- function regionCacheSet(key, html) {
682
+ function paramsKeyOf(params) {
683
+ return variantKey({ route: "", params });
684
+ }
685
+ function regionCacheSet(key, html, page, req, scope) {
422
686
  if (regionCache.size >= REGION_CACHE_MAX && !regionCache.has(key)) {
423
687
  const oldest = regionCache.keys().next().value;
424
688
  if (oldest !== undefined)
425
689
  regionCache.delete(oldest);
426
690
  }
427
- regionCache.set(key, { html, timestamp: Date.now() });
691
+ regionCache.set(key, {
692
+ html,
693
+ timestamp: Date.now(),
694
+ route: page.route,
695
+ paramsKey: paramsKeyOf(req.params),
696
+ tags: scope && scope.tags.size ? [...scope.tags] : undefined,
697
+ });
698
+ }
699
+ // invalidateRegions removes region entries for a route (optionally one params
700
+ // variant) and/or entries whose render read one of tags.
701
+ function invalidateRegions(route, params, tags) {
702
+ const pkey = params ? paramsKeyOf(params) : null;
703
+ let n = 0;
704
+ for (const [key, e] of Array.from(regionCache.entries())) {
705
+ const routeHit = route !== null && e.route === route && (pkey === null || e.paramsKey === pkey);
706
+ const tagHit = tags.length > 0 && !!e.tags && e.tags.some((t) => tags.includes(t));
707
+ if (routeHit || tagHit) {
708
+ regionCache.delete(key);
709
+ n++;
710
+ }
711
+ }
712
+ return n;
428
713
  }
429
714
  function clearRegionCache() {
430
715
  regionCache.clear();
@@ -451,17 +736,39 @@ function regionInterval(page, region) {
451
736
  return pprRevalidate;
452
737
  return 0;
453
738
  }
454
- function renderRegionFresh(region, req) {
739
+ async function renderRegionFresh(page, region, req) {
740
+ if (region.serverExport) {
741
+ const out = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderServerExport(page, region, req))));
742
+ return { html: out.result, scope: out.scope, invalidated: out.invalidated };
743
+ }
455
744
  const render = loadRuntimeRenderer(region.bundlePath);
456
- return withRenderTimeout(Promise.resolve().then(() => render(JSON.stringify(regionProps(region, req)))));
745
+ const out = await withRenderTimeout(withCacheScope(page.route, () => render(JSON.stringify(regionProps(region, req)))));
746
+ return { html: out.result, scope: out.scope, invalidated: out.invalidated };
747
+ }
748
+ function regionCacheable(r) {
749
+ return !r.scope.noStore && !r.invalidated;
750
+ }
751
+ // renderServerExport renders an async server component region with the page's
752
+ // own server bundle, which exports the component under region.serverExport.
753
+ async function renderServerExport(page, region, req) {
754
+ const mod = await loadPageModule(page);
755
+ const Comp = mod[region.serverExport];
756
+ if (typeof Comp !== "function") {
757
+ throw new Error(`server bundle for ${page.route} does not export ${region.serverExport}`);
758
+ }
759
+ const props = regionProps(region, req);
760
+ if (props.params && typeof props.params === "object")
761
+ props.params = thenableRecord(props.params);
762
+ return renderToStringAsync(jsx(Comp, props));
457
763
  }
458
764
  function revalidateRegionInBackground(page, region, req, key) {
459
765
  if (inFlightRegionRevalidations.has(key))
460
766
  return;
461
767
  const p = (async () => {
462
768
  try {
463
- const html = await renderRegionFresh(region, req);
464
- regionCacheSet(key, html);
769
+ const r = await renderRegionFresh(page, region, req);
770
+ if (regionCacheable(r))
771
+ regionCacheSet(key, r.html, page, req, r.scope);
465
772
  console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
466
773
  }
467
774
  catch (err) {
@@ -476,8 +783,8 @@ function revalidateRegionInBackground(page, region, req, key) {
476
783
  // renderRegion renders one region, applying region-level ISR caching for ISR
477
784
  // pages. Returns an NDJSON frame.
478
785
  async function renderRegion(page, region, req) {
479
- if (!region.bundlePath) {
480
- return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle" };
786
+ if (!region.bundlePath && !region.serverExport) {
787
+ return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle", fatal: !!page.serverComponents };
481
788
  }
482
789
  const key = regionCacheKey(page, region.id, req);
483
790
  const interval = regionInterval(page, region);
@@ -495,18 +802,32 @@ async function renderRegion(page, region, req) {
495
802
  }
496
803
  }
497
804
  try {
498
- const html = await renderRegionFresh(region, req);
499
- if (cacheable) {
500
- regionCacheSet(key, html);
805
+ const r = await renderRegionFresh(page, region, req);
806
+ const html = r.html;
807
+ if (cacheable && regionCacheable(r)) {
808
+ regionCacheSet(key, html, page, req, r.scope);
501
809
  }
502
810
  const frame = { type: "region", id: region.id, status: 200, html };
503
811
  if (cacheable)
504
812
  frame.cacheStatus = "miss";
813
+ if (r.scope.noStore || r.invalidated)
814
+ frame.noStore = true;
505
815
  return frame;
506
816
  }
507
817
  catch (err) {
508
- console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err.message);
509
- return { type: "error", id: region.id, status: 500, error: err.message };
818
+ const signal = renderSignal(err);
819
+ if (signal) {
820
+ const frame = { type: "region", id: region.id, status: signal.status, html: "" };
821
+ if (signal.notFound)
822
+ frame.notFound = true;
823
+ if (signal.redirect)
824
+ frame.redirect = signal.redirect;
825
+ return frame;
826
+ }
827
+ console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err);
828
+ // A server component region has no meaningful baked content, so its
829
+ // failure is fatal for the response (the Go server answers 500).
830
+ return { type: "error", id: region.id, status: 500, error: (err && err.message) || String(err), fatal: !!(region.serverExport || page.serverComponents) };
510
831
  }
511
832
  }
512
833
  function writeJsonLine(res, obj) {
@@ -532,6 +853,12 @@ async function renderPageRegion(page, id, req) {
532
853
  frame.notFound = true;
533
854
  if (result.redirect)
534
855
  frame.redirect = result.redirect;
856
+ if (result.error)
857
+ frame.error = result.error;
858
+ if (result.noStore)
859
+ frame.noStore = true;
860
+ if (page.serverComponents && frame.status >= 500)
861
+ frame.fatal = true;
535
862
  // Title swap: the Go server replaces the baked <title> with the freshly
536
863
  // rendered one so params-driven pages update the browser tab.
537
864
  const title = extractTitle(result.html);
@@ -543,10 +870,138 @@ function extractTitle(html) {
543
870
  const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
544
871
  return match ? match[1].trim() : "";
545
872
  }
873
+ const INTERNAL_OPS = {
874
+ "/__krate/ssr/revalidate": "revalidate-route",
875
+ "/__krate/ssr/refresh": "refresh-route",
876
+ "/__krate/ssr/invalidate": "dev-invalidate",
877
+ "/__krate/ssr/cache-invalidate": "cache-invalidate",
878
+ };
879
+ function stringList(v) {
880
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
881
+ }
882
+ // applyInternalOp applies one internal operation to this process's caches.
883
+ async function applyInternalOp(op, payload) {
884
+ switch (op) {
885
+ case "revalidate-route": {
886
+ const targetRoute = String(payload.route || "");
887
+ isrCache.deleteRoute(targetRoute);
888
+ clearRegionCacheForRoute(targetRoute);
889
+ cacheRuntime().invalidate({});
890
+ persistIsrNow();
891
+ const page = findPage(targetRoute);
892
+ if (page) {
893
+ await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
894
+ }
895
+ return { ok: true };
896
+ }
897
+ case "refresh-route": {
898
+ const targetRoute = String(payload.route || "");
899
+ const page = findPage(targetRoute);
900
+ const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
901
+ clearRegionCacheForRoute(targetRoute);
902
+ return { ok: true, refreshed };
903
+ }
904
+ case "dev-invalidate": {
905
+ const { route: targetRoute, source, bundlePath } = payload;
906
+ // Invalidate ISR cache for this route (all variants)
907
+ isrCache.deleteRoute(targetRoute);
908
+ // Invalidate module cache for the source file or bundle
909
+ const key = bundlePath || source;
910
+ if (key && moduleCache.has(key)) {
911
+ moduleCache.delete(key);
912
+ console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
913
+ }
914
+ // Runtime component bundles are recompiled in place on a dev rebuild, but
915
+ // their render functions are cached for the process lifetime. Clear them
916
+ // so the next region render picks up the new code. Bundles are tiny and
917
+ // re-read on demand, so clearing all of them is cheap and avoids tracking
918
+ // which component maps to which route here.
919
+ runtimeBundleCache.clear();
920
+ clearRegionCache();
921
+ return { ok: true };
922
+ }
923
+ case "cache-invalidate": {
924
+ const tags = stringList(payload.tags);
925
+ const targets = Array.isArray(payload.targets)
926
+ ? payload.targets.filter((t) => t && typeof t.route === "string")
927
+ : [];
928
+ // Path targets also drop the data their renders cached (implicit tag).
929
+ const dataTags = tags.concat(targets.map((t) => routeDataTag(t.route)));
930
+ const { dataEntries } = cacheRuntime().invalidate({ tags: dataTags });
931
+ let isrEntries = 0;
932
+ let regionEntries = 0;
933
+ for (const t of targets) {
934
+ const params = t.params && typeof t.params === "object" ? t.params : null;
935
+ isrEntries += params ? isrCache.deleteVariant(t.route, params) : isrCache.deleteRoute(t.route);
936
+ regionEntries += invalidateRegions(t.route, params, []);
937
+ }
938
+ if (tags.length) {
939
+ isrEntries += isrCache.deleteTags(tags);
940
+ regionEntries += invalidateRegions(null, null, tags);
941
+ }
942
+ if (isrEntries > 0)
943
+ persistIsrNow();
944
+ return { ok: true, isrEntries, regionEntries, dataEntries };
945
+ }
946
+ }
947
+ }
948
+ // Cluster fan-out (worker side). broadcastInternalOp resolves with one result
949
+ // per live worker once every worker applied the operation.
950
+ let broadcastSeq = 0;
951
+ const broadcastWaiters = new Map();
952
+ if (cluster.isWorker) {
953
+ process.on("message", async (msg) => {
954
+ if (!msg || typeof msg !== "object")
955
+ return;
956
+ if (msg.type === "krate:apply") {
957
+ let result;
958
+ try {
959
+ result = await applyInternalOp(msg.op, msg.payload || {});
960
+ }
961
+ catch (err) {
962
+ result = { ok: false, error: err && err.message ? err.message : String(err) };
963
+ }
964
+ process.send({ type: "krate:applied", id: msg.id, result });
965
+ }
966
+ else if (msg.type === "krate:bcast-done") {
967
+ const done = broadcastWaiters.get(msg.id);
968
+ if (done) {
969
+ broadcastWaiters.delete(msg.id);
970
+ done(Array.isArray(msg.results) ? msg.results : []);
971
+ }
972
+ }
973
+ });
974
+ }
975
+ function broadcastInternalOp(op, payload) {
976
+ if (!cluster.isWorker || typeof process.send !== "function") {
977
+ return applyInternalOp(op, payload).then((r) => [r]);
978
+ }
979
+ const id = `${process.pid}-${++broadcastSeq}`;
980
+ return new Promise((resolve) => {
981
+ broadcastWaiters.set(id, resolve);
982
+ process.send({ type: "krate:bcast", id, op, payload });
983
+ });
984
+ }
985
+ function mergeOpResults(op, results) {
986
+ const failed = results.filter((r) => r && r.ok === false);
987
+ if (failed.length > 0) {
988
+ throw new Error(failed.map((r) => r.error).join("; "));
989
+ }
990
+ const out = { ok: true, workers: results.length };
991
+ if (op === "refresh-route")
992
+ out.refreshed = results.reduce((n, r) => n + (r.refreshed || 0), 0);
993
+ if (op === "cache-invalidate") {
994
+ for (const k of ["isrEntries", "regionEntries", "dataEntries"]) {
995
+ out[k] = results.reduce((n, r) => n + (r[k] || 0), 0);
996
+ }
997
+ }
998
+ return out;
999
+ }
546
1000
  // HTTP Server
547
1001
  const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
548
1002
  const manifestPath = process.env.KRATE_MANIFEST || "";
549
1003
  const root = process.env.KRATE_ROOT || process.cwd();
1004
+ const OUT_DIR = process.env.KRATE_OUT_DIR || path.join(root, "dist");
550
1005
  projectRoot = root;
551
1006
  // Load manifest
552
1007
  if (manifestPath && fs.existsSync(manifestPath)) {
@@ -556,7 +1011,8 @@ if (manifestPath && fs.existsSync(manifestPath)) {
556
1011
  }
557
1012
  else {
558
1013
  // Try default location
559
- const defaultPath = path.join(root, "dist", "server-manifest.json");
1014
+ const krateDefault = path.join(OUT_DIR, ".krate", "server-manifest.json");
1015
+ const defaultPath = fs.existsSync(krateDefault) ? krateDefault : path.join(OUT_DIR, "server-manifest.json");
560
1016
  if (fs.existsSync(defaultPath)) {
561
1017
  const data = fs.readFileSync(defaultPath, "utf-8");
562
1018
  manifest = JSON.parse(data);
@@ -583,70 +1039,29 @@ const server = http.createServer(async (req, res) => {
583
1039
  res.end(JSON.stringify({ ok: true, pages: manifest?.pages?.length || 0 }));
584
1040
  return;
585
1041
  }
586
- // ISR revalidation endpoint (called by Go server in background)
587
- if (route === "/__krate/ssr/revalidate" && req.method === "POST") {
588
- const body = await parseBody(req);
589
- try {
590
- const { route: targetRoute } = JSON.parse(body);
591
- isrCache.deleteRoute(targetRoute);
592
- clearRegionCacheForRoute(targetRoute);
593
- // Trigger re-render of the base variant.
594
- const page = findPage(targetRoute);
595
- if (page) {
596
- await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
597
- }
598
- res.writeHead(200, { "Content-Type": "application/json" });
599
- res.end(JSON.stringify({ ok: true }));
600
- }
601
- catch (err) {
602
- res.writeHead(500, { "Content-Type": "application/json" });
603
- res.end(JSON.stringify({ error: err.message }));
604
- }
605
- return;
606
- }
607
- // ISR background refresh endpoint (called by the Go server on each route's
608
- // revalidation cadence). Unlike /__krate/ssr/revalidate this is
609
- // non-destructive: it re-renders every cached variant in place, so cached
610
- // dynamic variants stay fresh instead of being evicted (which would make the
611
- // next request a MISS rather than a HIT).
612
- if (route === "/__krate/ssr/refresh" && req.method === "POST") {
613
- const body = await parseBody(req);
614
- try {
615
- const { route: targetRoute } = JSON.parse(body);
616
- const page = findPage(targetRoute);
617
- const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
618
- clearRegionCacheForRoute(targetRoute);
619
- res.writeHead(200, { "Content-Type": "application/json" });
620
- res.end(JSON.stringify({ ok: true, refreshed }));
1042
+ // Mutating internal endpoints. Each requires the host's shared secret and is
1043
+ // applied on every clustered worker before the response is sent.
1044
+ // /__krate/ssr/revalidate {route} clear a route, re-render its base variant
1045
+ // /__krate/ssr/refresh {route} re-render cached variants in place (ISR timer)
1046
+ // /__krate/ssr/invalidate {route, source, bundlePath} dev module reload
1047
+ // /__krate/ssr/cache-invalidate {targets:[{route, params?}], tags:[]} on-demand revalidation
1048
+ const internalOp = INTERNAL_OPS[route];
1049
+ if (internalOp) {
1050
+ if (req.method !== "POST") {
1051
+ res.writeHead(405, { "Content-Type": "application/json", Allow: "POST" });
1052
+ res.end(JSON.stringify({ error: "method not allowed" }));
1053
+ return;
621
1054
  }
622
- catch (err) {
623
- res.writeHead(500, { "Content-Type": "application/json" });
624
- res.end(JSON.stringify({ error: err.message }));
1055
+ if (!internalAuthorized(req)) {
1056
+ res.writeHead(403, { "Content-Type": "application/json" });
1057
+ res.end(JSON.stringify({ error: "forbidden" }));
1058
+ return;
625
1059
  }
626
- return;
627
- }
628
- // Module cache invalidation (called on file change in dev mode)
629
- if (route === "/__krate/ssr/invalidate" && req.method === "POST") {
630
- const body = await parseBody(req);
631
1060
  try {
632
- const { route: targetRoute, source, bundlePath } = JSON.parse(body);
633
- // Invalidate ISR cache for this route (all variants)
634
- isrCache.deleteRoute(targetRoute);
635
- // Invalidate module cache for the source file or bundle
636
- const key = bundlePath || source;
637
- if (key && moduleCache.has(key)) {
638
- moduleCache.delete(key);
639
- console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
640
- }
641
- // Runtime component bundles are recompiled in place on a dev rebuild, but
642
- // their render functions are cached for the process lifetime. Clear them
643
- // so the next region render picks up the new code. Bundles are tiny and
644
- // re-read on demand, so clearing all of them is cheap and avoids tracking
645
- // which component maps to which route here.
646
- runtimeBundleCache.clear();
647
- clearRegionCache();
1061
+ const payload = JSON.parse((await parseBody(req)) || "{}");
1062
+ const results = await broadcastInternalOp(internalOp, payload);
648
1063
  res.writeHead(200, { "Content-Type": "application/json" });
649
- res.end(JSON.stringify({ ok: true }));
1064
+ res.end(JSON.stringify(mergeOpResults(internalOp, results)));
650
1065
  }
651
1066
  catch (err) {
652
1067
  res.writeHead(500, { "Content-Type": "application/json" });
@@ -661,6 +1076,11 @@ const server = http.createServer(async (req, res) => {
661
1076
  // sidecar renders each one (a component region from the manifest, or a
662
1077
  // coarse "page" region that renders the whole page component for SSR/ISR).
663
1078
  if (route === "/__krate/regions" && req.method === "POST") {
1079
+ if (!internalAuthorized(req)) {
1080
+ res.writeHead(403, { "Content-Type": "application/json" });
1081
+ res.end(JSON.stringify({ error: "forbidden" }));
1082
+ return;
1083
+ }
664
1084
  res.writeHead(200, {
665
1085
  "Content-Type": "application/x-ndjson; charset=utf-8",
666
1086
  "Cache-Control": "no-store",
@@ -692,21 +1112,20 @@ const server = http.createServer(async (req, res) => {
692
1112
  if (regions.length === 0) {
693
1113
  regions = (manifest?.regions?.[page.route] || []).map((r) => ({ id: r.id, kind: "component" }));
694
1114
  }
695
- for (const r of regions) {
696
- if (r.kind === "page") {
697
- writeJsonLine(res, await renderPageRegion(page, r.id, renderReq));
698
- }
699
- else {
700
- const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
701
- if (region) {
702
- writeJsonLine(res, await renderRegion(page, region, renderReq));
703
- }
704
- else {
705
- // Unknown region id - keep the baked content by sending no frame.
706
- writeJsonLine(res, { type: "skip", id: r.id });
707
- }
708
- }
709
- }
1115
+ // Start every region render at once (async server components await
1116
+ // I/O, so they overlap), then write the frames in document order.
1117
+ const pending = regions.map((r) => {
1118
+ if (r.kind === "page")
1119
+ return renderPageRegion(page, r.id, renderReq);
1120
+ const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
1121
+ if (region)
1122
+ return renderRegion(page, region, renderReq);
1123
+ // Unknown region id - keep the baked content by sending no frame.
1124
+ return Promise.resolve({ type: "skip", id: r.id });
1125
+ });
1126
+ // Write each frame as soon as it resolves. Async server components finish
1127
+ // out of document order, and the Go host inserts each chunk at its marker.
1128
+ await Promise.all(pending.map(async (p) => writeJsonLine(res, await p)));
710
1129
  writeJsonLine(res, { type: "end", count: regions.length });
711
1130
  }
712
1131
  catch (err) {
@@ -717,6 +1136,11 @@ const server = http.createServer(async (req, res) => {
717
1136
  return;
718
1137
  }
719
1138
  // Direct page requests (non-proxied)
1139
+ if (!internalAuthorized(req)) {
1140
+ res.writeHead(403, { "Content-Type": "application/json" });
1141
+ res.end(JSON.stringify({ error: "forbidden" }));
1142
+ return;
1143
+ }
720
1144
  // Collect request headers
721
1145
  const headers = {};
722
1146
  for (const [key, value] of Object.entries(req.headers)) {
@@ -732,7 +1156,7 @@ const server = http.createServer(async (req, res) => {
732
1156
  const result = await renderPage(renderReq);
733
1157
  if (result.notFound) {
734
1158
  // Try to serve 404.html from dist
735
- const notFoundPath = path.join(root, "dist", "404.html");
1159
+ const notFoundPath = path.join(OUT_DIR, "404.html");
736
1160
  if (fs.existsSync(notFoundPath)) {
737
1161
  const html = fs.readFileSync(notFoundPath, "utf-8");
738
1162
  res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
@@ -745,13 +1169,13 @@ const server = http.createServer(async (req, res) => {
745
1169
  return;
746
1170
  }
747
1171
  if (result.redirect) {
748
- res.writeHead(302, { Location: result.redirect });
1172
+ res.writeHead(result.status === 307 ? 307 : 302, { Location: result.redirect });
749
1173
  res.end();
750
1174
  return;
751
1175
  }
752
1176
  if (result.status === 500) {
753
1177
  // Try to serve 500.html from dist
754
- const errorPath = path.join(root, "dist", "500.html");
1178
+ const errorPath = path.join(OUT_DIR, "500.html");
755
1179
  if (fs.existsSync(errorPath)) {
756
1180
  const html = fs.readFileSync(errorPath, "utf-8");
757
1181
  res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
@@ -796,14 +1220,14 @@ else {
796
1220
  catch {
797
1221
  // not listening yet
798
1222
  }
799
- server.listen(PORT);
1223
+ server.listen(PORT, "127.0.0.1");
800
1224
  }, 100);
801
1225
  return;
802
1226
  }
803
1227
  }
804
1228
  throw err;
805
1229
  });
806
- server.listen(PORT, () => {
1230
+ server.listen(PORT, "127.0.0.1", () => {
807
1231
  console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
808
1232
  });
809
1233
  }