@blaze-cache/swr 0.0.0-stage → 0.3.0-beta.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Blaze Cache
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/blaze-cache/blaze-cache/main/docs/blaze-cache-logo.png" alt="Blaze Cache logo" width="150">
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <h1 align="center">@blaze-cache/swr</h1>
6
+
7
+ Persist SWR in WebAssembly — instant first paint after reload while
8
+ stale-while-revalidate still works.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @blaze-cache/swr@beta # swr ≥ 2 is a peer dependency
14
+ ```
15
+
16
+ `@beta` is npm's dist-tag for the prerelease; drop it to install the last stable
17
+ release.
18
+
19
+ ## Quick start
20
+
21
+ ```tsx
22
+ import { useBlazeSWR } from '@blaze-cache/swr';
23
+ import { cache } from './blaze.js'; // a cache created by @blaze-cache/core
24
+
25
+ function Todos() {
26
+ const { data } = useBlazeSWR(cache, '/api/todos', (url) => fetch(url).then((r) => r.json()), {
27
+ ttlMs: 5 * 60_000,
28
+ tags: ['todos'],
29
+ });
30
+ // first render: the persisted todos, instantly — background revalidation included
31
+ }
32
+ ```
33
+
34
+ A persisted entry is handed to SWR as `fallbackData` — the first paint after a reload
35
+ comes from the cache instantly, while SWR still revalidates in the background exactly
36
+ like plain `useSWR` (`revalidateIfStale` is untouched, so the fetcher runs on mount as
37
+ usual). Every successful fetch is written back under the same key, stamped with
38
+ `ttlMs`/`tags`. A caller-supplied `fallbackData` (or a provider-level `fallback` entry
39
+ for that key) always wins over the cache.
40
+
41
+ ## Behaviour
42
+
43
+ * Keys are filed under **SWR's own serialization** (`unstable_serialize`): plain strings
44
+ stay themselves, array/object keys get SWR's stable hash — an entry always lines up
45
+ with the key SWR uses internally, and `resolveBlazeKey(key)` exposes it for
46
+ imperative `cache.get` / `cache.set` / `cache.delete`.
47
+ * Successful fetches are written to the shared cache; failed fetches are not — errors
48
+ stay in SWR, data crosses into Blaze.
49
+ * An `undefined` result is skipped too: SWR reads it as "no data", so there is nothing
50
+ to stamp a TTL onto.
51
+ * What is written is an **envelope** — `{ kind: 'swr', data, storedAt }` — and hydration
52
+ only seeds the UI from values carrying it. On a cache shared with `@blaze-cache/axios`,
53
+ `@blaze-cache/fetch` or `@blaze-cache/react-query`, a forced key collision can park a
54
+ foreign value under an SWR key; the envelope keeps an HTTP record from ever being shown
55
+ as this hook's `data`. `readBlazeSWRRecord(cache, key)` exposes the gated read, and
56
+ `isBlazeSWRRecord` the shape check.
57
+ * Renders never touch cache statistics: the hydration read prefers `peek` over `get`,
58
+ so StrictMode's double render cannot move the hit rate or influence eviction.
59
+ * Paused keys (`null`/`undefined`/`false`, or a lazy key resolving to one) read and
60
+ write nothing.
61
+ * SWR owns freshness *within* a session; Blaze Cache owns it *across* sessions —
62
+ `ttlMs` defaults to 24 h, and with no `tags` given every write carries the `'swr'`
63
+ tag, so `cache.invalidateTags('swr')` purges everything this package wrote.
64
+ (Supplied `tags` **replace** the default rather than extending it — add `'swr'`
65
+ yourself if you want the integration-wide purge to keep reaching your entries.)
66
+
67
+ ## API
68
+
69
+ Both entry points take `(cache, …, options?)` — the cache first, then the usual SWR
70
+ arguments, then normal SWR options plus the Blaze-side stamp (`ttlMs`/`tags`).
71
+
72
+ | Export | What it does |
73
+ | --- | --- |
74
+ | `useBlazeSWR` | `useSWR` seeded from the cache, persisting successful fetches. |
75
+ | `blazeSWRMiddleware` | The same behaviour as a plain SWR middleware, for `SWRConfig` or an existing `useSWR`. |
76
+ | `resolveBlazeKey` | The key an SWR `key` is filed under in the Blaze Cache (`null` when paused). |
77
+ | `readBlazeSWRRecord` | The gated hydration read: `key`'s data, but only when the value is this package's own envelope. |
78
+ | `isBlazeSWRRecord` | The envelope shape check `readBlazeSWRRecord` uses. |
79
+ | `DEFAULT_TTL_MS` / `DEFAULT_TAGS` | The write stamp used when nothing is given: 24 h, `['swr']`. |
80
+ | `BlazeSWROptions` / `BlazeSWRMiddlewareOptions` / `BlazeSWRCacheLike` / `BlazeSWRRecord` | The option, cache and record types. |
81
+
82
+ Precedence for the write stamp: the current `useSWR`/`useBlazeSWR` options, then the
83
+ middleware's own options, then the defaults. `useBlazeSWR` keeps `ttlMs`/`tags` in the
84
+ SWR config it hands to `useSWR` rather than stripping them out, so a hook-level stamp
85
+ also wins an `SWRConfig` provider's merged values — a provider default can never shadow
86
+ a per-call one.
87
+
88
+ ## Example usage
89
+
90
+ ### `useBlazeSWR` — instant first paint
91
+
92
+ ```tsx
93
+ import { useBlazeSWR } from '@blaze-cache/swr';
94
+
95
+ function Profile({ userId }: { userId: string }) {
96
+ const { data, isLoading } = useBlazeSWR(
97
+ cache,
98
+ ['profile', userId],
99
+ ([url, id]) => api.get(`${url}/${id}`).then((r) => r.data),
100
+ { ttlMs: 60_000, tags: [`user:${userId}`] },
101
+ );
102
+ // renders the persisted profile immediately; refetches stale data in the background
103
+ }
104
+ ```
105
+
106
+ Omit the fetcher (or pass `null`) for a global fetcher or client-side state — the cache
107
+ is still read, nothing is written:
108
+
109
+ ```tsx
110
+ const { data } = useBlazeSWR(cache, 'theme', null, { fallbackData: 'dark' });
111
+ ```
112
+
113
+ ### `blazeSWRMiddleware` — one middleware for a whole tree
114
+
115
+ ```tsx
116
+ import { SWRConfig } from 'swr';
117
+ import { blazeSWRMiddleware } from '@blaze-cache/swr';
118
+
119
+ <SWRConfig value={{ use: [blazeSWRMiddleware(cache)] }}>
120
+ <App />
121
+ </SWRConfig>;
122
+ ```
123
+
124
+ It is a plain SWR middleware, so yours compose with it — this one goes first, so it
125
+ seeds the config and wraps the fetcher before they transform either:
126
+
127
+ ```ts
128
+ const { data } = useSWR('/api/todos', fetcher, {
129
+ use: [blazeSWRMiddleware(cache, { ttlMs: 60_000 }), loggerMiddleware],
130
+ });
131
+ ```
132
+
133
+ ### Invalidating by tag
134
+
135
+ ```ts
136
+ // Writes carry tags…
137
+ const { data } = useBlazeSWR(cache, '/api/todos', fetchTodos, { tags: ['todos'] });
138
+
139
+ // …so a mutation that changes the list purges every persisted copy —
140
+ // including ones from earlier sessions:
141
+ cache.invalidateTags('todos');
142
+ mutate('/api/todos'); // SWR's own revalidation for the mounted hook
143
+ ```
144
+
145
+ ## Testing
146
+
147
+ ```sh
148
+ pnpm --filter @blaze-cache/swr test
149
+ ```
150
+
151
+ The suite runs against the built package with Node's test runner, started with
152
+ `--experimental-test-module-mocks`: the hook test replaces the `swr` module with a
153
+ capture stub, so the exact config `useBlazeSWR` hands to SWR can be asserted without a
154
+ React renderer (the main suite needs none of that).
155
+
156
+ ## Documentation
157
+
158
+ Setup and the full integration reference live in the
159
+ [repository README](https://github.com/blaze-cache/blaze-cache#readme).
160
+
161
+ ## Part of Blaze Cache
162
+
163
+ * [`@blaze-cache/core`](https://www.npmjs.com/package/@blaze-cache/core) — the cache itself
164
+ * [`@blaze-cache/axios`](https://www.npmjs.com/package/@blaze-cache/axios) — HTTP adapter
165
+ * [`@blaze-cache/fetch`](https://www.npmjs.com/package/@blaze-cache/fetch) — drop-in `fetch()` replacement
166
+ * [`@blaze-cache/ky`](https://www.npmjs.com/package/@blaze-cache/ky) — ky hooks (v1 and v2)
167
+ * [`@blaze-cache/react-query`](https://www.npmjs.com/package/@blaze-cache/react-query) — TanStack Query v5 mirror + hook
168
+
169
+ ## License
170
+
171
+ [MIT](https://github.com/blaze-cache/blaze-cache/blob/main/LICENSE) © Blaze Cache
@@ -0,0 +1,33 @@
1
+ /**
2
+ * SWR integration backed by Blaze Cache — stale-while-revalidate that survives a reload.
3
+ *
4
+ * Two entry points:
5
+ *
6
+ * * {@link useBlazeSWR} — `useSWR` that paints the persisted entry on the first render
7
+ * and writes successful fetches back, with `ttlMs`/`tags` on top of normal SWR options.
8
+ * * {@link blazeSWRMiddleware} — the same behaviour as a plain SWR middleware, for
9
+ * wiring into `SWRConfig` or an existing `useSWR` call.
10
+ *
11
+ * {@link resolveBlazeKey} exposes the key an SWR `key` is filed under, for imperative
12
+ * reads and writes (`cache.get(resolveBlazeKey(key))`).
13
+ *
14
+ * ```tsx
15
+ * const cache = await createCache({ persistence: { namespace: 'app' } });
16
+ *
17
+ * function Todos() {
18
+ * const { data } = useBlazeSWR(cache, '/api/todos', (url) => fetch(url).then((r) => r.json()), {
19
+ * ttlMs: 5 * 60_000,
20
+ * tags: ['todos'],
21
+ * });
22
+ * // first render: the persisted todos, instantly — background revalidation included
23
+ * }
24
+ * ```
25
+ *
26
+ * @packageDocumentation
27
+ */
28
+ export { blazeSWRMiddleware, DEFAULT_TAGS, DEFAULT_TTL_MS } from './middleware.js';
29
+ export { resolveBlazeKey } from './key.js';
30
+ export { isBlazeSWRRecord, readBlazeSWRRecord } from './record.js';
31
+ export { useBlazeSWR } from './useBlazeSWR.js';
32
+ export type { BlazeSWRCacheLike, BlazeSWRRecord, BlazeSWROptions, BlazeSWRMiddlewareOptions, BlazeSWRStampOptions, } from './types.js';
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EACV,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * SWR integration backed by Blaze Cache — stale-while-revalidate that survives a reload.
3
+ *
4
+ * Two entry points:
5
+ *
6
+ * * {@link useBlazeSWR} — `useSWR` that paints the persisted entry on the first render
7
+ * and writes successful fetches back, with `ttlMs`/`tags` on top of normal SWR options.
8
+ * * {@link blazeSWRMiddleware} — the same behaviour as a plain SWR middleware, for
9
+ * wiring into `SWRConfig` or an existing `useSWR` call.
10
+ *
11
+ * {@link resolveBlazeKey} exposes the key an SWR `key` is filed under, for imperative
12
+ * reads and writes (`cache.get(resolveBlazeKey(key))`).
13
+ *
14
+ * ```tsx
15
+ * const cache = await createCache({ persistence: { namespace: 'app' } });
16
+ *
17
+ * function Todos() {
18
+ * const { data } = useBlazeSWR(cache, '/api/todos', (url) => fetch(url).then((r) => r.json()), {
19
+ * ttlMs: 5 * 60_000,
20
+ * tags: ['todos'],
21
+ * });
22
+ * // first render: the persisted todos, instantly — background revalidation included
23
+ * }
24
+ * ```
25
+ *
26
+ * @packageDocumentation
27
+ */
28
+ export { blazeSWRMiddleware, DEFAULT_TAGS, DEFAULT_TTL_MS } from './middleware.js';
29
+ export { resolveBlazeKey } from './key.js';
30
+ export { isBlazeSWRRecord, readBlazeSWRRecord } from './record.js';
31
+ export { useBlazeSWR } from './useBlazeSWR.js';
32
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/key.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { Key } from 'swr';
2
+ /**
3
+ * The key an SWR `key` is filed under in the Blaze Cache — SWR's **own** serialization
4
+ * (`unstable_serialize`), so an entry always lines up with the key SWR uses for its
5
+ * in-memory cache, and imperative reads/writes (`cache.set(resolveBlazeKey(key), …)`)
6
+ * address exactly what the middleware writes.
7
+ *
8
+ * Delegating to SWR rather than re-implementing the hashing means the lookup cannot
9
+ * drift from the key the middleware writes, even across library upgrades: plain strings
10
+ * stay themselves, array/object keys go through SWR's stable hash (object key order
11
+ * never matters), and lazy `() => key` functions are resolved the way SWR resolves them.
12
+ *
13
+ * Returns `null` for every key SWR itself treats as paused — `null`, `undefined`,
14
+ * `false`, `''`, an empty array, or a lazy key that throws or returns nothing — so a
15
+ * disabled hook never touches the Blaze Cache in either direction.
16
+ *
17
+ * ```ts
18
+ * resolveBlazeKey('/api/todos'); // '/api/todos'
19
+ * resolveBlazeKey(['todos', { page: 1 }]); // SWR's stable hash of the array
20
+ * resolveBlazeKey(() => null); // null — paused, nothing to read or write
21
+ * ```
22
+ */
23
+ export declare function resolveBlazeKey(key: Key): string | null;
24
+ //# sourceMappingURL=key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key.d.ts","sourceRoot":"","sources":["../src/key.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,IAAI,CAGvD"}
package/dist/key.js ADDED
@@ -0,0 +1,27 @@
1
+ import { unstable_serialize } from 'swr';
2
+ /**
3
+ * The key an SWR `key` is filed under in the Blaze Cache — SWR's **own** serialization
4
+ * (`unstable_serialize`), so an entry always lines up with the key SWR uses for its
5
+ * in-memory cache, and imperative reads/writes (`cache.set(resolveBlazeKey(key), …)`)
6
+ * address exactly what the middleware writes.
7
+ *
8
+ * Delegating to SWR rather than re-implementing the hashing means the lookup cannot
9
+ * drift from the key the middleware writes, even across library upgrades: plain strings
10
+ * stay themselves, array/object keys go through SWR's stable hash (object key order
11
+ * never matters), and lazy `() => key` functions are resolved the way SWR resolves them.
12
+ *
13
+ * Returns `null` for every key SWR itself treats as paused — `null`, `undefined`,
14
+ * `false`, `''`, an empty array, or a lazy key that throws or returns nothing — so a
15
+ * disabled hook never touches the Blaze Cache in either direction.
16
+ *
17
+ * ```ts
18
+ * resolveBlazeKey('/api/todos'); // '/api/todos'
19
+ * resolveBlazeKey(['todos', { page: 1 }]); // SWR's stable hash of the array
20
+ * resolveBlazeKey(() => null); // null — paused, nothing to read or write
21
+ * ```
22
+ */
23
+ export function resolveBlazeKey(key) {
24
+ const serialized = unstable_serialize(key);
25
+ return serialized === '' ? null : serialized;
26
+ }
27
+ //# sourceMappingURL=key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key.js","sourceRoot":"","sources":["../src/key.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,KAAK,CAAC;AAGzC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,eAAe,CAAC,GAAQ;IACtC,MAAM,UAAU,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;IAC3C,OAAO,UAAU,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;AAC/C,CAAC"}
@@ -0,0 +1,56 @@
1
+ import type { Middleware } from 'swr';
2
+ import type { BlazeSWRCacheLike, BlazeSWRMiddlewareOptions } from './types.js';
3
+ /** How long written entries survive in the Blaze Cache (SWR owns in-session freshness). */
4
+ export declare const DEFAULT_TTL_MS = 86400000;
5
+ /** Default tag, so `cache.invalidateTags('swr')` purges everything this package wrote. */
6
+ export declare const DEFAULT_TAGS: readonly string[];
7
+ /**
8
+ * SWR middleware that keeps SWR and the Blaze Cache in step — stale-while-revalidate
9
+ * that also survives a reload.
10
+ *
11
+ * | Moment | Behaviour |
12
+ * | --- | --- |
13
+ * | render | a persisted entry is read **without side effects** (`peek` first) and handed to SWR as `fallbackData` — the first paint is instant, from disk |
14
+ * | mount / revalidate | SWR runs its own revalidation as usual (`revalidateIfStale` still applies), so the fetcher runs in the background exactly like plain `useSWR` |
15
+ * | fetch success | the result is written to the Blaze Cache under the SWR-serialized key, stamped with `ttlMs`/`tags` |
16
+ * | fetch failure | ignored by the cache — errors live in SWR, data lives in Blaze |
17
+ *
18
+ * The seeded entry is deliberately **not** treated as fresh: SWR's `fallbackData` carries
19
+ * no timestamp, so `revalidateIfStale` (on by default) still revalidates on mount. Set
20
+ * `revalidateOnMount: false` or `revalidateIfStale: false` when a cache hit should skip
21
+ * the network entirely.
22
+ *
23
+ * Precedence for what wins the first paint: a caller-supplied `fallbackData`, then an
24
+ * entry in a provider-level `fallback` map, then the Blaze Cache. Precedence for the
25
+ * write stamp: `ttlMs`/`tags` on the current options, then the middleware's own
26
+ * options, then {@link DEFAULT_TTL_MS}/{@link DEFAULT_TAGS}.
27
+ *
28
+ * A paused key (`null`/`undefined`/`false`, or a lazy key resolving to one) reads and
29
+ * writes nothing — {@link resolveBlazeKey} maps those to `null` and the middleware passes
30
+ * the original arguments through untouched.
31
+ *
32
+ * ### Wiring it up
33
+ *
34
+ * `useBlazeSWR` builds it for you. By hand, add it to any `useSWR` call's `use` array —
35
+ * it is a plain SWR middleware, so it composes with yours:
36
+ *
37
+ * ```ts
38
+ * const { data } = useSWR('/api/todos', fetcher, {
39
+ * use: [blazeSWRMiddleware(cache, { ttlMs: 60_000 }), loggerMiddleware],
40
+ * });
41
+ * ```
42
+ *
43
+ * …or to a whole tree through `SWRConfig`:
44
+ *
45
+ * ```tsx
46
+ * <SWRConfig value={{ use: [blazeSWRMiddleware(cache), loggerMiddleware] }}>
47
+ * ```
48
+ *
49
+ * It must be the **first** entry of `use` to see the key, config and fetcher before any
50
+ * other middleware transforms them — {@link useBlazeSWR} puts it there for you.
51
+ *
52
+ * @param cache The Blaze Cache (or anything {@link BlazeSWRCacheLike}-shaped).
53
+ * @param options The Blaze-side stamp for writes; per-call options still override it.
54
+ */
55
+ export declare function blazeSWRMiddleware(cache: BlazeSWRCacheLike, options?: BlazeSWRMiddlewareOptions): Middleware;
56
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,UAAU,EAGX,MAAM,KAAK,CAAC;AAIb,OAAO,KAAK,EACV,iBAAiB,EACjB,yBAAyB,EAE1B,MAAM,YAAY,CAAC;AAEpB,2FAA2F;AAC3F,eAAO,MAAM,cAAc,WAAa,CAAC;AACzC,0FAA0F;AAC1F,eAAO,MAAM,YAAY,EAAE,SAAS,MAAM,EAAY,CAAC;AAuCvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,iBAAiB,EACxB,OAAO,GAAE,yBAA8B,GACtC,UAAU,CAyCZ"}
@@ -0,0 +1,111 @@
1
+ import { resolveBlazeKey } from './key.js';
2
+ import { readBlazeSWRRecord } from './record.js';
3
+ /** How long written entries survive in the Blaze Cache (SWR owns in-session freshness). */
4
+ export const DEFAULT_TTL_MS = 86_400_000;
5
+ /** Default tag, so `cache.invalidateTags('swr')` purges everything this package wrote. */
6
+ export const DEFAULT_TAGS = ['swr'];
7
+ /**
8
+ * Wraps a fetcher so every successful result is written to the Blaze Cache before SWR
9
+ * sees it.
10
+ *
11
+ * Kept module-level (rather than an inline closure) so the narrowing of `fetcher` and
12
+ * the key happens at the call site: inside a captured closure TypeScript would have to
13
+ * assume the parameter changed since the null check.
14
+ *
15
+ * Failures propagate untouched — SWR keeps its own error state, and the cache only ever
16
+ * holds data that a fetcher actually returned. `undefined` is skipped: SWR reads it as
17
+ * "no data", so there is nothing worth stamping a TTL onto. The raw result goes into a
18
+ * {@link BlazeSWRRecord} envelope, so hydration can tell this package's writes apart from
19
+ * foreign values on a shared cache (see {@link readBlazeSWRRecord}); the fetcher itself
20
+ * still resolves with the bare result, exactly as the caller's fetcher would.
21
+ */
22
+ function persistingFetcher(fetcher, cache, key, stamp) {
23
+ return async (...args) => {
24
+ const data = await fetcher(...args);
25
+ if (data !== undefined) {
26
+ const record = { kind: 'swr', data, storedAt: Date.now() };
27
+ cache.set(key, record, stamp);
28
+ }
29
+ return data;
30
+ };
31
+ }
32
+ /**
33
+ * SWR middleware that keeps SWR and the Blaze Cache in step — stale-while-revalidate
34
+ * that also survives a reload.
35
+ *
36
+ * | Moment | Behaviour |
37
+ * | --- | --- |
38
+ * | render | a persisted entry is read **without side effects** (`peek` first) and handed to SWR as `fallbackData` — the first paint is instant, from disk |
39
+ * | mount / revalidate | SWR runs its own revalidation as usual (`revalidateIfStale` still applies), so the fetcher runs in the background exactly like plain `useSWR` |
40
+ * | fetch success | the result is written to the Blaze Cache under the SWR-serialized key, stamped with `ttlMs`/`tags` |
41
+ * | fetch failure | ignored by the cache — errors live in SWR, data lives in Blaze |
42
+ *
43
+ * The seeded entry is deliberately **not** treated as fresh: SWR's `fallbackData` carries
44
+ * no timestamp, so `revalidateIfStale` (on by default) still revalidates on mount. Set
45
+ * `revalidateOnMount: false` or `revalidateIfStale: false` when a cache hit should skip
46
+ * the network entirely.
47
+ *
48
+ * Precedence for what wins the first paint: a caller-supplied `fallbackData`, then an
49
+ * entry in a provider-level `fallback` map, then the Blaze Cache. Precedence for the
50
+ * write stamp: `ttlMs`/`tags` on the current options, then the middleware's own
51
+ * options, then {@link DEFAULT_TTL_MS}/{@link DEFAULT_TAGS}.
52
+ *
53
+ * A paused key (`null`/`undefined`/`false`, or a lazy key resolving to one) reads and
54
+ * writes nothing — {@link resolveBlazeKey} maps those to `null` and the middleware passes
55
+ * the original arguments through untouched.
56
+ *
57
+ * ### Wiring it up
58
+ *
59
+ * `useBlazeSWR` builds it for you. By hand, add it to any `useSWR` call's `use` array —
60
+ * it is a plain SWR middleware, so it composes with yours:
61
+ *
62
+ * ```ts
63
+ * const { data } = useSWR('/api/todos', fetcher, {
64
+ * use: [blazeSWRMiddleware(cache, { ttlMs: 60_000 }), loggerMiddleware],
65
+ * });
66
+ * ```
67
+ *
68
+ * …or to a whole tree through `SWRConfig`:
69
+ *
70
+ * ```tsx
71
+ * <SWRConfig value={{ use: [blazeSWRMiddleware(cache), loggerMiddleware] }}>
72
+ * ```
73
+ *
74
+ * It must be the **first** entry of `use` to see the key, config and fetcher before any
75
+ * other middleware transforms them — {@link useBlazeSWR} puts it there for you.
76
+ *
77
+ * @param cache The Blaze Cache (or anything {@link BlazeSWRCacheLike}-shaped).
78
+ * @param options The Blaze-side stamp for writes; per-call options still override it.
79
+ */
80
+ export function blazeSWRMiddleware(cache, options = {}) {
81
+ return (useSWRNext) => (key, fetcher, config) => {
82
+ const blazeKey = resolveBlazeKey(key);
83
+ // Per-call `ttlMs`/`tags` ride in the SWR config (SWR merges unknown options through),
84
+ // then the middleware's own options, then the package defaults.
85
+ const stamp = {
86
+ ttlMs: config.ttlMs ??
87
+ options.ttlMs ??
88
+ DEFAULT_TTL_MS,
89
+ tags: config.tags ??
90
+ options.tags ??
91
+ DEFAULT_TAGS,
92
+ };
93
+ // Hydration: `peek` first so renders never move the hit rate or nudge eviction —
94
+ // a recording `get` stays the fallback for caches that predate it. Only this
95
+ // package's own envelope seeds the UI; a foreign value under a colliding key reads
96
+ // as a miss rather than being handed to the component as `data`.
97
+ const data = blazeKey === null ? undefined : readBlazeSWRRecord(cache, blazeKey);
98
+ // Caller-supplied fallbacks stay authoritative: `fallbackData` directly, or a
99
+ // provider-level `fallback` entry for this exact key. Blaze only fills the gap.
100
+ const callerFallback = config.fallbackData !== undefined ||
101
+ (blazeKey !== null && config.fallback?.[blazeKey] !== undefined);
102
+ const nextConfig = data !== undefined && !callerFallback
103
+ ? { ...config, fallbackData: data }
104
+ : config;
105
+ const nextFetcher = fetcher !== null && blazeKey !== null
106
+ ? persistingFetcher(fetcher, cache, blazeKey, stamp)
107
+ : fetcher;
108
+ return useSWRNext(key, nextFetcher, nextConfig);
109
+ };
110
+ }
111
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAOjD,2FAA2F;AAC3F,MAAM,CAAC,MAAM,cAAc,GAAG,UAAU,CAAC;AACzC,0FAA0F;AAC1F,MAAM,CAAC,MAAM,YAAY,GAAsB,CAAC,KAAK,CAAC,CAAC;AAQvD;;;;;;;;;;;;;;GAcG;AACH,SAAS,iBAAiB,CACxB,OAA0B,EAC1B,KAAwB,EACxB,GAAW,EACX,KAAoB;IAEpB,OAAO,KAAK,EAAE,GAAG,IAAW,EAAE,EAAE;QAC9B,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;QACpC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,MAAM,MAAM,GAAyB,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;YACjF,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAAwB,EACxB,UAAqC,EAAE;IAEvC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE;QAC9C,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAEtC,uFAAuF;QACvF,gEAAgE;QAChE,MAAM,KAAK,GAAkB;YAC3B,KAAK,EACF,MAAuD,CAAC,KAAK;gBAC9D,OAAO,CAAC,KAAK;gBACb,cAAc;YAChB,IAAI,EACD,MAAuD,CAAC,IAAI;gBAC7D,OAAO,CAAC,IAAI;gBACZ,YAAY;SACf,CAAC;QAEF,iFAAiF;QACjF,6EAA6E;QAC7E,mFAAmF;QACnF,iEAAiE;QACjE,MAAM,IAAI,GAAG,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,kBAAkB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;QAEjF,8EAA8E;QAC9E,gFAAgF;QAChF,MAAM,cAAc,GAClB,MAAM,CAAC,YAAY,KAAK,SAAS;YACjC,CAAC,QAAQ,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC,CAAC;QAEnE,MAAM,UAAU,GACd,IAAI,KAAK,SAAS,IAAI,CAAC,cAAc;YACnC,CAAC,CAAE,EAAE,GAAG,MAAM,EAAE,YAAY,EAAE,IAAI,EAAuB;YACzD,CAAC,CAAC,MAAM,CAAC;QAEb,MAAM,WAAW,GACf,OAAO,KAAK,IAAI,IAAI,QAAQ,KAAK,IAAI;YACnC,CAAC,CAAC,iBAAiB,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC;YACpD,CAAC,CAAC,OAAO,CAAC;QAEd,OAAO,UAAU,CAAC,GAAG,EAAE,WAAW,EAAE,UAAU,CAAgB,CAAC;IACjE,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { BlazeSWRCacheLike, BlazeSWRRecord } from './types.js';
2
+ /**
3
+ * Reads `key` and returns the record's data **only when the value is one this package
4
+ * wrote** — the hydration gate.
5
+ *
6
+ * Every write from {@link blazeSWRMiddleware} carries the `{ kind: 'swr' }` envelope, so
7
+ * a value without it belongs to something else sharing the cache: an axios/fetch response
8
+ * record, a react-query mirror record, a manual `cache.set` of the app's own. On a
9
+ * single-integration cache every value passes; the check exists for the shared one, where
10
+ * seeding a foreign shape would hand an HTTP body (or a whole response record) to a
11
+ * component as `data`.
12
+ *
13
+ * Read with `peek` when the cache has one — a render must not move the hit rate or nudge
14
+ * eviction — falling back to `get` for caches that predate it.
15
+ */
16
+ export declare function readBlazeSWRRecord<Data = unknown>(cache: BlazeSWRCacheLike, key: string): Data | undefined;
17
+ /** True when `value` is the envelope this package writes. */
18
+ export declare function isBlazeSWRRecord<T = unknown>(value: unknown): value is BlazeSWRRecord<T>;
19
+ //# sourceMappingURL=record.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../src/record.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAG,OAAO,EAC/C,KAAK,EAAE,iBAAiB,EACxB,GAAG,EAAE,MAAM,GACV,IAAI,GAAG,SAAS,CAGlB;AAED,6DAA6D;AAC7D,wBAAgB,gBAAgB,CAAC,CAAC,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC,CAOxF"}
package/dist/record.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Reads `key` and returns the record's data **only when the value is one this package
3
+ * wrote** — the hydration gate.
4
+ *
5
+ * Every write from {@link blazeSWRMiddleware} carries the `{ kind: 'swr' }` envelope, so
6
+ * a value without it belongs to something else sharing the cache: an axios/fetch response
7
+ * record, a react-query mirror record, a manual `cache.set` of the app's own. On a
8
+ * single-integration cache every value passes; the check exists for the shared one, where
9
+ * seeding a foreign shape would hand an HTTP body (or a whole response record) to a
10
+ * component as `data`.
11
+ *
12
+ * Read with `peek` when the cache has one — a render must not move the hit rate or nudge
13
+ * eviction — falling back to `get` for caches that predate it.
14
+ */
15
+ export function readBlazeSWRRecord(cache, key) {
16
+ const value = cache.peek ? cache.peek(key) : cache.get(key);
17
+ return isBlazeSWRRecord(value) ? value.data : undefined;
18
+ }
19
+ /** True when `value` is the envelope this package writes. */
20
+ export function isBlazeSWRRecord(value) {
21
+ return (typeof value === 'object' &&
22
+ value !== null &&
23
+ value.kind === 'swr' &&
24
+ typeof value.storedAt === 'number');
25
+ }
26
+ //# sourceMappingURL=record.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"record.js","sourceRoot":"","sources":["../src/record.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAAwB,EACxB,GAAW;IAEX,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC5D,OAAO,gBAAgB,CAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AAChE,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,gBAAgB,CAAc,KAAc;IAC1D,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACb,KAA4B,CAAC,IAAI,KAAK,KAAK;QAC5C,OAAQ,KAAgC,CAAC,QAAQ,KAAK,QAAQ,CAC/D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,87 @@
1
+ import type { BareFetcher, SWRConfiguration } from 'swr';
2
+ /**
3
+ * What this package writes to the cache: the fetcher's result wrapped in a self-describing
4
+ * envelope.
5
+ *
6
+ * The `kind: 'swr'` discriminator exists for the **shared-cache** case: on a store also
7
+ * written by `@blaze-cache/axios`, `@blaze-cache/fetch` or `@blaze-cache/react-query`, a
8
+ * forced key collision can park a foreign value under an SWR key — an axios response
9
+ * record, a react-query mirror record, a raw app entry. Hydration only seeds the UI from
10
+ * values that carry this envelope (see {@link readBlazeSWRRecord}); anything else reads as
11
+ * the miss it is, instead of being handed to the component as `data`.
12
+ *
13
+ * `storedAt` is recorded for introspection and debugging; freshness is SWR's own concern
14
+ * (it revalidates per its normal rules), so the middleware never reads it.
15
+ */
16
+ export interface BlazeSWRRecord<T = unknown> {
17
+ /** Discriminator — the literal this envelope is recognised by. */
18
+ kind: 'swr';
19
+ /** The fetcher's result, exactly as returned. */
20
+ data: T;
21
+ /** Wall-clock time of the write. */
22
+ storedAt: number;
23
+ }
24
+ /**
25
+ * The slice of a cache the SWR integration needs.
26
+ *
27
+ * The concrete `BlazeCache` from `@blaze-cache/core` fits it directly
28
+ * (`createCache()` returns `BlazeCache<any>`), and so does anything else with the same
29
+ * `get`/`set` — a `Map`-backed shim, a test double, a wrapper of your own. Pass
30
+ * `createCache<YourRecord>()` if you would rather have the compiler check both directions.
31
+ *
32
+ * `peek` and `invalidateTags` are optional on purpose:
33
+ *
34
+ * * `peek` is the render-time read (see {@link BlazeSWRCacheLike.peek}); caches that
35
+ * predate it fall back to `get`.
36
+ * * `invalidateTags` is only *documented* as the invalidation entry point — this package
37
+ * never calls it, so a cache without tags still works; tag invalidation then simply
38
+ * needs `cache.invalidateTags` (or a manual `cache.delete`) on your side.
39
+ */
40
+ export interface BlazeSWRCacheLike<V = any> {
41
+ get(key: string): V | undefined;
42
+ /**
43
+ * The same lookup as {@link BlazeSWRCacheLike.get}, minus every side effect: no hit or
44
+ * miss is recorded and the entry is not marked visited for eviction.
45
+ *
46
+ * The middleware prefers it on every render — rendering must not be able to move the
47
+ * hit rate or decide who gets evicted next, and renders happen far more often than
48
+ * real reads (StrictMode double-renders, discarded concurrent renders). The concrete
49
+ * `BlazeCache` has it.
50
+ */
51
+ peek?(key: string): V | undefined;
52
+ set(key: string, value: V, options?: {
53
+ ttlMs?: number;
54
+ tags?: readonly string[];
55
+ }): void;
56
+ delete?(key: string): boolean;
57
+ /** Removes every entry carrying any of `tags`, returning the removed keys. */
58
+ invalidateTags?(...tags: string[]): string[];
59
+ }
60
+ /**
61
+ * How long a written entry survives in the Blaze Cache, and under which tags — the
62
+ * `cache.set` stamp, both optional.
63
+ *
64
+ * Read from three places, in order of precedence: the options passed to the current
65
+ * `useSWR`/`useBlazeSWR` call, the options given to {@link blazeSWRMiddleware}, then the
66
+ * package defaults (24 h, tag `'swr'`).
67
+ */
68
+ export interface BlazeSWRStampOptions {
69
+ /** TTL for the entry in milliseconds. Defaults to 24 h. */
70
+ ttlMs?: number;
71
+ /** Tags attached to the entry — enables `cache.invalidateTags('todos')`. */
72
+ tags?: readonly string[];
73
+ }
74
+ /** Options {@link blazeSWRMiddleware} accepts — just the Blaze-side stamp. */
75
+ export type BlazeSWRMiddlewareOptions = BlazeSWRStampOptions;
76
+ /**
77
+ * Normal SWR options plus the Blaze Cache stamp (`ttlMs`/`tags`) — everything
78
+ * `useSWR` accepts keeps working; the two extra fields only shape how successful
79
+ * fetches are written to the Blaze Cache.
80
+ *
81
+ * They may also be set once for every hook under an `SWRConfig` provider (cast to
82
+ * `BlazeSWRStampOptions` — SWR merges unknown options into the config the middleware
83
+ * receives), or passed straight to {@link blazeSWRMiddleware} when you wire it up by hand.
84
+ */
85
+ export interface BlazeSWROptions<Data = any, Error = any, SWRFetcher extends BareFetcher<any> = BareFetcher<Data>> extends SWRConfiguration<Data, Error, SWRFetcher>, BlazeSWRStampOptions {
86
+ }
87
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,KAAK,CAAC;AAEzD;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,cAAc,CAAC,CAAC,GAAG,OAAO;IACzC,kEAAkE;IAClE,IAAI,EAAE,KAAK,CAAC;IACZ,iDAAiD;IACjD,IAAI,EAAE,CAAC,CAAC;IACR,oCAAoC;IACpC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,iBAAiB,CAAC,CAAC,GAAG,GAAG;IACxC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC;IAChC;;;;;;;;OAQG;IACH,IAAI,CAAC,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC;IAClC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,GAAG,IAAI,CAAC;IACzF,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAC9B,8EAA8E;IAC9E,cAAc,CAAC,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;CAC9C;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,oBAAoB;IACnC,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC1B;AAED,8EAA8E;AAC9E,MAAM,MAAM,yBAAyB,GAAG,oBAAoB,CAAC;AAE7D;;;;;;;;GAQG;AACH,MAAM,WAAW,eAAe,CAC9B,IAAI,GAAG,GAAG,EACV,KAAK,GAAG,GAAG,EACX,UAAU,SAAS,WAAW,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,IAAI,CAAC,CACvD,SAAQ,gBAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,UAAU,CAAC,EAC/C,oBAAoB;CAAG"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,45 @@
1
+ import type { Fetcher, Key, SWRResponse } from 'swr';
2
+ import type { BlazeSWRCacheLike, BlazeSWROptions } from './types.js';
3
+ /**
4
+ * `useSWR` that paints from the Blaze Cache and persists what it fetches.
5
+ *
6
+ * The whole behaviour is {@link blazeSWRMiddleware} behind a friendlier signature: the
7
+ * persisted entry for `key` is seeded as SWR's `fallbackData`, so the first render after
8
+ * a reload shows real data immediately while SWR still revalidates in the background —
9
+ * and every successful fetch lands back in the Blaze Cache under `ttlMs`/`tags`.
10
+ *
11
+ * ```tsx
12
+ * const todos = useBlazeSWR(cache, '/api/todos', (url) => api.get(url), {
13
+ * ttlMs: 5 * 60_000,
14
+ * tags: ['todos'],
15
+ * });
16
+ * ```
17
+ *
18
+ * Everything `useSWR` takes keeps working — `revalidateOnMount`, `keepPreviousData`,
19
+ * `suspense`, `use`, a global fetcher (omit `fetcher` or pass `null`) — plus the
20
+ * Blaze-side stamp:
21
+ *
22
+ * * `ttlMs` — how long a successful fetch survives in the Blaze Cache (default 24 h).
23
+ * It governs *cross-session* freshness; SWR's own options keep governing *in-session*
24
+ * freshness.
25
+ * * `tags` — attached to every write, so `cache.invalidateTags('todos')` purges them.
26
+ *
27
+ * Any other middleware in `options.use` composes normally; this one is placed first so
28
+ * it seeds the config and wraps the fetcher before they transform either.
29
+ *
30
+ * Invalidating by tag (the fetcher runs again on the next mount; SWR's in-memory copy
31
+ * keeps its own lifecycle, so revalidate it too when it must change on the spot):
32
+ *
33
+ * ```ts
34
+ * cache.invalidateTags('todos');
35
+ * mutate('/api/todos'); // SWR's own revalidation for the mounted hook
36
+ * ```
37
+ *
38
+ * @param cache The Blaze Cache (or anything {@link BlazeSWRCacheLike}-shaped).
39
+ * @param key The SWR key — string, tuple, object, or a lazy function; `null` pauses.
40
+ * @param fetcher The fetcher; omit it (or pass `null`) to use a global one or for
41
+ * client-side state — the cache is still read, nothing is written.
42
+ * @param options Normal SWR options plus `ttlMs`/`tags`.
43
+ */
44
+ export declare function useBlazeSWR<Data = any, Error = any, SWRKey extends Key = Key>(cache: BlazeSWRCacheLike, key: SWRKey, fetcher?: Fetcher<Data, SWRKey> | null, options?: BlazeSWROptions<Data, Error, Fetcher<Data, SWRKey>>): SWRResponse<Data, Error>;
45
+ //# sourceMappingURL=useBlazeSWR.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useBlazeSWR.d.ts","sourceRoot":"","sources":["../src/useBlazeSWR.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,KAAK,CAAC;AAGrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAgB,WAAW,CACzB,IAAI,GAAG,GAAG,EACV,KAAK,GAAG,GAAG,EACX,MAAM,SAAS,GAAG,GAAG,GAAG,EAExB,KAAK,EAAE,iBAAiB,EACxB,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,IAAW,EAC5C,OAAO,GAAE,eAAe,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAM,GAChE,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAY1B"}
@@ -0,0 +1,56 @@
1
+ import useSWR from 'swr';
2
+ import { blazeSWRMiddleware } from './middleware.js';
3
+ /**
4
+ * `useSWR` that paints from the Blaze Cache and persists what it fetches.
5
+ *
6
+ * The whole behaviour is {@link blazeSWRMiddleware} behind a friendlier signature: the
7
+ * persisted entry for `key` is seeded as SWR's `fallbackData`, so the first render after
8
+ * a reload shows real data immediately while SWR still revalidates in the background —
9
+ * and every successful fetch lands back in the Blaze Cache under `ttlMs`/`tags`.
10
+ *
11
+ * ```tsx
12
+ * const todos = useBlazeSWR(cache, '/api/todos', (url) => api.get(url), {
13
+ * ttlMs: 5 * 60_000,
14
+ * tags: ['todos'],
15
+ * });
16
+ * ```
17
+ *
18
+ * Everything `useSWR` takes keeps working — `revalidateOnMount`, `keepPreviousData`,
19
+ * `suspense`, `use`, a global fetcher (omit `fetcher` or pass `null`) — plus the
20
+ * Blaze-side stamp:
21
+ *
22
+ * * `ttlMs` — how long a successful fetch survives in the Blaze Cache (default 24 h).
23
+ * It governs *cross-session* freshness; SWR's own options keep governing *in-session*
24
+ * freshness.
25
+ * * `tags` — attached to every write, so `cache.invalidateTags('todos')` purges them.
26
+ *
27
+ * Any other middleware in `options.use` composes normally; this one is placed first so
28
+ * it seeds the config and wraps the fetcher before they transform either.
29
+ *
30
+ * Invalidating by tag (the fetcher runs again on the next mount; SWR's in-memory copy
31
+ * keeps its own lifecycle, so revalidate it too when it must change on the spot):
32
+ *
33
+ * ```ts
34
+ * cache.invalidateTags('todos');
35
+ * mutate('/api/todos'); // SWR's own revalidation for the mounted hook
36
+ * ```
37
+ *
38
+ * @param cache The Blaze Cache (or anything {@link BlazeSWRCacheLike}-shaped).
39
+ * @param key The SWR key — string, tuple, object, or a lazy function; `null` pauses.
40
+ * @param fetcher The fetcher; omit it (or pass `null`) to use a global one or for
41
+ * client-side state — the cache is still read, nothing is written.
42
+ * @param options Normal SWR options plus `ttlMs`/`tags`.
43
+ */
44
+ export function useBlazeSWR(cache, key, fetcher = null, options = {}) {
45
+ const { use, ...swrOptions } = options;
46
+ return useSWR(key, fetcher, {
47
+ // `ttlMs`/`tags` deliberately stay *in* the config: SWR merges an `SWRConfig`
48
+ // provider's values into it too, and hook-level options win that merge — so a
49
+ // per-call stamp reaches the middleware's `config.ttlMs ?? options.ttlMs ?? default`
50
+ // read as the highest precedence. Stripping them into the middleware's own options
51
+ // would invert that: the provider's config value would then shadow the per-call one.
52
+ ...swrOptions,
53
+ use: [blazeSWRMiddleware(cache, { ttlMs: options.ttlMs, tags: options.tags }), ...(use ?? [])],
54
+ });
55
+ }
56
+ //# sourceMappingURL=useBlazeSWR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useBlazeSWR.js","sourceRoot":"","sources":["../src/useBlazeSWR.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,KAAK,CAAC;AAGzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAGrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,MAAM,UAAU,WAAW,CAKzB,KAAwB,EACxB,GAAW,EACX,UAAwC,IAAI,EAC5C,UAA+D,EAAE;IAEjE,MAAM,EAAE,GAAG,EAAE,GAAG,UAAU,EAAE,GAAG,OAAO,CAAC;IAEvC,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE;QAC1B,8EAA8E;QAC9E,8EAA8E;QAC9E,qFAAqF;QACrF,mFAAmF;QACnF,qFAAqF;QACrF,GAAG,UAAU;QACb,GAAG,EAAE,CAAC,kBAAkB,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;KAC/F,CAA6B,CAAC;AACjC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@blaze-cache/swr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0-beta.0",
4
+ "description": "Persist SWR in WebAssembly — instant first paint after reload while stale-while-revalidate still works",
5
+ "keywords": [
6
+ "swr",
7
+ "react",
8
+ "cache",
9
+ "persistence",
10
+ "stale-while-revalidate",
11
+ "webassembly",
12
+ "wasm"
13
+ ],
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/blaze-cache/blaze-cache.git",
18
+ "directory": "packages/swr"
19
+ },
20
+ "homepage": "https://blaze-cache.github.io/docs/",
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "sideEffects": false,
25
+ "type": "module",
26
+ "main": "dist/index.js",
27
+ "types": "dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "dependencies": {
38
+ "@blaze-cache/core": "0.3.0-beta.0"
39
+ },
40
+ "peerDependencies": {
41
+ "swr": "^2.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "swr": "^2.5.1",
45
+ "typescript": "^5.9.3"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.json",
49
+ "test": "pnpm run build && node --experimental-test-module-mocks --test",
50
+ "typecheck": "tsc -p tsconfig.typecheck.json"
51
+ }
6
52
  }