@blaze-cache/ofetch 0.0.0-stage → 0.4.0-beta.1

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/index.js ADDED
@@ -0,0 +1,47 @@
1
+ import { ofetch } from 'ofetch';
2
+ import { blazeOfetch } from './client.js';
3
+ /**
4
+ * Creates a Blaze-cached ofetch instance from scratch.
5
+ *
6
+ * ```ts
7
+ * import { createBlazeOfetch } from '@blaze-cache/ofetch';
8
+ * import { createCache } from '@blaze-cache/core';
9
+ *
10
+ * const cache = createCache({ maxEntries: 500 });
11
+ * const api = createBlazeOfetch(cache, {
12
+ * baseURL: 'https://api.example.com',
13
+ * ttlMs: 30_000,
14
+ * tags: (res, ctx) => ['ofetch', ctx.url],
15
+ * });
16
+ *
17
+ * const users = await api('/users'); // parsed JSON, cached
18
+ * const res = await api.raw('/users'); // FetchResponse with x-blaze-cache marker
19
+ * ```
20
+ *
21
+ * ofetch defaults (like `baseURL`, `headers`, `retry`, `timeout`, `query`) and Blaze Cache
22
+ * options are passed in a single bag and split apart here. A custom `fetch` implementation
23
+ * (if provided) is forwarded as ofetch's global fetch override.
24
+ *
25
+ * @param cache The Blaze Cache instance (or any {@link BlazeOfetchCacheLike}).
26
+ * @param options ofetch defaults mixed with {@link BlazeOfetchOptions}.
27
+ */
28
+ export function createBlazeOfetch(cache, options = {}) {
29
+ const { ttlMs, methods, cacheControl, key, shouldCache, tags, varyHeaders, markerHeader, fetch: customFetch, ...ofetchOptions } = options;
30
+ const globalOpts = customFetch ? { fetch: customFetch } : undefined;
31
+ const instance = ofetch.create(ofetchOptions, globalOpts);
32
+ return blazeOfetch(instance, cache, {
33
+ ttlMs,
34
+ methods,
35
+ cacheControl,
36
+ key,
37
+ shouldCache,
38
+ tags,
39
+ varyHeaders,
40
+ markerHeader,
41
+ baseURL: ofetchOptions.baseURL ?? options.baseURL,
42
+ });
43
+ }
44
+ export { blazeOfetch } from './client.js';
45
+ export { defaultCacheKey, fnv1a } from './key.js';
46
+ export { parseAgeMs, parseCacheControl, varyIsStorable, NO_DIRECTIVES } from './cache-control.js';
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAO1C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAA2B,EAC3B,UAA0E,EAAE;IAE5E,MAAM,EACJ,KAAK,EACL,OAAO,EACP,YAAY,EACZ,GAAG,EACH,WAAW,EACX,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,KAAK,EAAE,WAAW,EAClB,GAAG,aAAa,EACjB,GAAG,OAAyE,CAAC;IAE9E,MAAM,UAAU,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IACpE,MAAM,QAAQ,GAAW,MAAM,CAAC,MAAM,CAAC,aAA6B,EAAE,UAAiB,CAAC,CAAC;IACzF,OAAO,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE;QAClC,KAAK;QACL,OAAO;QACP,YAAY;QACZ,GAAG;QACH,WAAW;QACX,IAAI;QACJ,WAAW;QACX,YAAY;QACZ,OAAO,EAAG,aAA8B,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;KACpE,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/key.d.ts ADDED
@@ -0,0 +1,67 @@
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
6
+ * secret in readable form.
7
+ */
8
+ export declare function fnv1a(input: string): string;
9
+ /**
10
+ * Whether a url already names its own origin, so no `baseURL` has to be applied to it.
11
+ *
12
+ * A relative url is the dangerous one: it is what a request looks like *before* the
13
+ * instance's `baseURL` is applied, and two wrappers over different origins produce the
14
+ * same relative url for two entirely different resources.
15
+ */
16
+ export declare function isAbsoluteUrl(url: string): boolean;
17
+ /** Whether a request actually carries a body — `null`/`undefined` mean it does not. */
18
+ export declare function hasRequestBody(body: unknown): boolean;
19
+ /**
20
+ * The request body as a stable, injective string for the cache key — or `undefined` when
21
+ * the body **cannot** be encoded and the request must therefore stay uncached.
22
+ *
23
+ * A body that reaches the key wrong is worse than no cached body at all: two different
24
+ * payloads would hash onto one entry and the first response would be replayed for the
25
+ * second. So anything whose content this function cannot actually read is refused rather
26
+ * than approximated:
27
+ *
28
+ * * a stream (`ReadableStream`, a `Request`'s body), a `Blob`/`File` or raw bytes have no
29
+ * readable own properties — `JSON.stringify` renders each as the bare `'{}'`, which would
30
+ * collapse *every* such body onto *one* key;
31
+ * * an object that serialises to `'{}'` for any other reason (a class instance keeping its
32
+ * data in private fields, an empty object) carries nothing to tell bodies apart by;
33
+ * * a circular structure throws out of `JSON.stringify`.
34
+ *
35
+ * Note the ordering rule: `JSON.stringify` walks own keys in insertion order, so two
36
+ * structurally equal bodies spelled with different key order produce different keys. That
37
+ * costs a cache miss and nothing worse — the direction of the error is "did not reuse",
38
+ * never "reused the wrong response". Canonicalising the order instead would mean building
39
+ * a sorted copy of caller data, which is exactly where `__proto__` handling goes wrong.
40
+ */
41
+ export declare function encodeRequestBody(body: unknown): string | undefined;
42
+ /**
43
+ * Default cache key: method + resolved URL, plus a hash of the `varyHeaders` values and of
44
+ * the request body.
45
+ *
46
+ * ```ts
47
+ * defaultCacheKey('GET', 'https://api.example.com/users', headers, ['authorization']);
48
+ * // "get https://api.example.com/users?a3f9k"
49
+ * ```
50
+ *
51
+ * The URL must be the *resolved* one (after `baseURL` and `query`/`params`), so one
52
+ * endpoint occupies one entry regardless of how it was spelled at the call site — and so
53
+ * two wrappers pointing at different origins can never share an entry. The adapter only
54
+ * calls this once it knows the full URL (see `isAbsoluteUrl`).
55
+ *
56
+ * The hash is appended whenever `varyHeaders` is non-empty — including when every value is
57
+ * absent — so keys stay stable across calls. Pass `varyHeaders: []` to get the bare
58
+ * `"<method> <url>"` form.
59
+ *
60
+ * A request that carries a body folds that body into the hash, so `POST /orders` with two
61
+ * different payloads occupies two entries instead of replaying one for the other.
62
+ *
63
+ * @throws when a body is present but {@link encodeRequestBody} cannot read it — callers
64
+ * that must not throw should check first and skip caching instead.
65
+ */
66
+ export declare function defaultCacheKey(method: string, url: string, headers: Headers, varyHeaders: readonly string[], body?: unknown): string;
67
+ //# 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;AAKD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAElD;AAED,uFAAuF;AACvF,wBAAgB,cAAc,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAErD;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CA2CnE;AASD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,SAAS,MAAM,EAAE,EAC9B,IAAI,CAAC,EAAE,OAAO,GACb,MAAM,CAqBR"}
package/dist/key.js ADDED
@@ -0,0 +1,147 @@
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
6
+ * secret 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
+ /** axios' own `isAbsoluteURL` test — a scheme or `//` makes the url absolute. */
17
+ const ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
18
+ /**
19
+ * Whether a url already names its own origin, so no `baseURL` has to be applied to it.
20
+ *
21
+ * A relative url is the dangerous one: it is what a request looks like *before* the
22
+ * instance's `baseURL` is applied, and two wrappers over different origins produce the
23
+ * same relative url for two entirely different resources.
24
+ */
25
+ export function isAbsoluteUrl(url) {
26
+ return ABSOLUTE_URL.test(url);
27
+ }
28
+ /** Whether a request actually carries a body — `null`/`undefined` mean it does not. */
29
+ export function hasRequestBody(body) {
30
+ return body !== undefined && body !== null;
31
+ }
32
+ /**
33
+ * The request body as a stable, injective string for the cache key — or `undefined` when
34
+ * the body **cannot** be encoded and the request must therefore stay uncached.
35
+ *
36
+ * A body that reaches the key wrong is worse than no cached body at all: two different
37
+ * payloads would hash onto one entry and the first response would be replayed for the
38
+ * second. So anything whose content this function cannot actually read is refused rather
39
+ * than approximated:
40
+ *
41
+ * * a stream (`ReadableStream`, a `Request`'s body), a `Blob`/`File` or raw bytes have no
42
+ * readable own properties — `JSON.stringify` renders each as the bare `'{}'`, which would
43
+ * collapse *every* such body onto *one* key;
44
+ * * an object that serialises to `'{}'` for any other reason (a class instance keeping its
45
+ * data in private fields, an empty object) carries nothing to tell bodies apart by;
46
+ * * a circular structure throws out of `JSON.stringify`.
47
+ *
48
+ * Note the ordering rule: `JSON.stringify` walks own keys in insertion order, so two
49
+ * structurally equal bodies spelled with different key order produce different keys. That
50
+ * costs a cache miss and nothing worse — the direction of the error is "did not reuse",
51
+ * never "reused the wrong response". Canonicalising the order instead would mean building
52
+ * a sorted copy of caller data, which is exactly where `__proto__` handling goes wrong.
53
+ */
54
+ export function encodeRequestBody(body) {
55
+ if (!hasRequestBody(body))
56
+ return '';
57
+ if (typeof body === 'string')
58
+ return JSON.stringify(body);
59
+ if (typeof body === 'number' || typeof body === 'boolean' || typeof body === 'bigint') {
60
+ return String(body);
61
+ }
62
+ if (typeof body !== 'object')
63
+ return undefined; // function, symbol, ...
64
+ if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
65
+ // Order-preserving: ofetch sends `.toString()` verbatim, so two differently-ordered
66
+ // search strings are genuinely different requests on the wire.
67
+ return `URLSearchParams(${body.toString()})`;
68
+ }
69
+ if (typeof FormData !== 'undefined' && body instanceof FormData) {
70
+ // Multipart part order carries no semantics, so entries are sorted — same fields in a
71
+ // different order are the same request. Files are described by identity attributes;
72
+ // their bytes are not read (they may be huge or not yet loaded).
73
+ const parts = [];
74
+ for (const [key, item] of body.entries()) {
75
+ parts.push(typeof item === 'string'
76
+ ? `${JSON.stringify(key)}=${JSON.stringify(item)}`
77
+ : `${JSON.stringify(key)}#file(${item.name},${item.size},${item.type})`);
78
+ }
79
+ return `FormData(${parts.sort().join('&')})`;
80
+ }
81
+ // Raw bytes: refused rather than hashed, because a 32-bit digest over caller-supplied
82
+ // bytes is a collision surface this key does not need to open.
83
+ if (typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) {
84
+ return undefined;
85
+ }
86
+ let json;
87
+ try {
88
+ json = JSON.stringify(body);
89
+ }
90
+ catch {
91
+ return undefined; // circular
92
+ }
93
+ if (json === undefined)
94
+ return undefined;
95
+ if (json === '{}')
96
+ return undefined; // no enumerable content — see the doc comment above
97
+ return json;
98
+ }
99
+ /**
100
+ * Separator between the two hashed key components: a raw NUL, which `JSON.stringify` never
101
+ * emits unescaped (it writes a six-character escape instead), so no `vary` value or body
102
+ * can be crafted to straddle the boundary and impersonate the other component.
103
+ */
104
+ const COMPONENT_SEPARATOR = String.fromCharCode(0);
105
+ /**
106
+ * Default cache key: method + resolved URL, plus a hash of the `varyHeaders` values and of
107
+ * the request body.
108
+ *
109
+ * ```ts
110
+ * defaultCacheKey('GET', 'https://api.example.com/users', headers, ['authorization']);
111
+ * // "get https://api.example.com/users?a3f9k"
112
+ * ```
113
+ *
114
+ * The URL must be the *resolved* one (after `baseURL` and `query`/`params`), so one
115
+ * endpoint occupies one entry regardless of how it was spelled at the call site — and so
116
+ * two wrappers pointing at different origins can never share an entry. The adapter only
117
+ * calls this once it knows the full URL (see `isAbsoluteUrl`).
118
+ *
119
+ * The hash is appended whenever `varyHeaders` is non-empty — including when every value is
120
+ * absent — so keys stay stable across calls. Pass `varyHeaders: []` to get the bare
121
+ * `"<method> <url>"` form.
122
+ *
123
+ * A request that carries a body folds that body into the hash, so `POST /orders` with two
124
+ * different payloads occupies two entries instead of replaying one for the other.
125
+ *
126
+ * @throws when a body is present but {@link encodeRequestBody} cannot read it — callers
127
+ * that must not throw should check first and skip caching instead.
128
+ */
129
+ export function defaultCacheKey(method, url, headers, varyHeaders, body) {
130
+ const base = `${method.toLowerCase()} ${url}`;
131
+ const carriesBody = hasRequestBody(body);
132
+ const encodedBody = carriesBody ? encodeRequestBody(body) : undefined;
133
+ if (carriesBody && encodedBody === undefined) {
134
+ throw new Error('[blaze-cache] this request body cannot be encoded into a cache key');
135
+ }
136
+ if (varyHeaders.length === 0 && encodedBody === undefined)
137
+ return base;
138
+ // JSON, never a plain join: the encoding must stay *injective*, because a collision here
139
+ // would replay one identity's payload to another. Joining with a space lets a value
140
+ // containing the separator impersonate the boundary — `['x y', '']` and `['x', 'y']` are
141
+ // two different identities, and only a length-delimited encoding (JSON being the simplest)
142
+ // keeps them apart.
143
+ const vary = varyHeaders.length === 0 ? '' : JSON.stringify(varyHeaders.map((name) => headers.get(name) ?? ''));
144
+ const payload = encodedBody === undefined ? vary : `${vary}${COMPONENT_SEPARATOR}${encodedBody}`;
145
+ return `${base}?${fnv1a(payload)}`;
146
+ }
147
+ //# 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,iFAAiF;AACjF,MAAM,YAAY,GAAG,6BAA6B,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,GAAW;IACvC,OAAO,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,cAAc,CAAC,IAAa;IAC1C,OAAO,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,CAAC;AAC7C,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAa;IAC7C,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAErC,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAC1D,IAAI,OAA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AC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAErG,MAAM,OAAO,GAAG,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,mBAAmB,GAAG,WAAW,EAAE,CAAC;IACjG,OAAO,GAAG,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;AACrC,CAAC"}
@@ -0,0 +1,194 @@
1
+ import type { $Fetch, FetchOptions, FetchResponse } from 'ofetch';
2
+ /**
3
+ * Value written on the `x-blaze-cache` response header by every response the adapter
4
+ * returns (when the marker is enabled and headers are mutable).
5
+ *
6
+ * * `MISS` — the response came from the network.
7
+ * * `HIT` — served from the cache while still fresh.
8
+ *
9
+ * There is no `STALE`: this adapter never serves an entry past its freshness window —
10
+ * `Cache-Control: stale-while-revalidate` belongs to `@blaze-cache/fetch`, which has a
11
+ * stale window to serve from.
12
+ */
13
+ export type BlazeOfetchMarker = 'HIT' | 'MISS';
14
+ /**
15
+ * What the adapter stores in Blaze Cache for one response.
16
+ *
17
+ * The record is a plain, structured-clone-friendly object: an `ArrayBuffer` body plus
18
+ * primitive metadata, so it survives an IndexedDB round-trip when the cache is configured
19
+ * with persistence. The shape is intentionally compatible with the records other
20
+ * `@blaze-cache/*` adapters store (`ArrayBuffer` body, `freshUntil`, `storedAt`, `headers`)
21
+ * so a single cache instance can be shared across integrations.
22
+ */
23
+ export interface OfetchCacheRecord {
24
+ status: number;
25
+ statusText: string;
26
+ /** Response headers as a plain record, names lower-cased (as `Headers` reports them). */
27
+ headers: Record<string, string>;
28
+ /**
29
+ * Raw response body.
30
+ *
31
+ * Empty for statuses that cannot carry one (`204`, `205`, `304`) — those are replayed with
32
+ * a `null` body, exactly like the network sent them.
33
+ */
34
+ body: ArrayBuffer;
35
+ /** Final URL after redirects — replayed as [`Response.url`](https://developer.mozilla.org/en-US/docs/Web/API/Response/url). */
36
+ url: string;
37
+ /** Whether the stored response followed a redirect. */
38
+ redirected: boolean;
39
+ /** `Date.now()` when the response was received. */
40
+ storedAt: number;
41
+ /**
42
+ * `Date.now()` at which the entry stops being fresh.
43
+ *
44
+ * The read path checks this itself instead of trusting the store: {@link BlazeOfetchCacheLike}
45
+ * is deliberately structural — a plain `Map` shim qualifies — and such a store never
46
+ * expires anything, so without this deadline a record would be replayed forever.
47
+ */
48
+ freshUntil: number;
49
+ /**
50
+ * The parsed payload (`_data`) ofetch produced, stored so a cache hit can return the
51
+ * same value as a network call without re-parsing the body. Omitted for non-JSON /
52
+ * stream responses where only the raw body is meaningful.
53
+ */
54
+ _data?: unknown;
55
+ /** ofetch `responseType` used for this response, so a raw replay can honour it. */
56
+ responseType?: string;
57
+ }
58
+ /** The slice of a cache the adapter needs — deliberately structural. */
59
+ export interface BlazeOfetchCacheLike {
60
+ get(key: string): OfetchCacheRecord | undefined;
61
+ set(key: string, value: OfetchCacheRecord, options?: {
62
+ ttlMs?: number;
63
+ tags?: readonly string[];
64
+ }): void;
65
+ /**
66
+ * Optional, so a minimal `Map` shim still satisfies the interface.
67
+ *
68
+ * When present, the adapter uses it to drop a record it found past
69
+ * {@link OfetchCacheRecord.freshUntil} — without it a non-expiring store would keep dead
70
+ * weight it is never allowed to serve.
71
+ */
72
+ delete?(key: string): boolean | void;
73
+ }
74
+ /** Resolved request identity passed to {@link BlazeOfetchOptions.key}. */
75
+ export interface BlazeOfetchKeyContext {
76
+ /** Original request argument. */
77
+ request: string | Request | URL;
78
+ /** Options as resolved for this call (defaults merged). */
79
+ options: FetchOptions;
80
+ /** Upper-cased HTTP method. */
81
+ method: string;
82
+ /** Final URL after `baseURL` and `query`/`params` resolution. */
83
+ url: string;
84
+ /** Request headers (a `Headers` instance), including this instance's default headers. */
85
+ headers: Headers;
86
+ /**
87
+ * Request body, if the call carries one — `undefined`/`null` when it does not.
88
+ *
89
+ * The default key folds this into the hash so two payloads to the same URL occupy two
90
+ * entries. A body it cannot encode (a stream, a `Blob`) leaves the request uncached
91
+ * unless you supply {@link BlazeOfetchOptions.key} and describe the body yourself.
92
+ */
93
+ body?: unknown;
94
+ }
95
+ /** Options accepted by {@link blazeOfetch} and {@link createBlazeOfetch}. All optional. */
96
+ export interface BlazeOfetchOptions {
97
+ /**
98
+ * Freshness window for a stored response, in milliseconds.
99
+ *
100
+ * Ignored when the response carries `Cache-Control: max-age`, which wins. A response
101
+ * carrying `Age` has that age deducted. Default: `60_000`. A value `<= 0` means
102
+ * "do not store".
103
+ */
104
+ ttlMs?: number | ((response: FetchResponse<unknown>, request: BlazeOfetchKeyContext) => number);
105
+ /**
106
+ * HTTP methods eligible for caching. Default: `['GET']`.
107
+ *
108
+ * Pass `['GET', 'HEAD']` to cache `HEAD` too. Any other method always goes to the network
109
+ * and is never stored.
110
+ */
111
+ methods?: readonly string[];
112
+ /**
113
+ * Honour `Cache-Control` on both sides of the exchange. Default: `true`.
114
+ *
115
+ * * request `no-store` → neither read nor write the cache;
116
+ * * request `no-cache` / `max-age=0` → skip the read, still store the response;
117
+ * * response `no-store` → never stored;
118
+ * * response `no-cache` (even per-field, `no-cache="field1"`) → never stored;
119
+ * * response `max-age` → overrides {@link ttlMs}, minus the response's `Age`.
120
+ *
121
+ * Set to `false` to treat `ttlMs` as the only authority. The response's `Vary` header is
122
+ * *always* honoured (see {@link varyHeaders}) — variant correctness is not a preference.
123
+ */
124
+ cacheControl?: boolean;
125
+ /**
126
+ * Builds the cache key. Receives the resolved request identity (final URL after `baseURL`/
127
+ * `query` resolution, normalized method and merged headers).
128
+ *
129
+ * The default is `"<method> <url>"` plus a hash of {@link varyHeaders} and of the request
130
+ * body — {@link defaultCacheKey} implements that default. Replacing the key replaces
131
+ * **everything** the default included, so include the method yourself when caching more
132
+ * than one method — and the body too, if you cache a method that carries one.
133
+ */
134
+ key?: (context: BlazeOfetchKeyContext) => string;
135
+ /**
136
+ * Decide whether a response is worth storing. Default: only `2xx` responses
137
+ * (the {@link methods} gate has already applied by then).
138
+ *
139
+ * A response this rejects is still returned — it is simply not cached. A callback that
140
+ * *throws* is treated the same way (after one console warning): a cache-layer failure
141
+ * never fails a response the network answered well.
142
+ */
143
+ shouldCache?: (response: FetchResponse<unknown>, request: BlazeOfetchKeyContext) => boolean;
144
+ /**
145
+ * Tags attached to stored responses. Default: `['ofetch', '<method> <url>']`.
146
+ *
147
+ * The first tag lets one call drop the whole adapter's content
148
+ * (`cache.invalidateTags('ofetch')`); the second drops a single resource.
149
+ */
150
+ tags?: (response: FetchResponse<unknown>, request: BlazeOfetchKeyContext) => readonly string[];
151
+ /**
152
+ * Request headers whose values participate in the cache key. Default: `['authorization']`.
153
+ *
154
+ * A personalized response must never be served to a different user just because the URL
155
+ * matched. Values are hashed, never stored verbatim.
156
+ *
157
+ * A response's own `Vary` header is checked against this list before it is stored: a
158
+ * response varying on anything *not* listed cannot be keyed correctly, so it is left
159
+ * uncached — and `Vary: *` is never stored at all (RFC 9111 §3).
160
+ */
161
+ varyHeaders?: readonly string[];
162
+ /**
163
+ * Response header set to `HIT` / `MISS` on replayed and rebuilt responses. Default:
164
+ * `'x-blaze-cache'`. Pass `false` to disable the marker entirely.
165
+ *
166
+ * The marker is stamped on the `Response` headers (visible via `$fetch.raw()` and on the
167
+ * underlying `FetchResponse`). The parsed value returned by `$fetch()` is unchanged.
168
+ */
169
+ markerHeader?: string | false;
170
+ /**
171
+ * `baseURL` for cache-key resolution when wrapping a pre-configured ofetch instance.
172
+ *
173
+ * ofetch keeps an instance's `defaults` in a closure it does not expose, so a wrapper
174
+ * cannot read them. Passing it here makes the key describe the same URL the request will
175
+ * actually go to — and the value is forced onto the request as well, so key and wire can
176
+ * never disagree. {@link createBlazeOfetch} forwards its `baseURL` automatically.
177
+ *
178
+ * When it is *not* passed and the instance has its own `baseURL`, the adapter recovers
179
+ * the origin from the first response's `Response.url` and keys from then on. Until that
180
+ * happens the request URL is still relative, so nothing is read or written — a relative
181
+ * URL is exactly what two different origins have in common.
182
+ */
183
+ baseURL?: string;
184
+ }
185
+ /**
186
+ * {@link blazeOfetch}'s cache options plus every ofetch option, for {@link createBlazeOfetch}
187
+ * — one bag for both layers: `{baseURL, ttlMs, tags, ...}`. ofetch's own options keep their
188
+ * meaning and become the instance defaults.
189
+ */
190
+ export interface CreateBlazeOfetchOptions extends FetchOptions, BlazeOfetchOptions {
191
+ }
192
+ /** The wrapped ofetch instance returned by {@link blazeOfetch} / {@link createBlazeOfetch}. */
193
+ export type BlazeOfetchInstance = $Fetch;
194
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAElE;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,MAAM,CAAC;AAE/C;;;;;;;;GAQG;AACH,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,yFAAyF;IACzF,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC;;;;;OAKG;IACH,IAAI,EAAE,WAAW,CAAC;IAClB,+HAA+H;IAC/H,GAAG,EAAE,MAAM,CAAC;IACZ,uDAAuD;IACvD,UAAU,EAAE,OAAO,CAAC;IACpB,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;;OAMG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,mFAAmF;IACnF,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,wEAAwE;AACxE,MAAM,WAAW,oBAAoB;IACnC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAAC;IAChD,GA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a,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,qBAAqB,KAAK,SAAS,MAAM,EAAE,CAAC;IAE/F;;;;;;;;;OASG;IACH,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAEhC;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAE9B;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,MAAM,WAAW,wBAAyB,SAAQ,YAAY,EAAE,kBAAkB;CAAG;AAErF,+FAA+F;AAC/F,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC"}
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":""}
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@blaze-cache/ofetch",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.4.0-beta.1",
4
+ "description": "Cache ofetch ($fetch) responses via a WebAssembly cache — TTLs, tags, Cache-Control support and an x-blaze-cache HIT/MISS marker",
5
+ "keywords": [
6
+ "ofetch",
7
+ "$fetch",
8
+ "fetch",
9
+ "http",
10
+ "request",
11
+ "cache",
12
+ "caching",
13
+ "hooks",
14
+ "cache-control",
15
+ "webassembly",
16
+ "wasm",
17
+ "ttl"
18
+ ],
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/blaze-cache/blaze-cache.git",
23
+ "directory": "packages/ofetch"
24
+ },
25
+ "homepage": "https://blaze-cache.github.io/docs/",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "sideEffects": false,
30
+ "type": "module",
31
+ "main": "dist/index.js",
32
+ "types": "dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "dependencies": {
43
+ "ufo": "^1.5.0",
44
+ "@blaze-cache/core": "0.4.0-beta.1"
45
+ },
46
+ "peerDependencies": {
47
+ "ofetch": "^1.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "ofetch": "^1.5.1",
51
+ "typescript": "^5.9.3"
52
+ },
53
+ "scripts": {
54
+ "build": "tsc -p tsconfig.json",
55
+ "test": "pnpm run build && node --test",
56
+ "typecheck": "tsc -p tsconfig.typecheck.json",
57
+ "test:live": "pnpm run build && BLAZE_CACHE_LIVE=1 node --test test/live.test.mjs"
58
+ }
6
59
  }