@krate/runtime 0.5.0-rc.15 → 0.5.0-rc.16

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.
@@ -0,0 +1,14 @@
1
+ export declare function approxBytes(value: unknown, maxDepth?: number): number;
2
+ /** The default memory budget of the render caches, in bytes. */
3
+ export declare const DEFAULT_CACHE_BYTES: number;
4
+ /**
5
+ * The byte budgets of the in-memory caches, from KRATE_SSR_CACHE_BYTES (the
6
+ * total for one process; 0 or unset is the default). Rendered pages get half,
7
+ * PPR regions and the data cache a quarter each.
8
+ */
9
+ export declare function cacheByteBudgets(total?: number): {
10
+ pages: number;
11
+ regions: number;
12
+ data: number;
13
+ };
14
+ export declare function cacheBytesFromEnv(env: Record<string, string | undefined> | undefined): number;
@@ -0,0 +1,71 @@
1
+ // Approximate retained size of cached values, for byte-bounded caches. It
2
+ // counts string characters as bytes (V8 stores ASCII text one byte per
3
+ // character), adds a small fixed cost per object, array, key and number, and
4
+ // stops at maxDepth so a deep or cyclic value costs a bounded walk.
5
+ const OBJECT_COST = 32;
6
+ const SLOT_COST = 8;
7
+ export function approxBytes(value, maxDepth = 8) {
8
+ const seen = new Set();
9
+ const walk = (v, depth) => {
10
+ switch (typeof v) {
11
+ case "string":
12
+ return v.length + 16;
13
+ case "number":
14
+ case "boolean":
15
+ case "undefined":
16
+ case "symbol":
17
+ return SLOT_COST;
18
+ case "bigint":
19
+ return 16;
20
+ case "function":
21
+ return OBJECT_COST;
22
+ }
23
+ if (v === null)
24
+ return SLOT_COST;
25
+ const o = v;
26
+ if (seen.has(o))
27
+ return SLOT_COST;
28
+ seen.add(o);
29
+ if (ArrayBuffer.isView(o))
30
+ return o.byteLength + OBJECT_COST;
31
+ if (o instanceof ArrayBuffer)
32
+ return o.byteLength + OBJECT_COST;
33
+ if (depth >= maxDepth)
34
+ return OBJECT_COST;
35
+ let n = OBJECT_COST;
36
+ if (Array.isArray(o)) {
37
+ for (const item of o)
38
+ n += SLOT_COST + walk(item, depth + 1);
39
+ return n;
40
+ }
41
+ if (o instanceof Map) {
42
+ for (const [k, item] of o)
43
+ n += walk(k, depth + 1) + walk(item, depth + 1);
44
+ return n;
45
+ }
46
+ if (o instanceof Set) {
47
+ for (const item of o)
48
+ n += SLOT_COST + walk(item, depth + 1);
49
+ return n;
50
+ }
51
+ for (const k of Object.keys(o))
52
+ n += k.length + SLOT_COST + walk(o[k], depth + 1);
53
+ return n;
54
+ };
55
+ return walk(value, 0);
56
+ }
57
+ /** The default memory budget of the render caches, in bytes. */
58
+ export const DEFAULT_CACHE_BYTES = 64 * 1024 * 1024;
59
+ /**
60
+ * The byte budgets of the in-memory caches, from KRATE_SSR_CACHE_BYTES (the
61
+ * total for one process; 0 or unset is the default). Rendered pages get half,
62
+ * PPR regions and the data cache a quarter each.
63
+ */
64
+ export function cacheByteBudgets(total) {
65
+ const t = total && total > 0 ? total : DEFAULT_CACHE_BYTES;
66
+ return { pages: Math.floor(t / 2), regions: Math.floor(t / 4), data: Math.floor(t / 4) };
67
+ }
68
+ export function cacheBytesFromEnv(env) {
69
+ const n = Number(env?.KRATE_SSR_CACHE_BYTES);
70
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
71
+ }
@@ -1,17 +1,30 @@
1
+ export interface ByteLimit<V> {
2
+ maxBytes: number;
3
+ sizeOf: (value: V) => number;
4
+ }
1
5
  export declare class SegmentedLRU<V> {
2
6
  private probation;
3
7
  private protectedSeg;
4
8
  private readonly max;
5
9
  private readonly protectedMax;
6
- constructor(maxSize: number);
10
+ private readonly limit?;
11
+ private readonly sizes;
12
+ private used;
13
+ constructor(maxSize: number, limit?: ByteLimit<V>);
7
14
  get size(): number;
15
+ /** The summed sizes of the entries (0 without a byte limit). */
16
+ get bytes(): number;
8
17
  has(key: string): boolean;
9
18
  /** Reads an entry without counting as a use. */
10
19
  peek(key: string): V | undefined;
11
20
  /** Reads an entry and counts the use: probation entries are promoted. */
12
21
  get(key: string): V | undefined;
22
+ private demoteColdest;
13
23
  /** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
14
24
  set(key: string, value: V): Array<[string, V]>;
25
+ private evictOldest;
26
+ private fitBytes;
27
+ private account;
15
28
  delete(key: string): boolean;
16
29
  clear(): void;
17
30
  keys(): string[];
@@ -6,9 +6,13 @@
6
6
  // flood of one-off keys only churns probation and never reaches the entries
7
7
  // that were requested twice.
8
8
  export class SegmentedLRU {
9
- constructor(maxSize) {
9
+ constructor(maxSize, limit) {
10
10
  this.probation = new Map();
11
11
  this.protectedSeg = new Map();
12
+ this.sizes = new Map();
13
+ this.used = 0;
14
+ if (limit && limit.maxBytes > 0)
15
+ this.limit = limit;
12
16
  this.max = Math.max(1, Math.floor(maxSize));
13
17
  // At least one probation slot, so a new entry can always be admitted.
14
18
  this.protectedMax = Math.min(this.max - 1, Math.max(1, Math.floor(this.max * 0.8)));
@@ -16,6 +20,10 @@ export class SegmentedLRU {
16
20
  get size() {
17
21
  return this.probation.size + this.protectedSeg.size;
18
22
  }
23
+ /** The summed sizes of the entries (0 without a byte limit). */
24
+ get bytes() {
25
+ return this.used;
26
+ }
19
27
  has(key) {
20
28
  return this.protectedSeg.has(key) || this.probation.has(key);
21
29
  }
@@ -40,43 +48,104 @@ export class SegmentedLRU {
40
48
  return cold;
41
49
  }
42
50
  this.protectedSeg.set(key, cold);
43
- if (this.protectedSeg.size > this.protectedMax) {
44
- // The coldest protected entry goes back to probation's newest slot.
45
- const demoted = this.protectedSeg.keys().next().value;
46
- const v = this.protectedSeg.get(demoted);
47
- this.protectedSeg.delete(demoted);
48
- this.probation.set(demoted, v);
51
+ if (this.protectedSeg.size > this.protectedMax)
52
+ this.demoteColdest();
53
+ if (this.limit) {
54
+ // Protected entries keep at most 80% of the bytes too, so probation
55
+ // always has room and new entries never flush the hot set.
56
+ const cap = this.limit.maxBytes * 0.8;
57
+ let hot = 0;
58
+ for (const k of this.protectedSeg.keys())
59
+ hot += this.sizes.get(k) || 0;
60
+ while (hot > cap && this.protectedSeg.size > 1)
61
+ hot -= this.sizes.get(this.demoteColdest()) || 0;
49
62
  }
50
63
  return cold;
51
64
  }
65
+ // demoteColdest moves the coldest protected entry to probation's newest
66
+ // slot and returns its key.
67
+ demoteColdest() {
68
+ const demoted = this.protectedSeg.keys().next().value;
69
+ const v = this.protectedSeg.get(demoted);
70
+ this.protectedSeg.delete(demoted);
71
+ this.probation.set(demoted, v);
72
+ return demoted;
73
+ }
52
74
  /** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
53
75
  set(key, value) {
54
- if (this.protectedSeg.has(key)) {
55
- this.protectedSeg.delete(key);
56
- this.protectedSeg.set(key, value);
57
- return [];
76
+ const n = this.limit ? Math.max(0, this.limit.sizeOf(value)) : 0;
77
+ if (this.limit && n > this.limit.maxBytes) {
78
+ // Too large to cache: drop any older copy instead of keeping it stale.
79
+ const old = this.peek(key);
80
+ if (old === undefined)
81
+ return [];
82
+ this.delete(key);
83
+ return [[key, old]];
58
84
  }
59
- if (this.probation.has(key)) {
60
- this.probation.delete(key);
61
- this.probation.set(key, value);
62
- return [];
85
+ const seg = this.protectedSeg.has(key) ? this.protectedSeg : this.probation.has(key) ? this.probation : null;
86
+ if (seg) {
87
+ seg.delete(key);
88
+ seg.set(key, value);
89
+ this.account(key, n);
90
+ return this.fitBytes(key);
63
91
  }
64
92
  const evicted = [];
65
- while (this.size >= this.max) {
66
- const seg = this.probation.size > 0 ? this.probation : this.protectedSeg;
67
- const oldest = seg.keys().next().value;
68
- evicted.push([oldest, seg.get(oldest)]);
69
- seg.delete(oldest);
93
+ while (this.size > 0 && (this.size >= this.max || (this.limit && this.used + n > this.limit.maxBytes))) {
94
+ evicted.push(this.evictOldest());
70
95
  }
71
96
  this.probation.set(key, value);
97
+ this.account(key, n);
72
98
  return evicted;
73
99
  }
100
+ // evictOldest removes the coldest entry: probation first, then protected.
101
+ evictOldest() {
102
+ const seg = this.probation.size > 0 ? this.probation : this.protectedSeg;
103
+ const oldest = seg.keys().next().value;
104
+ const v = seg.get(oldest);
105
+ seg.delete(oldest);
106
+ this.account(oldest, 0);
107
+ return [oldest, v];
108
+ }
109
+ // fitBytes evicts other entries, coldest first, until the sizes fit the
110
+ // limit again.
111
+ fitBytes(keep) {
112
+ const evicted = [];
113
+ if (!this.limit || this.used <= this.limit.maxBytes)
114
+ return evicted;
115
+ for (const seg of [this.probation, this.protectedSeg]) {
116
+ for (const k of [...seg.keys()]) {
117
+ if (this.used <= this.limit.maxBytes)
118
+ return evicted;
119
+ if (k === keep)
120
+ continue;
121
+ evicted.push([k, seg.get(k)]);
122
+ seg.delete(k);
123
+ this.account(k, 0);
124
+ }
125
+ }
126
+ return evicted;
127
+ }
128
+ account(key, n) {
129
+ if (!this.limit)
130
+ return;
131
+ this.used -= this.sizes.get(key) || 0;
132
+ if (n > 0)
133
+ this.sizes.set(key, n);
134
+ else
135
+ this.sizes.delete(key);
136
+ this.used += n;
137
+ }
74
138
  delete(key) {
75
- return this.protectedSeg.delete(key) || this.probation.delete(key);
139
+ const gone = this.protectedSeg.delete(key) || this.probation.delete(key);
140
+ if (gone)
141
+ this.account(key, 0);
142
+ return gone;
76
143
  }
77
144
  clear() {
78
145
  this.probation.clear();
79
146
  this.protectedSeg.clear();
147
+ this.sizes.clear();
148
+ this.used = 0;
80
149
  }
81
150
  keys() {
82
151
  return [...this.probation.keys(), ...this.protectedSeg.keys()];
@@ -65,6 +65,7 @@ export interface HandlerConfig {
65
65
  ssr: {
66
66
  timeout: number;
67
67
  maxCacheSize: number;
68
+ cacheBytes?: number;
68
69
  ppr: boolean;
69
70
  pprRevalidate: number;
70
71
  };
@@ -11,6 +11,7 @@
11
11
  // generates (`krate deploy`), and static files come from a pluggable layer.
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  import { createSSRCore, MemoryIsrStore, } from "./ssr-core.js";
14
+ import { cacheByteBudgets } from "./memsize.js";
14
15
  import { runAfterTasks } from "./after.js";
15
16
  import { platformWaitUntil } from "./platform.js";
16
17
  import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
@@ -318,7 +319,7 @@ export function createKrateHandler(options) {
318
319
  installRenderStore(new AsyncLocalStorage());
319
320
  patchFetch();
320
321
  // The ISR and data caches: this instance's memory, or the shared cache adapter.
321
- const memoryIsr = new MemoryIsrStore(cfg.ssr.maxCacheSize > 0 ? cfg.ssr.maxCacheSize : 512);
322
+ const memoryIsr = new MemoryIsrStore(cfg.ssr.maxCacheSize > 0 ? cfg.ssr.maxCacheSize : 512, cacheByteBudgets(cfg.ssr.cacheBytes).pages);
322
323
  const sharedCache = options.isrStore
323
324
  ? { store: options.isrStore, ready: Promise.resolve(null) }
324
325
  : isrStoreFor(options.cache ?? cacheSpecFromConfig(cfg.cache), memoryIsr);
@@ -344,6 +345,7 @@ export function createKrateHandler(options) {
344
345
  return fn;
345
346
  },
346
347
  maxCacheSize: cfg.ssr.maxCacheSize,
348
+ cacheBytes: cfg.ssr.cacheBytes,
347
349
  timeoutMs: cfg.ssr.timeout > 0 ? cfg.ssr.timeout : 5000,
348
350
  ppr: cfg.ssr.ppr,
349
351
  pprRevalidate: cfg.ssr.pprRevalidate,
@@ -14,6 +14,7 @@ import { encodeFrame, REGION_FRAMES_TYPE, wantsRegionFrames } from "./region-wir
14
14
  import { installRenderStore, patchFetch } from "./cache-scope.js";
15
15
  import { cacheSpecFromEnv } from "./cache-adapter.js";
16
16
  import { isrStoreFor } from "./shared-isr.js";
17
+ import { cacheByteBudgets, cacheBytesFromEnv } from "./memsize.js";
17
18
  import { registerLanguage, setFenceResolver } from "./highlight.js";
18
19
  import { installProcessGuards } from "./process-guard.js";
19
20
  // Render cache scopes (tags / revalidate windows read during a render) and the
@@ -289,7 +290,8 @@ function loadRuntimeRenderer(relPath) {
289
290
  }
290
291
  // Render core
291
292
  const pprEnabledEnv = process.env.KRATE_PPR === "1";
292
- const isrMemory = new MemoryIsrStore(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512);
293
+ const cacheBytes = cacheBytesFromEnv(process.env);
294
+ const isrMemory = new MemoryIsrStore(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512, cacheByteBudgets(cacheBytes).pages);
293
295
  // With a shared cache adapter (KRATE_CACHE) the ISR cache and the data cache live
294
296
  // in the adapter, so every instance serves and invalidates the same pages.
295
297
  const sharedCache = isrStoreFor(cacheSpecFromEnv(process.env), isrMemory);
@@ -300,6 +302,7 @@ const core = createSSRCore({
300
302
  loadPageModule,
301
303
  loadRuntimeRenderer,
302
304
  maxCacheSize: parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512,
305
+ cacheBytes,
303
306
  timeoutMs: parseInt(process.env.KRATE_SSR_TIMEOUT || "", 10) || 5000,
304
307
  ppr: pprEnabledEnv,
305
308
  pprRevalidate: parseInt(process.env.KRATE_PPR_REVALIDATE || "", 10) || 60,
package/dist/server.d.ts CHANGED
@@ -33,11 +33,13 @@ interface JSXElement {
33
33
  type: string | Function | object | symbol;
34
34
  props: Record<string, any>;
35
35
  children: JSXNode[];
36
+ /** The element's React key, when it has one (a client island carries it, see clientBoundary). */
37
+ key?: string;
36
38
  }
37
39
  export declare function Fragment(_props: {
38
40
  children?: JSXNode;
39
41
  }): JSXNode;
40
- export declare function jsx(type: string | Function | object | symbol, props: Record<string, any>, _key?: string): JSXElement;
42
+ export declare function jsx(type: string | Function | object | symbol, props: Record<string, any>, key?: string): JSXElement;
41
43
  export declare const jsxs: typeof jsx;
42
44
  /**
43
45
  * ServerErrorBoundary is the request-time form of a segment's error.tsx under
package/dist/server.js CHANGED
@@ -101,14 +101,19 @@ function base64url(s) {
101
101
  export function Fragment(_props) {
102
102
  return _props.children ?? [];
103
103
  }
104
- export function jsx(type, props, _key) {
104
+ export function jsx(type, props, key) {
105
105
  const { children, ...rest } = props ?? {};
106
106
  const childArray = Array.isArray(children)
107
107
  ? children.flat(Infinity)
108
108
  : children != null
109
109
  ? [children]
110
110
  : [];
111
- return { type, props: rest, children: childArray };
111
+ const el = { type, props: rest, children: childArray };
112
+ // The automatic runtime passes the key apart; createElement leaves it in props.
113
+ const k = key ?? rest.key;
114
+ if (k != null)
115
+ el.key = String(k);
116
+ return el;
112
117
  }
113
118
  export const jsxs = jsx;
114
119
  // HTML Rendering
@@ -217,7 +222,11 @@ function normalizeNode(node) {
217
222
  return node;
218
223
  const { children, ref: _ref, ...rest } = node.props ?? {};
219
224
  const kids = Array.isArray(children) ? children.flat(Infinity) : children != null ? [children] : [];
220
- return { type: node.type, props: rest, children: kids };
225
+ const el = { type: node.type, props: rest, children: kids };
226
+ const k = node.key;
227
+ if (k != null)
228
+ el.key = String(k);
229
+ return el;
221
230
  }
222
231
  function foreignContext(type) {
223
232
  if (type.$$typeof === R_PROVIDER)
@@ -515,7 +524,7 @@ async function expandComponent(node, vals) {
515
524
  return { out: consumerChild(callProps)(vals?.has(ctx) ? vals.get(ctx) : ctx._currentValue), vals };
516
525
  }
517
526
  // A client boundary also gets the context values in scope (slotValues).
518
- let out = fn.__krateClient ? fn(callProps, vals, RENDER_CALL) : fn(callProps);
527
+ let out = fn.__krateClient ? fn(callProps, vals, RENDER_CALL, node.key) : fn(callProps);
519
528
  if (isThenable(out))
520
529
  out = await out;
521
530
  if (fn.__krateForeignProvider) {
@@ -551,7 +560,7 @@ function renderElement(el) {
551
560
  throw asyncInSyncRender("A lazy component");
552
561
  throw e;
553
562
  }
554
- return renderElement({ type: fn, props, children });
563
+ return renderElement({ ...el, type: fn });
555
564
  }
556
565
  if (typeof type === "function") {
557
566
  if (isClassComponent(type)) {
@@ -563,7 +572,9 @@ function renderElement(el) {
563
572
  return renderNode(classFallback(type, instance, error));
564
573
  }
565
574
  }
566
- const result = type.__krateClient ? type({ ...props, children }, undefined, RENDER_CALL) : type({ ...props, children });
575
+ const result = type.__krateClient
576
+ ? type({ ...props, children }, undefined, RENDER_CALL, el.key)
577
+ : type({ ...props, children });
567
578
  if (isThenable(result))
568
579
  throw asyncInSyncRender(`<${componentName(type)}>`);
569
580
  return withProviderValue(type, props, () => renderNode(result));
@@ -836,8 +847,14 @@ export const ISLAND_CLOSE = "<!--/krate-island-->";
836
847
  // islandOpen is the opening comment of a Preact island: its module, export,
837
848
  // chunk and props as JSON. "<", ">" and "--" are escaped (they occur only in
838
849
  // strings), so no value can end the comment or open another one.
839
- function islandOpen(moduleId, exportName, src, props, ids) {
840
- const json = JSON.stringify({ m: moduleId, e: exportName, s: src, i: ids, p: props })
850
+ function islandOpen(moduleId, exportName, src, props, ids, key) {
851
+ const head = { m: moduleId, e: exportName, s: src, i: ids };
852
+ // The React key: the router keeps a keyed island's state by key, not by
853
+ // position, across a refresh (see island-swap.ts).
854
+ if (key != null)
855
+ head.k = key;
856
+ head.p = props;
857
+ const json = JSON.stringify(head)
841
858
  .replace(/</g, "\\u003c")
842
859
  .replace(/>/g, "\\u003e")
843
860
  .replace(/--/g, "-\\u002d");
@@ -845,22 +862,28 @@ function islandOpen(moduleId, exportName, src, props, ids) {
845
862
  }
846
863
  // islandIdPrefix names the next island of a component in the render that is
847
864
  // running: a hash of its module and export, and how many islands of that
848
- // component came before it in this document. useId() numbers from 0 inside
865
+ // component came before it in this document (for a keyed island, how many
866
+ // before it had its key, and a hash of the key). useId() numbers from 0 inside
849
867
  // each island, so the prefix is what keeps ids unique across the page. The
850
- // router pairs the n-th island of a component in the live page with the n-th
851
- // one in the new markup, so a page that a navigation swaps in never reuses the
852
- // prefix of an island the swap keeps.
868
+ // router pairs the n-th unkeyed island of a component in the live page with
869
+ // the n-th one in the new markup, and a keyed one with the one of the same
870
+ // key, so a page that a navigation swaps in never reuses the prefix of an
871
+ // island the swap keeps.
853
872
  const looseIslands = new Map();
854
- function islandIdPrefix(moduleId, exportName) {
855
- const key = moduleId + "#" + exportName;
873
+ function fnv36(s) {
874
+ let h = 0x811C9DC5;
875
+ for (let i = 0; i < s.length; i++)
876
+ h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0;
877
+ return h.toString(36).padStart(7, "0");
878
+ }
879
+ function islandIdPrefix(moduleId, exportName, key) {
880
+ const component = moduleId + "#" + exportName;
856
881
  const scope = currentRenderScope();
857
882
  const seen = scope ? (scope.islands ?? (scope.islands = new Map())) : looseIslands;
858
- const n = seen.get(key) ?? 0;
859
- seen.set(key, n + 1);
860
- let h = 0x811C9DC5;
861
- for (let i = 0; i < key.length; i++)
862
- h = Math.imul(h ^ key.charCodeAt(i), 0x01000193) >>> 0;
863
- return h.toString(36).padStart(7, "0") + "_" + n;
883
+ const counter = key == null ? component : component + "\u0000" + key;
884
+ const n = seen.get(counter) ?? 0;
885
+ seen.set(counter, n + 1);
886
+ return fnv36(component) + "_" + (key == null ? "" : "k" + fnv36(key) + "_") + n;
864
887
  }
865
888
  const warnedUncloneable = new Set();
866
889
  // RENDER_CALL is the third argument the renderer passes when it renders a
@@ -933,15 +956,17 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
933
956
  // Called by user code, the boundary fails here and now. An async function
934
957
  // would hand back a rejected promise the caller never awaits, and that
935
958
  // unhandled rejection would take the renderer process down.
936
- const Boundary = (props, vals, from) => {
959
+ const Boundary = (props, vals, from, key) => {
937
960
  if (from !== RENDER_CALL)
938
961
  throw clientCallError(exportName, name);
939
- return renderBoundary(props, vals);
962
+ return renderBoundary(props, vals, key);
940
963
  };
941
- const renderBoundary = async (props, vals) => {
964
+ const renderBoundary = async (props, vals, elementKey) => {
965
+ // A key is not a prop (React leaves it out of props too).
966
+ const { children, key: propKey, ...rest } = props || {};
967
+ const key = elementKey ?? (propKey != null ? String(propKey) : undefined);
942
968
  // Taken before the first await, so islands number in render order.
943
- const ids = islandIdPrefix(moduleId, exportName);
944
- const { children, ...rest } = props || {};
969
+ const ids = islandIdPrefix(moduleId, exportName, key);
945
970
  const slots = [];
946
971
  const slotCtx = { hydrate: false, component: name, slots, vals };
947
972
  const data = await clientProps(rest, slotCtx, flight);
@@ -984,9 +1009,10 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
984
1009
  // element of its own; a Preact island hydrates the nodes between its two
985
1010
  // comments in place.
986
1011
  if (!flight)
987
- return raw(islandOpen(moduleId, exportName, src, data, ids) + html + ISLAND_CLOSE);
1012
+ return raw(islandOpen(moduleId, exportName, src, data, ids, key) + html + ISLAND_CLOSE);
1013
+ const keyAttr = key != null ? ` data-key="${escapeHTML(key)}"` : "";
988
1014
  return raw(propsScript(data) +
989
- `<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
1015
+ `<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}"${keyAttr} ` +
990
1016
  `data-src="${escapeHTML(src)}">${html}</krate-island>`);
991
1017
  };
992
1018
  Object.defineProperty(Boundary, "name", { value: name });
@@ -1,4 +1,5 @@
1
1
  // The ISR page cache on a shared cache adapter (see cache-adapter.ts).
2
+ import { cacheByteBudgets } from "./memsize.js";
2
3
  import { MemoryIsrStore, variantKey } from './ssr-core.js';
3
4
  import { installCacheAdapter, loadCacheAdapter, tagName } from './cache-adapter.js';
4
5
  const ISR_PREFIX = 'isr:';
@@ -11,7 +12,7 @@ export class SharedIsrStore {
11
12
  constructor(guard, ttlSeconds = 7 * 24 * 3600, maxMemory = 512) {
12
13
  this.guard = guard;
13
14
  this.ttlSeconds = ttlSeconds;
14
- this.memory = new MemoryIsrStore(maxMemory);
15
+ this.memory = new MemoryIsrStore(maxMemory, cacheByteBudgets().pages);
15
16
  }
16
17
  async get(key) {
17
18
  const r = await this.guard.call((a) => a.get(ISR_PREFIX + key));
@@ -80,11 +80,14 @@ export interface QueryTracker {
80
80
  }
81
81
  export declare function newQueryTracker(): QueryTracker;
82
82
  export declare function trackedQuery(query: Record<string, string> | undefined, t: QueryTracker): Record<string, string>;
83
+ export declare function cacheEntryBytes(e: CacheEntry): number;
83
84
  export declare class ISRCache {
84
85
  private cache;
85
86
  private byTag;
86
87
  private revalidationIntervals;
87
- constructor(maxSize?: number);
88
+ constructor(maxSize?: number, maxBytes?: number);
89
+ /** The approximate memory the cached pages take, in bytes. */
90
+ get bytes(): number;
88
91
  setRevalidation(route: string, seconds: number): void;
89
92
  get(key: string): CacheEntry | undefined;
90
93
  set(key: string, entry: CacheEntry): void;
@@ -116,6 +119,11 @@ export interface SSRCoreOptions {
116
119
  loadRuntimeRenderer(relPath: string): (props: string | Record<string, any>) => string | Promise<string>;
117
120
  /** ISR/region cache entry bound (default 512). */
118
121
  maxCacheSize?: number;
122
+ /**
123
+ * Memory budget of the in-memory render caches in bytes (default 64 MiB):
124
+ * rendered pages get half, PPR regions a quarter (see cacheByteBudgets).
125
+ */
126
+ cacheBytes?: number;
119
127
  /** Per-render timeout in ms (default 5000, 0 disables). */
120
128
  timeoutMs?: number;
121
129
  ppr?: boolean;
@@ -151,7 +159,7 @@ export interface IsrStore {
151
159
  /** The in-process IsrStore: a bounded map with a tag index. */
152
160
  export declare class MemoryIsrStore implements IsrStore {
153
161
  readonly cache: ISRCache;
154
- constructor(maxSize?: number);
162
+ constructor(maxSize?: number, maxBytes?: number);
155
163
  get(key: string): CacheEntry | undefined;
156
164
  set(key: string, entry: CacheEntry): void;
157
165
  deleteRoute(route: string): number;
package/dist/ssr-core.js CHANGED
@@ -9,6 +9,7 @@ import { sha256Hex as portableSha256Hex } from "./sha256.js";
9
9
  import { isNotFoundSignal, isDynamicUsageError, dynamicUsageError, dynamicUsageReason, accessDeniedStatus, parseCookieHeader, redirectTarget, redirectStatus, thenable, thenableRecord, } from "./request-context.js";
10
10
  import { HEAD_CLOSE, HEAD_OPEN, takeHead } from "./head-tags.js";
11
11
  import { metadataHeadTags } from "./metadata.js";
12
+ import { approxBytes, cacheByteBudgets } from "./memsize.js";
12
13
  import { SegmentedLRU } from "./segmented-lru.js";
13
14
  import { cacheRuntime, routeDataTag, withCacheScope, } from "./cache-scope.js";
14
15
  // ISR Cache (variant-aware, SWR, persisted)
@@ -54,11 +55,20 @@ export function trackedQuery(query, t) {
54
55
  },
55
56
  });
56
57
  }
58
+ // cacheEntryBytes is the approximate size of a cached page: its HTML plus
59
+ // the small records kept with it.
60
+ export function cacheEntryBytes(e) {
61
+ return e.html.length + approxBytes({ params: e.params, query: e.query, tags: e.tags }) + 64;
62
+ }
57
63
  export class ISRCache {
58
- constructor(maxSize = 512) {
64
+ constructor(maxSize = 512, maxBytes = 0) {
59
65
  this.byTag = new Map();
60
66
  this.revalidationIntervals = new Map(); // route -> seconds
61
- this.cache = new SegmentedLRU(maxSize);
67
+ this.cache = new SegmentedLRU(maxSize, maxBytes > 0 ? { maxBytes, sizeOf: cacheEntryBytes } : undefined);
68
+ }
69
+ /** The approximate memory the cached pages take, in bytes. */
70
+ get bytes() {
71
+ return this.cache.bytes;
62
72
  }
63
73
  setRevalidation(route, seconds) {
64
74
  this.revalidationIntervals.set(route, seconds);
@@ -185,8 +195,8 @@ export class ISRCache {
185
195
  }
186
196
  /** The in-process IsrStore: a bounded map with a tag index. */
187
197
  export class MemoryIsrStore {
188
- constructor(maxSize = 512) {
189
- this.cache = new ISRCache(maxSize);
198
+ constructor(maxSize = 512, maxBytes = 0) {
199
+ this.cache = new ISRCache(maxSize, maxBytes);
190
200
  }
191
201
  get(key) {
192
202
  return this.cache.get(key);
@@ -295,7 +305,7 @@ export function createSSRCore(opts) {
295
305
  }
296
306
  // ISR cache size and the render timeout are configurable via the compiler
297
307
  // (ssr.maxCacheSize / ssr.timeout), which exports them to the sidecar env.
298
- const isrStore = opts.isrStore || new MemoryIsrStore(opts.maxCacheSize && opts.maxCacheSize > 0 ? opts.maxCacheSize : 512);
308
+ const isrStore = opts.isrStore || new MemoryIsrStore(opts.maxCacheSize && opts.maxCacheSize > 0 ? opts.maxCacheSize : 512, cacheByteBudgets(opts.cacheBytes).pages);
299
309
  // pageIntervals remembers each ISR page's revalidate window (seconds).
300
310
  const pageIntervals = new Map();
301
311
  // entryStale: the entry is older than its page window, or than the smaller
@@ -638,7 +648,10 @@ export function createSSRCore(opts) {
638
648
  // Bounded like the page cache, and with the same segmented eviction: a
639
649
  // client minting params variants cannot push out the regions hit twice.
640
650
  const REGION_CACHE_MAX = opts.maxCacheSize && opts.maxCacheSize > 0 ? opts.maxCacheSize : 512;
641
- const regionCache = new SegmentedLRU(REGION_CACHE_MAX);
651
+ const regionCache = new SegmentedLRU(REGION_CACHE_MAX, {
652
+ maxBytes: cacheByteBudgets(opts.cacheBytes).regions,
653
+ sizeOf: (e) => e.html.length + e.route.length + e.paramsKey.length + approxBytes(e.tags) + 64,
654
+ });
642
655
  const inFlightRegionRevalidations = new Map();
643
656
  function paramsKeyOf(params) {
644
657
  return variantKey({ route: "", params });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-rc.15",
3
+ "version": "0.5.0-rc.16",
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",
@@ -125,7 +125,8 @@
125
125
  },
126
126
  "files": [
127
127
  "dist",
128
- "!dist/**/*.test.*"
128
+ "!dist/**/*.test.*",
129
+ "NOTICE"
129
130
  ],
130
131
  "devDependencies": {
131
132
  "@types/node": "^26.2.0",