@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
@@ -0,0 +1,311 @@
1
+ /**
2
+ * Server data cache and render cache scopes.
3
+ *
4
+ * This module holds the process-wide state behind `@krate/runtime/cache`:
5
+ *
6
+ * - The render scope: the SSR renderer runs every page and region render
7
+ * inside `withCacheScope`, which records the cache tags, the smallest
8
+ * revalidate window and any no-store read the render made. The renderer
9
+ * stores the tags on its ISR/region cache entry so `revalidateTag` can find
10
+ * the entries a tag fed.
11
+ * - The data cache: `unstable_cache` results and `fetch` responses cached via
12
+ * `{ next: { revalidate, tags } }` or `cache: "force-cache"`, keyed by the
13
+ * call, expired by revalidate seconds and indexed by tag.
14
+ * - The `fetch` wrapper that applies those options.
15
+ *
16
+ * State lives on `globalThis` under `Symbol.for` keys, so the copy bundled
17
+ * into the renderer and the copy a page bundle imports share it. The module
18
+ * has no Node imports: the embedded QuickJS API runtime bundles it too, and
19
+ * there the data cache is backed by the Go host (`_go_cache_get/_go_cache_set`).
20
+ */
21
+ const STATE_KEY = Symbol.for('krate.cache.runtime');
22
+ const REVALIDATE_STORE_KEY = Symbol.for('krate.revalidate.store');
23
+ /** In-process data cache with tag index and FIFO bound. */
24
+ export class DataCache {
25
+ constructor(max = 1000) {
26
+ this.max = max;
27
+ this.map = new Map();
28
+ this.byTag = new Map();
29
+ }
30
+ get size() {
31
+ return this.map.size;
32
+ }
33
+ get(key) {
34
+ const e = this.map.get(key);
35
+ if (!e)
36
+ return undefined;
37
+ if (e.expires <= Date.now()) {
38
+ this.delete(key);
39
+ return undefined;
40
+ }
41
+ return e.value;
42
+ }
43
+ set(key, value, ttlSeconds, tags) {
44
+ if (!(ttlSeconds > 0))
45
+ return;
46
+ if (this.map.has(key))
47
+ this.delete(key);
48
+ while (this.map.size >= this.max) {
49
+ const oldest = this.map.keys().next().value;
50
+ if (oldest === undefined)
51
+ break;
52
+ this.delete(oldest);
53
+ }
54
+ const expires = ttlSeconds === Infinity ? Infinity : Date.now() + ttlSeconds * 1000;
55
+ this.map.set(key, { value, expires, tags: [...tags] });
56
+ for (const t of tags) {
57
+ let keys = this.byTag.get(t);
58
+ if (!keys)
59
+ this.byTag.set(t, (keys = new Set()));
60
+ keys.add(key);
61
+ }
62
+ }
63
+ delete(key) {
64
+ const e = this.map.get(key);
65
+ if (!e)
66
+ return;
67
+ this.map.delete(key);
68
+ for (const t of e.tags) {
69
+ const keys = this.byTag.get(t);
70
+ if (keys) {
71
+ keys.delete(key);
72
+ if (keys.size === 0)
73
+ this.byTag.delete(t);
74
+ }
75
+ }
76
+ }
77
+ /** Removes every entry carrying one of tags; returns how many. */
78
+ invalidateTags(tags) {
79
+ let n = 0;
80
+ for (const t of tags) {
81
+ const keys = this.byTag.get(t);
82
+ if (!keys)
83
+ continue;
84
+ for (const k of [...keys]) {
85
+ if (this.map.has(k))
86
+ n++;
87
+ this.delete(k);
88
+ }
89
+ }
90
+ return n;
91
+ }
92
+ clear() {
93
+ this.map.clear();
94
+ this.byTag.clear();
95
+ }
96
+ }
97
+ /** The shared cache runtime, created on first use. */
98
+ export function cacheRuntime() {
99
+ const g = globalThis;
100
+ let rt = g[STATE_KEY];
101
+ if (!rt) {
102
+ const max = envNumber('KRATE_DATA_CACHE_MAX') || 1000;
103
+ const created = {
104
+ dataCache: new DataCache(max),
105
+ epoch: 0,
106
+ invalidate(payload) {
107
+ created.epoch++;
108
+ const tags = Array.isArray(payload.tags) ? payload.tags.filter((t) => typeof t === 'string') : [];
109
+ return { dataEntries: tags.length ? created.dataCache.invalidateTags(tags) : 0 };
110
+ },
111
+ };
112
+ rt = created;
113
+ g[STATE_KEY] = rt;
114
+ }
115
+ return rt;
116
+ }
117
+ function envNumber(name) {
118
+ const proc = globalThis.process;
119
+ const v = proc && proc.env ? proc.env[name] : undefined;
120
+ const n = v ? parseInt(v, 10) : NaN;
121
+ return Number.isFinite(n) && n > 0 ? n : 0;
122
+ }
123
+ /** Installs the render scope storage (an AsyncLocalStorage). Renderer only. */
124
+ export function installRenderStore(store) {
125
+ cacheRuntime().renderStore = store;
126
+ }
127
+ /** The scope of the render currently running, if any. */
128
+ export function currentRenderScope() {
129
+ const store = cacheRuntime().renderStore;
130
+ return store ? store.getStore() : undefined;
131
+ }
132
+ /** The pending-revalidation scope of the current server action / API request. */
133
+ export function currentRevalidateScope() {
134
+ const store = globalThis[REVALIDATE_STORE_KEY];
135
+ return store && typeof store.getStore === 'function' ? store.getStore() : undefined;
136
+ }
137
+ /**
138
+ * Runs fn inside a fresh render scope and returns its result together with
139
+ * the scope (tags, revalidate window, noStore) and whether an invalidation
140
+ * happened while it ran (then the result must not be cached).
141
+ */
142
+ export async function withCacheScope(route, fn) {
143
+ const rt = cacheRuntime();
144
+ const scope = { route, tags: new Set(), revalidate: 0, noStore: false };
145
+ const epoch = rt.epoch;
146
+ const store = rt.renderStore;
147
+ const result = store ? await store.run(scope, () => Promise.resolve().then(fn)) : await fn();
148
+ return { result, scope, invalidated: rt.epoch !== epoch };
149
+ }
150
+ /**
151
+ * Implicit tag carried by data-cache entries first stored while rendering
152
+ * route, so revalidatePath(route) also drops the data that render cached.
153
+ */
154
+ export function routeDataTag(route) {
155
+ return '_krate_route:' + route;
156
+ }
157
+ /** Records tags and a revalidate window on the current render scope. */
158
+ export function recordCacheRead(tags, revalidate) {
159
+ const scope = currentRenderScope();
160
+ if (!scope)
161
+ return;
162
+ if (tags)
163
+ for (const t of tags)
164
+ if (typeof t === 'string' && t)
165
+ scope.tags.add(t);
166
+ if (revalidate === 0)
167
+ scope.noStore = true;
168
+ else if (typeof revalidate === 'number' && revalidate > 0 && (scope.revalidate === 0 || revalidate < scope.revalidate)) {
169
+ scope.revalidate = revalidate;
170
+ }
171
+ }
172
+ /** Marks the current render as uncacheable. Outside a render it has no effect. */
173
+ export function markNoStore() {
174
+ const scope = currentRenderScope();
175
+ if (scope)
176
+ scope.noStore = true;
177
+ }
178
+ // Data cache access. In QuickJS the Go host owns the cache (shared by every
179
+ // VM worker and invalidated with the rest of the host's caches); values cross
180
+ // the bridge as JSON.
181
+ function goBridge() {
182
+ const g = globalThis;
183
+ return typeof g._go_cache_get === 'function' && typeof g._go_cache_set === 'function'
184
+ ? g
185
+ : null;
186
+ }
187
+ /** Reads a JSON value from the data cache; undefined on a miss. */
188
+ export function dataCacheGetJSON(key) {
189
+ const go = goBridge();
190
+ if (go) {
191
+ const v = go._go_cache_get(key);
192
+ return typeof v === 'string' && v !== '' ? v : undefined;
193
+ }
194
+ const v = cacheRuntime().dataCache.get(key);
195
+ return typeof v === 'string' ? v : undefined;
196
+ }
197
+ /**
198
+ * Stores a JSON value unless an invalidation happened since epoch. Inside a
199
+ * render the entry also gets the route's implicit tag (see routeDataTag).
200
+ */
201
+ export function dataCacheSetJSON(key, json, ttlSeconds, tags, epoch) {
202
+ const scope = currentRenderScope();
203
+ if (scope)
204
+ tags = [...tags, routeDataTag(scope.route)];
205
+ const go = goBridge();
206
+ if (go) {
207
+ go._go_cache_set(key, json, ttlSeconds === Infinity ? -1 : ttlSeconds, JSON.stringify(tags));
208
+ return;
209
+ }
210
+ const rt = cacheRuntime();
211
+ if (rt.epoch !== epoch)
212
+ return;
213
+ rt.dataCache.set(key, json, ttlSeconds, tags);
214
+ }
215
+ function toBase64(bytes) {
216
+ const B = globalThis.Buffer;
217
+ if (B)
218
+ return B.from(bytes).toString('base64');
219
+ let s = '';
220
+ for (let i = 0; i < bytes.length; i++)
221
+ s += String.fromCharCode(bytes[i]);
222
+ return btoa(s);
223
+ }
224
+ function fromBase64(b64) {
225
+ const B = globalThis.Buffer;
226
+ if (B)
227
+ return new Uint8Array(B.from(b64, 'base64'));
228
+ const s = atob(b64);
229
+ const out = new Uint8Array(s.length);
230
+ for (let i = 0; i < s.length; i++)
231
+ out[i] = s.charCodeAt(i);
232
+ return out;
233
+ }
234
+ function requestURL(input) {
235
+ if (typeof input === 'string')
236
+ return input;
237
+ if (input && typeof input.href === 'string')
238
+ return input.href;
239
+ if (input && typeof input.url === 'string')
240
+ return input.url;
241
+ return String(input);
242
+ }
243
+ function fetchCacheKey(method, url, init) {
244
+ const headers = [];
245
+ if (init && init.headers) {
246
+ new Headers(init.headers).forEach((v, k) => headers.push([k, v]));
247
+ headers.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
248
+ }
249
+ return 'fetch:' + JSON.stringify([method, url, headers]);
250
+ }
251
+ /**
252
+ * Wraps globalThis.fetch once so Next-style cache options work in server
253
+ * code: `next.tags` are recorded on the current render, `next.revalidate: N`
254
+ * or `cache: "force-cache"` cache successful GET/HEAD responses (by method,
255
+ * URL and headers) for N seconds (indefinitely for force-cache or
256
+ * `revalidate: false`) under the given tags, and `cache: "no-store"` /
257
+ * `next.revalidate: 0` bypass the cache and make the render uncacheable.
258
+ * Requests without these options are passed through untouched.
259
+ */
260
+ export function patchFetch() {
261
+ const rt = cacheRuntime();
262
+ const g = globalThis;
263
+ if (rt.fetchPatched || typeof g.fetch !== 'function')
264
+ return;
265
+ const original = g.fetch.bind(globalThis);
266
+ rt.fetchPatched = true;
267
+ const wrapped = async (input, init) => {
268
+ const next = init && init.next;
269
+ const mode = init && init.cache;
270
+ if (!next && !mode)
271
+ return original(input, init);
272
+ const { next: _drop, ...rest } = init;
273
+ const plainInit = rest;
274
+ const tags = next && Array.isArray(next.tags) ? next.tags.filter((t) => typeof t === 'string' && t !== '') : [];
275
+ const revalidate = next ? next.revalidate : undefined;
276
+ recordCacheRead(tags, revalidate);
277
+ if (mode === 'no-store' || revalidate === 0) {
278
+ markNoStore();
279
+ return original(input, plainInit);
280
+ }
281
+ let ttl = 0;
282
+ if (typeof revalidate === 'number' && revalidate > 0)
283
+ ttl = revalidate;
284
+ else if (revalidate === false || mode === 'force-cache')
285
+ ttl = Infinity;
286
+ const method = String(plainInit.method || (input instanceof Request ? input.method : 'GET')).toUpperCase();
287
+ if (ttl === 0 || (method !== 'GET' && method !== 'HEAD'))
288
+ return original(input, plainInit);
289
+ const key = fetchCacheKey(method, requestURL(input), plainInit);
290
+ const hit = dataCacheGetJSON(key);
291
+ if (hit !== undefined) {
292
+ const c = JSON.parse(hit);
293
+ return new Response(method === 'HEAD' ? null : fromBase64(c.body), {
294
+ status: c.status,
295
+ statusText: c.statusText,
296
+ headers: c.headers,
297
+ });
298
+ }
299
+ const epoch = rt.epoch;
300
+ const res = await original(input, plainInit);
301
+ if (res.ok) {
302
+ const bytes = new Uint8Array(await res.clone().arrayBuffer());
303
+ const headers = [];
304
+ res.headers.forEach((v, k) => headers.push([k, v]));
305
+ const entry = { status: res.status, statusText: res.statusText, headers, body: toBase64(bytes) };
306
+ dataCacheSetJSON(key, JSON.stringify(entry), ttl, tags, epoch);
307
+ }
308
+ return res;
309
+ };
310
+ g.fetch = wrapped;
311
+ }
@@ -0,0 +1,55 @@
1
+ /** What `revalidatePath` invalidates: the page at path, or every page under it. */
2
+ export type RevalidatePathType = 'page' | 'layout';
3
+ /** A revalidation request as sent to the Krate host. */
4
+ export interface RevalidatePayload {
5
+ paths: Array<{
6
+ path: string;
7
+ type: RevalidatePathType;
8
+ }>;
9
+ tags: string[];
10
+ }
11
+ /** The host's answer: what was invalidated and what could not be. */
12
+ export interface RevalidateResult {
13
+ revalidated: Array<{
14
+ target: string;
15
+ kind: 'path' | 'tag';
16
+ routes?: string[];
17
+ }>;
18
+ skipped: Array<{
19
+ target: string;
20
+ reason: string;
21
+ }>;
22
+ }
23
+ /** Logs targets the host could not revalidate (static pages, unknown routes). */
24
+ export declare function reportSkippedRevalidations(result: RevalidateResult | null | undefined): void;
25
+ /** Sends a revalidation to the host (used outside a request scope). */
26
+ export declare function sendRevalidation(payload: RevalidatePayload): Promise<RevalidateResult>;
27
+ /**
28
+ * Invalidates the cached render of `path`. `type: "page"` (the default for a
29
+ * concrete URL) targets that page; a dynamic pattern such as `/blog/[slug]`
30
+ * targets every cached variant; `type: "layout"` targets every page under
31
+ * the path.
32
+ */
33
+ export declare function revalidatePath(path: string, type?: RevalidatePathType): void;
34
+ /** Invalidates every cached page render, region and data entry that read `tag`. */
35
+ export declare function revalidateTag(tag: string): void;
36
+ /** Options for `unstable_cache`. */
37
+ export interface UnstableCacheOptions {
38
+ /** Tags that `revalidateTag` can invalidate this entry by. */
39
+ tags?: string[];
40
+ /** Seconds to keep the result; false (default) keeps it until invalidated. */
41
+ revalidate?: number | false;
42
+ }
43
+ /**
44
+ * Caches the JSON-serializable result of an async function. The cache key is
45
+ * the function source, keyParts and the call arguments. Results expire after
46
+ * `revalidate` seconds (never when false/omitted) and are invalidated by
47
+ * `revalidateTag` for any of `tags`. When called during a render, the tags
48
+ * and window are recorded on the page's cache entry too.
49
+ */
50
+ export declare function unstable_cache<A extends unknown[], R>(fn: (...args: A) => Promise<R> | R, keyParts?: string[], options?: UnstableCacheOptions): (...args: A) => Promise<R>;
51
+ /**
52
+ * Opts the current render out of caching: an ISR page rendered with it is
53
+ * served fresh and not stored. It has no effect outside a render.
54
+ */
55
+ export declare function unstable_noStore(): void;
package/dist/cache.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * `@krate/runtime/cache` - on-demand revalidation and the server data cache,
3
+ * mirroring `next/cache`. Also re-exported from `@krate/runtime/server`.
4
+ *
5
+ * - `revalidatePath(path, type?)` and `revalidateTag(tag)` invalidate the
6
+ * host's ISR page cache, region caches and data cache. Inside a server
7
+ * action or an API route the invalidation is applied before the response
8
+ * is sent (read-your-writes); actions also tell the client which paths and
9
+ * tags changed. They throw when called while a page renders or outside the
10
+ * Krate server (for example during a build).
11
+ * - `unstable_cache(fn, keyParts, { tags, revalidate })` caches an async
12
+ * function's JSON-serializable result.
13
+ * - `unstable_noStore()` marks the current render uncacheable.
14
+ */
15
+ import { cacheRuntime, currentRenderScope, currentRevalidateScope, dataCacheGetJSON, dataCacheSetJSON, markNoStore, recordCacheRead, } from './cache-scope.js';
16
+ function env(name) {
17
+ const proc = globalThis.process;
18
+ return (proc && proc.env && proc.env[name]) || '';
19
+ }
20
+ /** Logs targets the host could not revalidate (static pages, unknown routes). */
21
+ export function reportSkippedRevalidations(result) {
22
+ if (!result || !Array.isArray(result.skipped))
23
+ return;
24
+ for (const s of result.skipped) {
25
+ console.warn(`[krate] revalidation skipped for ${s.target}: ${s.reason}`);
26
+ }
27
+ }
28
+ /** Sends a revalidation to the host (used outside a request scope). */
29
+ export async function sendRevalidation(payload) {
30
+ const host = env('KRATE_HOST_URL');
31
+ const secret = env('KRATE_INTERNAL_SECRET');
32
+ if (!host || !secret) {
33
+ throw new Error('revalidation needs the Krate server: KRATE_HOST_URL / KRATE_INTERNAL_SECRET are not set');
34
+ }
35
+ const res = await fetch(host.replace(/\/$/, '') + '/__krate/internal/revalidate', {
36
+ method: 'POST',
37
+ headers: { 'content-type': 'application/json', 'x-krate-internal': secret },
38
+ body: JSON.stringify(payload),
39
+ });
40
+ const text = await res.text();
41
+ if (!res.ok)
42
+ throw new Error(`revalidation failed: host answered ${res.status} ${text}`);
43
+ const result = JSON.parse(text);
44
+ reportSkippedRevalidations(result);
45
+ return result;
46
+ }
47
+ function request(api, payload) {
48
+ if (currentRenderScope()) {
49
+ throw new Error(`${api}() cannot be called while a page renders. Call it from a server action ("use server") or an API route after the data changed.`);
50
+ }
51
+ // Same-process data cache entries go right away; the host fans the tags
52
+ // out to every other process and worker.
53
+ if (payload.tags.length)
54
+ cacheRuntime().invalidate({ tags: payload.tags });
55
+ const scope = currentRevalidateScope();
56
+ if (scope) {
57
+ scope.paths.push(...payload.paths);
58
+ scope.tags.push(...payload.tags);
59
+ return;
60
+ }
61
+ const go = globalThis._go_revalidate;
62
+ if (typeof go === 'function') {
63
+ // Embedded QuickJS API route: the Go host applies it synchronously.
64
+ const out = JSON.parse(go(JSON.stringify(payload)));
65
+ if (out.error)
66
+ throw new Error(`${api}() failed: ${out.error}`);
67
+ reportSkippedRevalidations(out);
68
+ return;
69
+ }
70
+ if (env('KRATE_HOST_URL') && env('KRATE_INTERNAL_SECRET') && typeof fetch === 'function') {
71
+ // Server code outside a request (a timer, a queue consumer): send now.
72
+ sendRevalidation(payload).catch((err) => {
73
+ console.error(`[krate] ${api}() failed:`, err);
74
+ });
75
+ return;
76
+ }
77
+ throw new Error(`${api}() can only run on the Krate server: in a server action, an API route, or server code under \`krate serve\` / \`krate dev\` (KRATE_HOST_URL is not set, e.g. during a build).`);
78
+ }
79
+ /**
80
+ * Invalidates the cached render of `path`. `type: "page"` (the default for a
81
+ * concrete URL) targets that page; a dynamic pattern such as `/blog/[slug]`
82
+ * targets every cached variant; `type: "layout"` targets every page under
83
+ * the path.
84
+ */
85
+ export function revalidatePath(path, type) {
86
+ if (typeof path !== 'string' || !path.startsWith('/')) {
87
+ throw new TypeError(`revalidatePath() expects an absolute path starting with "/", got ${JSON.stringify(path)}`);
88
+ }
89
+ if (type !== undefined && type !== 'page' && type !== 'layout') {
90
+ throw new TypeError(`revalidatePath() type must be "page" or "layout", got ${JSON.stringify(type)}`);
91
+ }
92
+ request('revalidatePath', { paths: [{ path, type: type || 'page' }], tags: [] });
93
+ }
94
+ /** Invalidates every cached page render, region and data entry that read `tag`. */
95
+ export function revalidateTag(tag) {
96
+ if (typeof tag !== 'string' || tag === '') {
97
+ throw new TypeError(`revalidateTag() expects a non-empty string tag, got ${JSON.stringify(tag)}`);
98
+ }
99
+ request('revalidateTag', { paths: [], tags: [tag] });
100
+ }
101
+ const pending = new Map();
102
+ /**
103
+ * Caches the JSON-serializable result of an async function. The cache key is
104
+ * the function source, keyParts and the call arguments. Results expire after
105
+ * `revalidate` seconds (never when false/omitted) and are invalidated by
106
+ * `revalidateTag` for any of `tags`. When called during a render, the tags
107
+ * and window are recorded on the page's cache entry too.
108
+ */
109
+ export function unstable_cache(fn, keyParts, options = {}) {
110
+ if (typeof fn !== 'function')
111
+ throw new TypeError('unstable_cache() expects a function');
112
+ const tags = (options.tags || []).filter((t) => typeof t === 'string' && t !== '');
113
+ const revalidate = options.revalidate;
114
+ if (revalidate !== undefined && revalidate !== false && !(typeof revalidate === 'number' && revalidate >= 0)) {
115
+ throw new TypeError('unstable_cache() revalidate must be a number of seconds or false');
116
+ }
117
+ const ttl = typeof revalidate === 'number' ? revalidate : Infinity;
118
+ const base = String(fn) + '\u0000' + JSON.stringify(keyParts || []);
119
+ return async (...args) => {
120
+ recordCacheRead(tags, revalidate === undefined ? false : revalidate);
121
+ if (ttl === 0)
122
+ return fn(...args);
123
+ const key = 'uc:' + base + '\u0000' + JSON.stringify(args);
124
+ const hit = dataCacheGetJSON(key);
125
+ if (hit !== undefined)
126
+ return JSON.parse(hit);
127
+ const running = pending.get(key);
128
+ if (running)
129
+ return running;
130
+ const epoch = cacheRuntime().epoch;
131
+ const p = (async () => {
132
+ const value = await fn(...args);
133
+ const json = JSON.stringify(value);
134
+ if (json === undefined) {
135
+ throw new TypeError('unstable_cache() results must be JSON-serializable (got undefined or a function)');
136
+ }
137
+ dataCacheSetJSON(key, json, ttl, tags, epoch);
138
+ return value;
139
+ })();
140
+ pending.set(key, p);
141
+ try {
142
+ return await p;
143
+ }
144
+ finally {
145
+ pending.delete(key);
146
+ }
147
+ };
148
+ }
149
+ /**
150
+ * Opts the current render out of caching: an ISR page rendered with it is
151
+ * served fresh and not stored. It has no effect outside a render.
152
+ */
153
+ export function unstable_noStore() {
154
+ markNoStore();
155
+ }
@@ -0,0 +1 @@
1
+ export {};