@blaze-cache/ky 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/dist/hook.js ADDED
@@ -0,0 +1,391 @@
1
+ import { NO_DIRECTIVES, parseAgeMs, parseCacheControl, varyIsStorable } from './cache-control.js';
2
+ import { defaultCacheKey } from './key.js';
3
+ /** Freshness window when neither the option nor `Cache-Control` says otherwise. */
4
+ const DEFAULT_TTL_MS = 60_000;
5
+ /** Only `GET` is cached unless the caller says otherwise. */
6
+ const DEFAULT_METHODS = ['GET'];
7
+ /** A personalized response must never be replayed to a different user. */
8
+ const DEFAULT_VARY_HEADERS = ['authorization'];
9
+ const DEFAULT_MARKER_HEADER = 'x-blaze-cache';
10
+ /**
11
+ * Statuses that cannot carry a body — a replay must pass `null` for them.
12
+ *
13
+ * `101` is deliberately **not** here: the `Response` constructor rejects it outright
14
+ * (`RangeError: init.status` must be 200–599), so a stored 101 could never be rebuilt at
15
+ * all — and none can ever reach the store, since ky never surfaces a 101 to JavaScript.
16
+ */
17
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
18
+ /**
19
+ * ky hooks that cache HTTP responses through Blaze Cache.
20
+ *
21
+ * Two hooks, matched to ky's own architecture: `beforeRequest` may answer a request from
22
+ * the cache by returning a `Response` (ky skips the network), and `afterResponse` — which
23
+ * receives a *clone* of every response — stores what is worth keeping and stamps the
24
+ * `x-blaze-cache` marker.
25
+ *
26
+ * ```ts
27
+ * import ky from 'ky';
28
+ * import { blazeKyHook } from '@blaze-cache/ky';
29
+ *
30
+ * const api = ky.extend({
31
+ * hooks: {
32
+ * ...blazeKyHook(cache, { ttlMs: 30_000 }),
33
+ * },
34
+ * });
35
+ * ```
36
+ *
37
+ * Works on **ky v1 and v2**: their hooks take different shapes — `(request, options, …)` in
38
+ * v1, a single `{request, options, …}` state object in v2 — and these hooks recognise
39
+ * whichever they are called with, from the first argument alone.
40
+ *
41
+ * Ordering: `ky.extend` appends hooks, so with `blazeKyHook`'s hooks spread in last (the
42
+ * usual `hooks: {...blazeKyHook(cache)}` spelling), *your* `beforeRequest` hooks run first
43
+ * — any header they add is folded into the cache key — and *your* `afterResponse` hooks
44
+ * run before the store sees the response.
45
+ */
46
+ export function blazeKyHook(cache, options = {}) {
47
+ const markerHeader = options.markerHeader === undefined ? DEFAULT_MARKER_HEADER : options.markerHeader;
48
+ const methods = new Set((options.methods ?? DEFAULT_METHODS).map((method) => method.toUpperCase()));
49
+ const cacheControl = options.cacheControl ?? true;
50
+ const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
51
+ const shouldCache = options.shouldCache ?? defaultShouldCache;
52
+ /**
53
+ * Requests this closure answered from the cache, by object identity.
54
+ *
55
+ * ky runs `afterResponse` on a `beforeRequest`-returned response too — the cache hit
56
+ * travels back through the same pipeline as a network response. Without this set the
57
+ * hit would be re-stored on its way out, sliding its TTL a little on every read.
58
+ * Identity is precise here: a served hit never reaches the network, so its request can
59
+ * never come back around a retry.
60
+ */
61
+ const servedFromCache = new WeakSet();
62
+ /**
63
+ * Whether a cache-layer failure has been reported already.
64
+ *
65
+ * A throwing `cache.get`/`cache.set` or callback must never fail a request the network
66
+ * answered well — the first such failure is announced, then the adapter keeps working
67
+ * (uncached) in silence rather than spamming the console on every call.
68
+ */
69
+ let warned = false;
70
+ /** The one place a cache-layer exception is allowed to surface: a single console warning. */
71
+ function warnCacheFailure(error) {
72
+ if (warned)
73
+ return;
74
+ warned = true;
75
+ console.warn('[blaze-cache] cache layer failed; continuing without it', error);
76
+ }
77
+ const keyOf = (request) => options.key ? options.key(request) : defaultCacheKey(request, varyHeaders);
78
+ /**
79
+ * `cache.get`, guarded: a cache-layer failure reads as a plain miss — the request falls
80
+ * through to the network instead of failing over a broken cache.
81
+ */
82
+ function read(key) {
83
+ try {
84
+ return cache.get(key);
85
+ }
86
+ catch (error) {
87
+ warnCacheFailure(error);
88
+ return undefined;
89
+ }
90
+ }
91
+ const beforeRequest = (requestOrState) => {
92
+ const request = unwrapRequest(requestOrState);
93
+ if (!request || !methods.has(request.method.toUpperCase()))
94
+ return undefined;
95
+ // The caller's instruction (`Request.cache`), the caller's headers, and the server's
96
+ // `Cache-Control` — with `cacheControl: false` only the first two are still obeyed.
97
+ const control = cacheControl ? parseCacheControl(request.headers.get('Cache-Control')) : NO_DIRECTIVES;
98
+ // `max-age=0` is, per RFC 9111 §5.2.2.1, a demand to revalidate before reuse. This
99
+ // cache has no conditional requests, so the closest honest reading is a full refetch
100
+ // — exactly what skipping the read does — rather than replaying the entry untouched.
101
+ const bypassRead = control.noStore ||
102
+ control.noCache ||
103
+ control.maxAgeMs === 0 ||
104
+ request.cache === 'no-store' ||
105
+ request.cache === 'no-cache' ||
106
+ request.cache === 'reload';
107
+ if (bypassRead)
108
+ return undefined;
109
+ const key = keyOf(request);
110
+ const record = read(key);
111
+ if (!isKyRecord(record))
112
+ return undefined;
113
+ // `force-cache` means "use it whatever its age"; otherwise freshness decides.
114
+ if (request.cache !== 'force-cache' && Date.now() > record.freshUntil) {
115
+ // Past its own deadline — the store itself may never expire anything (the types
116
+ // bless a plain `Map` shim, which drops nothing), so *our* record is dropped here.
117
+ // Left alone it would linger as dead weight that nothing is allowed to serve.
118
+ try {
119
+ cache.delete?.(key);
120
+ }
121
+ catch (error) {
122
+ warnCacheFailure(error);
123
+ }
124
+ return undefined;
125
+ }
126
+ servedFromCache.add(request);
127
+ return replay(record, 'HIT');
128
+ };
129
+ const afterResponse = (requestOrState, _options, responseOrState) => {
130
+ const request = unwrapRequest(requestOrState);
131
+ // ky v1 passes the response positionally; ky v2 bundles it into the state object.
132
+ const response = unwrapResponse(responseOrState, requestOrState);
133
+ if (!request || !response)
134
+ return undefined;
135
+ // A response we replayed ourselves is on its way back to the caller — never re-store
136
+ // it, never re-mark it. See `servedFromCache`.
137
+ if (servedFromCache.has(request))
138
+ return undefined;
139
+ const control = cacheControl ? parseCacheControl(request.headers.get('Cache-Control')) : NO_DIRECTIVES;
140
+ // `no-store` on the request: neither read (above) nor write. The read-only directives
141
+ // (`no-cache`, `max-age=0`, `reload`) skip the read but still refresh the entry.
142
+ const bypassWrite = control.noStore || request.cache === 'no-store';
143
+ if (!bypassWrite && methods.has(request.method.toUpperCase())) {
144
+ // The response's own `Vary` gates the store: `Vary: *` is never cacheable, and a
145
+ // response varying on a header outside `varyHeaders` would be replayed to callers
146
+ // who differ in exactly that header — see `varyIsStorable` for why "unknown ⇒ do
147
+ // not store" is the only safe answer.
148
+ if (varyIsStorable(response.headers.get('Vary'), varyHeaders)) {
149
+ let keep = false;
150
+ try {
151
+ keep = shouldCache(response, request);
152
+ }
153
+ catch (error) {
154
+ // A callback that throws must not fail the response the network just delivered.
155
+ warnCacheFailure(error);
156
+ }
157
+ if (keep) {
158
+ // Tee now: `mark` below may rebuild the response around its body stream, and a
159
+ // body can be consumed exactly once. Deliberately fire-and-forget — the caller's
160
+ // branch of the tee delivers bytes while `store` buffers its own, so nothing
161
+ // about this response's latency depends on the write, and the record is complete
162
+ // (never half-written) by the time `cache.set` runs.
163
+ let stored;
164
+ let storeKey;
165
+ try {
166
+ stored = response.clone();
167
+ storeKey = keyOf(request);
168
+ }
169
+ catch (error) {
170
+ // A clone that refuses (an exotic host handing over an already-consumed body)
171
+ // or a `key` callback that throws must not fail a response the network just
172
+ // delivered — it simply goes back uncached. Here, unlike in `beforeRequest`,
173
+ // the request has already been answered once: failing it over a cache-layer
174
+ // mistake would be doubly wrong.
175
+ warnCacheFailure(error);
176
+ }
177
+ if (stored !== undefined && storeKey !== undefined) {
178
+ void store(stored, request, storeKey).catch(warnCacheFailure);
179
+ }
180
+ }
181
+ }
182
+ }
183
+ // Marked last, so `shouldCache`/`tags`/`ttlMs` see exactly what the network sent.
184
+ return mark(response, 'MISS');
185
+ };
186
+ /**
187
+ * Buffers the body and writes the record. Returns early when nothing is worth keeping.
188
+ *
189
+ * The response it reads is the tee taken in `afterResponse`, so every millisecond it
190
+ * spends buffering is invisible to the caller — and the record is complete before
191
+ * `cache.set` runs, so a hit can never half-load.
192
+ */
193
+ async function store(response, request, key) {
194
+ // An opaque response (`no-cors`) exposes no status, headers or body: nothing to store.
195
+ if (response.status === 0)
196
+ return;
197
+ const control = cacheControl ? parseCacheControl(response.headers.get('Cache-Control')) : NO_DIRECTIVES;
198
+ // `no-store` forbids storing; `no-cache` demands revalidation on every use, and this
199
+ // cache has no conditional requests — so neither is worth an entry.
200
+ if (control.noStore || control.noCache)
201
+ return;
202
+ const configured = options.ttlMs;
203
+ const ttl = typeof configured === 'function' ? configured(response, request) : (configured ?? DEFAULT_TTL_MS);
204
+ // The response's own `max-age` wins; the option is the fallback for servers that never
205
+ // send one. `Age` spends the origin's freshness budget before it reaches us: a
206
+ // `max-age=60, Age: 50` response has ten seconds of life left, not sixty.
207
+ const age = cacheControl ? parseAgeMs(response.headers.get('Age')) : 0;
208
+ const freshMs = (control.maxAgeMs ?? ttl) - age;
209
+ // Zero, negative or `NaN` means "keep nothing": already stale, or the caller opted out.
210
+ if (!(freshMs > 0))
211
+ return;
212
+ let body;
213
+ try {
214
+ // Fully buffered *before* `cache.set`, so a follow-up read can never race a
215
+ // half-written entry.
216
+ body = await response.arrayBuffer();
217
+ }
218
+ catch {
219
+ return; // a body that fails mid-flight must not poison the cache
220
+ }
221
+ const storedAt = Date.now();
222
+ const record = {
223
+ status: response.status,
224
+ statusText: response.statusText,
225
+ headers: storedHeaders(response.headers, body),
226
+ body,
227
+ // A real network response carries its final (post-redirect) URL. A `Response` that
228
+ // ky or another hook rebuilt from scratch has none — and for those the URL being
229
+ // answered is the honest metadata, never an empty string.
230
+ url: response.url || request.url,
231
+ redirected: response.redirected,
232
+ storedAt,
233
+ freshUntil: storedAt + freshMs,
234
+ };
235
+ cache.set(key, record, {
236
+ // `0` is how the core spells "never expires" — reached only via `ttlMs: Infinity`.
237
+ ttlMs: Number.isFinite(freshMs) ? freshMs : 0,
238
+ tags: options.tags?.(response, request) ?? defaultTags(request),
239
+ });
240
+ }
241
+ /** Rebuilds a `Response` from a stored record. */
242
+ function replay(record, marker) {
243
+ const headers = headersFromRecord(record.headers);
244
+ if (markerHeader !== false)
245
+ headers.set(markerHeader, marker);
246
+ const response = new Response(NULL_BODY_STATUSES.has(record.status) ? null : record.body, { status: record.status, statusText: record.statusText, headers });
247
+ // `url`/`redirected` are read-only accessors on the prototype; an own property shadows
248
+ // them so a hit carries the metadata of the network response it stands in for.
249
+ defineOwn(response, 'url', record.url);
250
+ defineOwn(response, 'redirected', record.redirected);
251
+ return response;
252
+ }
253
+ /** Stamps the marker on a network response, rebuilding it only if its headers refuse. */
254
+ function mark(response, marker) {
255
+ if (markerHeader === false)
256
+ return response;
257
+ try {
258
+ response.headers.set(markerHeader, marker);
259
+ return response;
260
+ }
261
+ catch {
262
+ // Immutable headers (network responses in undici, `Response.redirect()`): rebuild so
263
+ // the marker contract holds — the marker goes on the *rebuild*, since the original
264
+ // refused it. Status 0 cannot be rebuilt at all: pass it through unmarked.
265
+ if (response.status === 0)
266
+ return response;
267
+ const headers = new Headers(response.headers);
268
+ headers.set(markerHeader, marker);
269
+ const rebuilt = new Response(response.body, {
270
+ status: response.status,
271
+ statusText: response.statusText,
272
+ headers,
273
+ });
274
+ defineOwn(rebuilt, 'url', response.url);
275
+ defineOwn(rebuilt, 'redirected', response.redirected);
276
+ return rebuilt;
277
+ }
278
+ }
279
+ return { beforeRequest: [beforeRequest], afterResponse: [afterResponse] };
280
+ }
281
+ /** Successful responses only. The {@link BlazeKyCacheOptions.methods} gate has already applied. */
282
+ function defaultShouldCache(response) {
283
+ return response.status >= 200 && response.status < 300;
284
+ }
285
+ /**
286
+ * Shape check: is this value one **this adapter** wrote?
287
+ *
288
+ * `freshUntil` is the deadline every record carries and `body` the payload it always
289
+ * stores — a value missing either belongs to something else sharing the cache (a
290
+ * `FetchCacheRecord` has a `freshUntil` but no `ArrayBuffer` body; raw SWR and react-query
291
+ * values carry neither), and a read must neither serve nor destroy it. On a
292
+ * single-integration cache this is always true; the check exists for the shared one, and
293
+ * keeps a foreign value from throwing inside `replay` — where ky would treat the error as
294
+ * fatal and fail the request over a cache entry that was never ours.
295
+ */
296
+ function isKyRecord(value) {
297
+ return typeof value?.freshUntil === 'number' && value.body instanceof ArrayBuffer;
298
+ }
299
+ /**
300
+ * `['ky', '<method> <url>']` — one tag drops everything this adapter stored
301
+ * (`cache.invalidateTags('ky')`), the other drops a single resource. The second tag uses
302
+ * the same `<method> <url>` spelling as `@blaze-cache/fetch` and `@blaze-cache/axios`, so
303
+ * integrations pointed at one shared cache invalidate together.
304
+ */
305
+ function defaultTags(request) {
306
+ return ['ky', `${request.method.toLowerCase()} ${request.url}`];
307
+ }
308
+ /**
309
+ * ky v1 calls hooks as `(request, options, state)`; ky v2 as a single `{request, options,
310
+ * …}` state object. A real `Request` as the first argument means v1 — otherwise the state
311
+ * object's `request` is taken. The guard keeps a future third spelling from throwing here:
312
+ * an unrecognised call simply bypasses the cache, which is the safe direction.
313
+ */
314
+ function unwrapRequest(value) {
315
+ if (value instanceof Request)
316
+ return value;
317
+ const request = value?.request;
318
+ return request instanceof Request ? request : undefined;
319
+ }
320
+ /**
321
+ * The `afterResponse` response, in whichever shape the ky major hands it over: a
322
+ * positional third argument (ky v1) or `state.response` on the first (ky v2).
323
+ */
324
+ function unwrapResponse(responseOrState, requestOrState) {
325
+ if (responseOrState instanceof Response)
326
+ return responseOrState;
327
+ const bundled = requestOrState?.response;
328
+ if (bundled instanceof Response)
329
+ return bundled;
330
+ const nested = responseOrState?.response;
331
+ return nested instanceof Response ? nested : undefined;
332
+ }
333
+ /**
334
+ * Response headers as a plain record, corrected to describe the bytes we actually hold.
335
+ *
336
+ * `fetch` decodes `content-encoding` for us, so a stored body is always the plain payload
337
+ * while the headers still describe the *wire* format — `gzip` plus the compressed
338
+ * `content-length` (on a real API: 1425 bytes claimed for 6504 stored). Replaying those
339
+ * would hand back a response that contradicts itself, breaking anything that reads
340
+ * `content-length` — a file downloader, `blob().size`, a progress bar — or that trusts the
341
+ * encoding and tries to inflate plain bytes. `transfer-encoding` is hop-by-hop and stops
342
+ * being true the moment the body is buffered.
343
+ *
344
+ * HEAD is the one exception: no body was ever sent, so its `content-length` and
345
+ * `content-encoding` describe what a GET *would* return and stay as metadata.
346
+ */
347
+ function storedHeaders(headers, body) {
348
+ const record = headersToRecord(headers);
349
+ delete record['transfer-encoding'];
350
+ if (body.byteLength > 0) {
351
+ delete record['content-encoding'];
352
+ if ('content-length' in record)
353
+ record['content-length'] = String(body.byteLength);
354
+ }
355
+ return record;
356
+ }
357
+ /** Copies headers into a plain, structured-clone-friendly record. */
358
+ function headersToRecord(headers) {
359
+ const record = {};
360
+ // `Headers.forEach` reports names already lower-cased. Defined, never assigned: a plain
361
+ // `record[name] = value` hands a literal `__proto__` to the inherited setter, which
362
+ // ignores primitives — silently dropping a perfectly legal header instead of storing it.
363
+ headers.forEach((value, name) => {
364
+ Object.defineProperty(record, name, { value, enumerable: true, writable: true, configurable: true });
365
+ });
366
+ return record;
367
+ }
368
+ /**
369
+ * Rebuilds a `Headers` from a stored record, name by name.
370
+ *
371
+ * Never `new Headers(record)`: the platform's plain-object conversion drops a literal
372
+ * `__proto__` key on its way through the inherited setter, losing a legal header between
373
+ * the store and the replay. `append` accepts every name the store can hold.
374
+ */
375
+ function headersFromRecord(record) {
376
+ const headers = new Headers();
377
+ for (const [name, value] of Object.entries(record)) {
378
+ headers.append(name, value);
379
+ }
380
+ return headers;
381
+ }
382
+ /** Shadows a read-only prototype accessor with an own property; never throws. */
383
+ function defineOwn(target, key, value) {
384
+ try {
385
+ Object.defineProperty(target, key, { value, writable: true, enumerable: false, configurable: true });
386
+ }
387
+ catch {
388
+ // A frozen response: the missing metadata is cosmetic, never worth failing a hit over.
389
+ }
390
+ }
391
+ //# sourceMappingURL=hook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook.js","sourceRoot":"","sources":["../src/hook.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aA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,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IACvG,CAAC;IAAC,MAAM,CAAC;QACP,uFAAuF;IACzF,CAAC;AACH,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * ky hooks that cache HTTP responses through a WebAssembly cache.
3
+ *
4
+ * ky is built on `fetch` and designed around hooks, so caching is two of them: one that
5
+ * answers a request from the cache by returning a `Response` (ky skips the network
6
+ * entirely), and one that stores the response worth keeping. Per-entry TTLs, tag-based
7
+ * invalidation, `Cache-Control` on both sides of the exchange and SIEVE eviction all come
8
+ * from {@link createCache | `@blaze-cache/core`} — and both ky majors are supported:
9
+ * v1's `(request, options, response, state)` hooks and v2's single-state-object hooks are
10
+ * recognised at runtime, from one implementation.
11
+ *
12
+ * ```ts
13
+ * import ky from 'ky';
14
+ * import { blazeKyHook, createBlazeKy } from '@blaze-cache/ky';
15
+ * import { createCache } from '@blaze-cache/core';
16
+ *
17
+ * const cache = await createCache({ capacity: 1000 });
18
+ *
19
+ * // Hook style (preferred, fits ky):
20
+ * const api = ky.extend({
21
+ * hooks: {
22
+ * ...blazeKyHook(cache, { ttlMs: 30_000, methods: ['GET'] }),
23
+ * },
24
+ * });
25
+ *
26
+ * // Helper style:
27
+ * const api = createBlazeKy(cache, { prefixUrl: 'https://api.example.com', ttlMs: 30_000 });
28
+ *
29
+ * const users = await api.get('users').json();
30
+ * ```
31
+ *
32
+ * @packageDocumentation
33
+ */
34
+ export { blazeKyHook } from './hook.js';
35
+ export { createBlazeKy } from './client.js';
36
+ export { parseCacheControl, parseAgeMs, varyIsStorable } from './cache-control.js';
37
+ export type { CacheControl } from './cache-control.js';
38
+ export { defaultCacheKey, fnv1a } from './key.js';
39
+ export type { BlazeKyAfterResponseHook, BlazeKyBeforeRequestHook, BlazeKyCacheLike, BlazeKyCacheOptions, BlazeKyHookState, BlazeKyHooks, BlazeKyMarker, CreateBlazeKyOptions, KyCacheRecord, } from './types.js';
40
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACnF,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAElD,YAAY,EACV,wBAAwB,EACxB,wBAAwB,EACxB,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,oBAAoB,EACpB,aAAa,GACd,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * ky hooks that cache HTTP responses through a WebAssembly cache.
3
+ *
4
+ * ky is built on `fetch` and designed around hooks, so caching is two of them: one that
5
+ * answers a request from the cache by returning a `Response` (ky skips the network
6
+ * entirely), and one that stores the response worth keeping. Per-entry TTLs, tag-based
7
+ * invalidation, `Cache-Control` on both sides of the exchange and SIEVE eviction all come
8
+ * from {@link createCache | `@blaze-cache/core`} — and both ky majors are supported:
9
+ * v1's `(request, options, response, state)` hooks and v2's single-state-object hooks are
10
+ * recognised at runtime, from one implementation.
11
+ *
12
+ * ```ts
13
+ * import ky from 'ky';
14
+ * import { blazeKyHook, createBlazeKy } from '@blaze-cache/ky';
15
+ * import { createCache } from '@blaze-cache/core';
16
+ *
17
+ * const cache = await createCache({ capacity: 1000 });
18
+ *
19
+ * // Hook style (preferred, fits ky):
20
+ * const api = ky.extend({
21
+ * hooks: {
22
+ * ...blazeKyHook(cache, { ttlMs: 30_000, methods: ['GET'] }),
23
+ * },
24
+ * });
25
+ *
26
+ * // Helper style:
27
+ * const api = createBlazeKy(cache, { prefixUrl: 'https://api.example.com', ttlMs: 30_000 });
28
+ *
29
+ * const users = await api.get('users').json();
30
+ * ```
31
+ *
32
+ * @packageDocumentation
33
+ */
34
+ export { blazeKyHook } from './hook.js';
35
+ export { createBlazeKy } from './client.js';
36
+ export { parseCacheControl, parseAgeMs, varyIsStorable } from './cache-control.js';
37
+ export { defaultCacheKey, fnv1a } from './key.js';
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGnF,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC"}
package/dist/key.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * FNV-1a, 32-bit.
3
+ *
4
+ * Folds sensitive material (bearer tokens, `vary` headers) into a short, stable token. It is
5
+ * not a security primitive — the point is that a persisted cache key never contains a secret
6
+ * in readable form.
7
+ */
8
+ export declare function fnv1a(input: string): string;
9
+ /**
10
+ * Default cache key: method + URL, plus a hash of the `varyHeaders` values.
11
+ *
12
+ * ```ts
13
+ * defaultCacheKey(request, ['authorization']); // "get https://api.example.com/users?a3f9k"
14
+ * ```
15
+ *
16
+ * By the time ky's hooks run, the `Request` is already the *final* request: `prefixUrl`
17
+ * (ky v1) / `baseUrl` (ky v2) and `searchParams` applied, method normalized and headers
18
+ * merged — so its `url` is exactly what will go on the wire, and one endpoint occupies one
19
+ * entry instead of every spelling of it.
20
+ *
21
+ * The hash is appended whenever `varyHeaders` is non-empty — including when every value is
22
+ * absent — so keys stay stable across calls. Pass `varyHeaders: []` to get the bare
23
+ * `"<method> <url>"` form. Call it from the {@link BlazeKyCacheOptions.key} callback with
24
+ * the `request` you were handed.
25
+ */
26
+ export declare function defaultCacheKey(request: Request, varyHeaders: readonly string[]): string;
27
+ //# sourceMappingURL=key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key.d.ts","sourceRoot":"","sources":["../src/key.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAO3C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAWxF"}
package/dist/key.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * FNV-1a, 32-bit.
3
+ *
4
+ * Folds sensitive material (bearer tokens, `vary` headers) into a short, stable token. It is
5
+ * not a security primitive — the point is that a persisted cache key never contains a secret
6
+ * in readable form.
7
+ */
8
+ export function fnv1a(input) {
9
+ let hash = 0x811c9dc5;
10
+ for (let index = 0; index < input.length; index += 1) {
11
+ hash ^= input.charCodeAt(index);
12
+ hash = Math.imul(hash, 0x01000193) >>> 0;
13
+ }
14
+ return hash.toString(36);
15
+ }
16
+ /**
17
+ * Default cache key: method + URL, plus a hash of the `varyHeaders` values.
18
+ *
19
+ * ```ts
20
+ * defaultCacheKey(request, ['authorization']); // "get https://api.example.com/users?a3f9k"
21
+ * ```
22
+ *
23
+ * By the time ky's hooks run, the `Request` is already the *final* request: `prefixUrl`
24
+ * (ky v1) / `baseUrl` (ky v2) and `searchParams` applied, method normalized and headers
25
+ * merged — so its `url` is exactly what will go on the wire, and one endpoint occupies one
26
+ * entry instead of every spelling of it.
27
+ *
28
+ * The hash is appended whenever `varyHeaders` is non-empty — including when every value is
29
+ * absent — so keys stay stable across calls. Pass `varyHeaders: []` to get the bare
30
+ * `"<method> <url>"` form. Call it from the {@link BlazeKyCacheOptions.key} callback with
31
+ * the `request` you were handed.
32
+ */
33
+ export function defaultCacheKey(request, varyHeaders) {
34
+ const base = `${request.method.toLowerCase()} ${request.url}`;
35
+ if (varyHeaders.length === 0)
36
+ return base;
37
+ // JSON, never a plain join: the encoding must stay *injective*, because a collision here
38
+ // would replay one identity's payload to another. Joining with a space lets a value
39
+ // containing the separator impersonate the boundary — `['x y', '']` and `['x', 'y']` are
40
+ // two different identities, and only a length-delimited encoding (JSON being the simplest)
41
+ // keeps them apart.
42
+ const vary = JSON.stringify(varyHeaders.map((name) => request.headers.get(name) ?? ''));
43
+ return `${base}?${fnv1a(vary)}`;
44
+ }
45
+ //# sourceMappingURL=key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key.js","sourceRoot":"","sources":["../src/key.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,UAAU,KAAK,CAAC,KAAa;IACjC,IAAI,IAAI,GAAG,UAAU,CAAC;IACtB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACrD,IAAI,IAAI,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QAChC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AAC3B,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,eAAe,CAAC,OAAgB,EAAE,WAA8B;IAC9E,MAAM,IAAI,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IAC9D,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAE1C,yFAAyF;IACzF,oFAAoF;IACpF,yFAAyF;IACzF,2FAA2F;IAC3F,oBAAoB;IACpB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACxF,OAAO,GAAG,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;AAClC,CAAC"}