@krate/runtime 0.5.0-alpha.3 → 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.
@@ -37,9 +37,16 @@ export interface ActionContext {
37
37
  }
38
38
  /** The current action context, or undefined outside a server action. */
39
39
  export declare function getActionContext(): ActionContext | undefined;
40
- /** Request headers of the current server action call. */
40
+ /**
41
+ * Request headers of the current server action call or server component
42
+ * render. The result can also be awaited (`await headers()`), as in Next.js 15.
43
+ */
41
44
  export declare function headers(): Headers;
42
- /** Cookies of the current server action call. */
45
+ /**
46
+ * Cookies of the current server action call, or a read-only view of the
47
+ * request cookies while a server component renders (`get(name)` returns
48
+ * `{ name, value }` there, like Next.js). Can also be awaited.
49
+ */
43
50
  export declare function cookies(): ActionCookies;
44
51
  /**
45
52
  * Ends the server action and navigates the client to `url` (a JSON
@@ -5,6 +5,7 @@
5
5
  * publishes it on `globalThis[Symbol.for('krate.action.store')]`. These helpers
6
6
  * read that scope, so they only work while a server action is executing.
7
7
  */
8
+ import { getRequestContext, requestCookies, thenable } from './request-context.js';
8
9
  /** The current action context, or undefined outside a server action. */
9
10
  export function getActionContext() {
10
11
  const store = globalThis[Symbol.for('krate.action.store')];
@@ -13,18 +14,53 @@ export function getActionContext() {
13
14
  function requireContext(api) {
14
15
  const ctx = getActionContext();
15
16
  if (!ctx) {
16
- throw new Error(`${api}() can only be called while a server action runs (inside a "use server" export)`);
17
+ throw new Error(`${api}() can only be called while a server action runs (inside a "use server" export) ` +
18
+ `or while a server component (an async component) renders in the SSR sidecar`);
17
19
  }
18
20
  return ctx;
19
21
  }
20
- /** Request headers of the current server action call. */
22
+ /**
23
+ * Request headers of the current server action call or server component
24
+ * render. The result can also be awaited (`await headers()`), as in Next.js 15.
25
+ */
21
26
  export function headers() {
27
+ const action = getActionContext();
28
+ if (action)
29
+ return awaitableHeaders(action.headers);
30
+ const req = getRequestContext();
31
+ if (req)
32
+ return awaitableHeaders(req.headers);
22
33
  return requireContext('headers').headers;
23
34
  }
24
- /** Cookies of the current server action call. */
35
+ /**
36
+ * Cookies of the current server action call, or a read-only view of the
37
+ * request cookies while a server component renders (`get(name)` returns
38
+ * `{ name, value }` there, like Next.js). Can also be awaited.
39
+ */
25
40
  export function cookies() {
41
+ const action = getActionContext();
42
+ if (action)
43
+ return awaitableActionCookies(action.cookies);
44
+ const req = getRequestContext();
45
+ if (req)
46
+ return requestCookies(req.cookies);
26
47
  return requireContext('cookies').cookies;
27
48
  }
49
+ function awaitableActionCookies(c) {
50
+ const view = () => ({
51
+ get: (name) => c.get(name),
52
+ getAll: () => c.getAll(),
53
+ has: (name) => c.has(name),
54
+ set: (name, value, options) => c.set(name, value, options),
55
+ delete: (name, options) => c.delete(name, options),
56
+ });
57
+ return thenable(view(), view);
58
+ }
59
+ function awaitableHeaders(h) {
60
+ const plain = new Headers(h);
61
+ const view = new Headers(h);
62
+ return thenable(view, () => plain);
63
+ }
28
64
  /**
29
65
  * Ends the server action and navigates the client to `url` (a JSON
30
66
  * `redirect` for enhanced forms, a 303 for native form posts). Returning
package/dist/actions.js CHANGED
@@ -17,7 +17,8 @@
17
17
  * request JSON {"args":[...]} every argument JSON
18
18
  * multipart form fields + "__krate_args" last argument a FormData;
19
19
  * (JSON array of leading args)
20
- * response {"ok":true,"result":R,"redirect":"/path"?}
20
+ * response {"ok":true,"result":R,"redirect":"/path"?,
21
+ * "revalidated":true?,"revalidation":{"paths":[...],"tags":[...]}?}
21
22
  * {"ok":false,"error":{"message":M,"digest":D}}
22
23
  */
23
24
  import { createEffect, onCleanup, krateRunEvent, krateTransitionWrites } from './signal.js';
@@ -48,6 +49,20 @@ function navigateTo(url) {
48
49
  else if (typeof location !== 'undefined')
49
50
  location.assign(url);
50
51
  }
52
+ /**
53
+ * Tells the page that the action revalidated server caches. The router
54
+ * listens for `krate:revalidate` and refreshes the current route; detail is
55
+ * `{ paths: [{ path, type }], tags: [...] }`.
56
+ */
57
+ function dispatchRevalidate(info) {
58
+ if (typeof window === 'undefined' || typeof CustomEvent === 'undefined')
59
+ return;
60
+ const detail = {
61
+ paths: info && Array.isArray(info.paths) ? info.paths : [],
62
+ tags: info && Array.isArray(info.tags) ? info.tags : [],
63
+ };
64
+ window.dispatchEvent(new CustomEvent('krate:revalidate', { detail }));
65
+ }
51
66
  function errorFrom(p, status, statusText) {
52
67
  const e = p ? p.error : undefined;
53
68
  if (e && typeof e === 'object') {
@@ -97,6 +112,8 @@ export async function callServerAction(url, args) {
97
112
  if (!res.ok || !payload || payload.ok === false) {
98
113
  throw errorFrom(payload, res.status, res.statusText);
99
114
  }
115
+ if (payload.revalidated)
116
+ dispatchRevalidate(payload.revalidation);
100
117
  if (typeof payload.redirect === 'string' && payload.redirect)
101
118
  navigateTo(payload.redirect);
102
119
  return payload.result;
@@ -388,4 +388,30 @@ describe('server action proxies', () => {
388
388
  await __krateAction('a4')();
389
389
  expect(nav).toHaveBeenCalledWith('/next');
390
390
  });
391
+ it('dispatches krate:revalidate when the action revalidated server caches', async () => {
392
+ const revalidation = { paths: [{ path: '/posts', type: 'page' }], tags: ['posts'] };
393
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: 1, revalidated: true, revalidation })));
394
+ const seen = [];
395
+ const onRevalidate = (e) => seen.push(e.detail);
396
+ window.addEventListener('krate:revalidate', onRevalidate);
397
+ try {
398
+ await expect(__krateAction('a5')()).resolves.toBe(1);
399
+ expect(seen).toEqual([revalidation]);
400
+ }
401
+ finally {
402
+ window.removeEventListener('krate:revalidate', onRevalidate);
403
+ }
404
+ });
405
+ it('does not dispatch krate:revalidate for actions that revalidated nothing', async () => {
406
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: null })));
407
+ const handler = vi.fn();
408
+ window.addEventListener('krate:revalidate', handler);
409
+ try {
410
+ await __krateAction('a6')();
411
+ expect(handler).not.toHaveBeenCalled();
412
+ }
413
+ finally {
414
+ window.removeEventListener('krate:revalidate', handler);
415
+ }
416
+ });
391
417
  });
@@ -0,0 +1,118 @@
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
+ /** What one render read through the cache. */
22
+ export interface CacheScope {
23
+ /** Route being rendered (diagnostics only). */
24
+ route: string;
25
+ /** Cache tags the render read. */
26
+ tags: Set<string>;
27
+ /** Smallest positive revalidate window (seconds) a read declared; 0 = none. */
28
+ revalidate: number;
29
+ /** True when a read opted out of caching (no-store, revalidate 0, unstable_noStore). */
30
+ noStore: boolean;
31
+ }
32
+ /** Minimal AsyncLocalStorage shape (the Node class satisfies it). */
33
+ export interface AsyncStore<T> {
34
+ getStore(): T | undefined;
35
+ run<R>(store: T, fn: () => R): R;
36
+ }
37
+ /** Pending revalidations of one server action or API request. */
38
+ export interface RevalidateScope {
39
+ kind: string;
40
+ paths: Array<{
41
+ path: string;
42
+ type: 'page' | 'layout';
43
+ }>;
44
+ tags: string[];
45
+ }
46
+ /** In-process data cache with tag index and FIFO bound. */
47
+ export declare class DataCache {
48
+ private max;
49
+ private map;
50
+ private byTag;
51
+ constructor(max?: number);
52
+ get size(): number;
53
+ get(key: string): unknown | undefined;
54
+ set(key: string, value: unknown, ttlSeconds: number, tags: string[]): void;
55
+ delete(key: string): void;
56
+ /** Removes every entry carrying one of tags; returns how many. */
57
+ invalidateTags(tags: string[]): number;
58
+ clear(): void;
59
+ }
60
+ /** Process-wide cache runtime shared by every bundled copy of this module. */
61
+ export interface CacheRuntime {
62
+ dataCache: DataCache;
63
+ /** Render scope storage; installed by the SSR renderer. */
64
+ renderStore?: AsyncStore<CacheScope>;
65
+ /** Bumped on every invalidation so in-flight renders/reads do not store stale results. */
66
+ epoch: number;
67
+ /** Applies a tag invalidation to the local data cache. */
68
+ invalidate(payload: {
69
+ tags?: string[];
70
+ }): {
71
+ dataEntries: number;
72
+ };
73
+ fetchPatched?: boolean;
74
+ }
75
+ /** The shared cache runtime, created on first use. */
76
+ export declare function cacheRuntime(): CacheRuntime;
77
+ /** Installs the render scope storage (an AsyncLocalStorage). Renderer only. */
78
+ export declare function installRenderStore(store: AsyncStore<CacheScope>): void;
79
+ /** The scope of the render currently running, if any. */
80
+ export declare function currentRenderScope(): CacheScope | undefined;
81
+ /** The pending-revalidation scope of the current server action / API request. */
82
+ export declare function currentRevalidateScope(): RevalidateScope | undefined;
83
+ /**
84
+ * Runs fn inside a fresh render scope and returns its result together with
85
+ * the scope (tags, revalidate window, noStore) and whether an invalidation
86
+ * happened while it ran (then the result must not be cached).
87
+ */
88
+ export declare function withCacheScope<T>(route: string, fn: () => T | Promise<T>): Promise<{
89
+ result: T;
90
+ scope: CacheScope;
91
+ invalidated: boolean;
92
+ }>;
93
+ /**
94
+ * Implicit tag carried by data-cache entries first stored while rendering
95
+ * route, so revalidatePath(route) also drops the data that render cached.
96
+ */
97
+ export declare function routeDataTag(route: string): string;
98
+ /** Records tags and a revalidate window on the current render scope. */
99
+ export declare function recordCacheRead(tags: readonly string[] | undefined, revalidate: number | false | undefined): void;
100
+ /** Marks the current render as uncacheable. Outside a render it has no effect. */
101
+ export declare function markNoStore(): void;
102
+ /** Reads a JSON value from the data cache; undefined on a miss. */
103
+ export declare function dataCacheGetJSON(key: string): string | undefined;
104
+ /**
105
+ * Stores a JSON value unless an invalidation happened since epoch. Inside a
106
+ * render the entry also gets the route's implicit tag (see routeDataTag).
107
+ */
108
+ export declare function dataCacheSetJSON(key: string, json: string, ttlSeconds: number, tags: string[], epoch: number): void;
109
+ /**
110
+ * Wraps globalThis.fetch once so Next-style cache options work in server
111
+ * code: `next.tags` are recorded on the current render, `next.revalidate: N`
112
+ * or `cache: "force-cache"` cache successful GET/HEAD responses (by method,
113
+ * URL and headers) for N seconds (indefinitely for force-cache or
114
+ * `revalidate: false`) under the given tags, and `cache: "no-store"` /
115
+ * `next.revalidate: 0` bypass the cache and make the render uncacheable.
116
+ * Requests without these options are passed through untouched.
117
+ */
118
+ export declare function patchFetch(): void;
@@ -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;