@npora/request 1.17.4 → 1.18.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.
Files changed (88) hide show
  1. package/README.md +88 -86
  2. package/dist/{MockAdapter-5CFrxv9q.d.ts → MockAdapter--6ZwMMQ8.d.ts} +2 -2
  3. package/dist/{MockAdapter-mR3CWESj.d.cts → MockAdapter-BrXOqgTA.d.cts} +2 -2
  4. package/dist/{Plugin-C9ZQzyF6.d.ts → Plugin-C5P_tBXo.d.ts} +1 -1
  5. package/dist/{Plugin-Cxb-obdZ.d.cts → Plugin-DYSeSZ6O.d.cts} +1 -1
  6. package/dist/{SchemaValidationError-Bls3Uxwj.d.cts → SchemaValidationError-BANH6INo.d.cts} +3 -3
  7. package/dist/{SchemaValidationError-DRSiM7h7.d.ts → SchemaValidationError-ljhan6YH.d.ts} +3 -3
  8. package/dist/{adapter-YnK7Xzw4.d.ts → adapter-CBaLHCEm.d.ts} +1 -1
  9. package/dist/{adapter-Bshqh0DY.d.cts → adapter-DlZ5Qbou.d.cts} +1 -1
  10. package/dist/{authPlugin-BXi6WjtM.d.cts → authPlugin-DpE4afbz.d.cts} +1 -1
  11. package/dist/{authPlugin-DdzlLQVo.d.ts → authPlugin-USKx_XNX.d.ts} +1 -1
  12. package/dist/{cachePlugin-Bk7V57oZ.d.cts → cachePlugin-BMcLP92z.d.cts} +82 -80
  13. package/dist/cachePlugin-ComdU-Tb.cjs +1 -0
  14. package/dist/{cachePlugin-BZ0lLFOx.d.ts → cachePlugin-D5iyPREK.d.ts} +82 -80
  15. package/dist/cachePlugin-kcIdZe02.js +1 -0
  16. package/dist/{circuitBreakerPlugin-CX7s4iAe.d.ts → circuitBreakerPlugin-D12NHWon.d.ts} +2 -2
  17. package/dist/{circuitBreakerPlugin-BG2PlHSo.d.cts → circuitBreakerPlugin-tbwS-j5u.d.cts} +2 -2
  18. package/dist/{concurrencyPlugin-DeDnm7ND.d.cts → concurrencyPlugin-Dvsgel94.d.cts} +2 -2
  19. package/dist/{concurrencyPlugin-HvGuOA2p.d.ts → concurrencyPlugin-W84oJyJP.d.ts} +2 -2
  20. package/dist/core.cjs +1 -1
  21. package/dist/core.d.cts +5 -5
  22. package/dist/core.d.ts +5 -5
  23. package/dist/core.js +1 -1
  24. package/dist/createClient-BJInwX7D.js +1 -0
  25. package/dist/createClient-ICkQQqcE.cjs +1 -0
  26. package/dist/{downloadPlugin-BlA-z0Pj.d.cts → downloadPlugin-DJDuMLwT.d.cts} +1 -1
  27. package/dist/{downloadPlugin-BrXcygGo.d.ts → downloadPlugin-DjCZgsVL.d.ts} +1 -1
  28. package/dist/index.cjs +1 -1
  29. package/dist/index.d.cts +17 -17
  30. package/dist/index.d.ts +17 -17
  31. package/dist/index.js +1 -1
  32. package/dist/loggerPlugin-DFIXW1B1.d.ts +6 -0
  33. package/dist/loggerPlugin-DZlxRUT0.d.cts +6 -0
  34. package/dist/{openTelemetryMetricsPlugin-fQOtuYJX.d.ts → openTelemetryMetricsPlugin-0UQ5jqvv.d.ts} +2 -2
  35. package/dist/{openTelemetryMetricsPlugin-D6y3KC4M.d.cts → openTelemetryMetricsPlugin-BqUiYPda.d.cts} +2 -2
  36. package/dist/{openTelemetryPlugin-FAngP8jc.d.cts → openTelemetryPlugin-Cuap7zKx.d.cts} +2 -2
  37. package/dist/{openTelemetryPlugin-CiRMppHI.d.ts → openTelemetryPlugin-w3t3yoCr.d.ts} +2 -2
  38. package/dist/plugins/auth.d.cts +1 -1
  39. package/dist/plugins/auth.d.ts +1 -1
  40. package/dist/plugins/cache.cjs +1 -1
  41. package/dist/plugins/cache.d.cts +2 -2
  42. package/dist/plugins/cache.d.ts +2 -2
  43. package/dist/plugins/cache.js +1 -1
  44. package/dist/plugins/circuit-breaker.d.cts +1 -1
  45. package/dist/plugins/circuit-breaker.d.ts +1 -1
  46. package/dist/plugins/concurrency.d.cts +1 -1
  47. package/dist/plugins/concurrency.d.ts +1 -1
  48. package/dist/plugins/download.d.cts +1 -1
  49. package/dist/plugins/download.d.ts +1 -1
  50. package/dist/plugins/logger.d.cts +1 -1
  51. package/dist/plugins/logger.d.ts +1 -1
  52. package/dist/plugins/memory-cache.cjs +1 -0
  53. package/dist/plugins/memory-cache.d.cts +19 -0
  54. package/dist/plugins/memory-cache.d.ts +19 -0
  55. package/dist/plugins/memory-cache.js +1 -0
  56. package/dist/plugins/opentelemetry-metrics.d.cts +1 -1
  57. package/dist/plugins/opentelemetry-metrics.d.ts +1 -1
  58. package/dist/plugins/opentelemetry.d.cts +1 -1
  59. package/dist/plugins/opentelemetry.d.ts +1 -1
  60. package/dist/plugins/rate-limit.d.cts +1 -1
  61. package/dist/plugins/rate-limit.d.ts +1 -1
  62. package/dist/plugins/retry.d.cts +1 -1
  63. package/dist/plugins/retry.d.ts +1 -1
  64. package/dist/plugins/upload.d.cts +1 -1
  65. package/dist/plugins/upload.d.ts +1 -1
  66. package/dist/plugins.cjs +1 -1
  67. package/dist/plugins.d.cts +13 -13
  68. package/dist/plugins.d.ts +13 -13
  69. package/dist/plugins.js +1 -1
  70. package/dist/{rateLimitPlugin-1rbZeJmP.d.cts → rateLimitPlugin-KOSUTbvE.d.cts} +2 -2
  71. package/dist/{rateLimitPlugin-D5t-8kzP.d.ts → rateLimitPlugin-cU0qI8TH.d.ts} +2 -2
  72. package/dist/{response-B6Z3qxyO.d.cts → response-BmBc0r8_.d.cts} +8 -1
  73. package/dist/{response-B6Z3qxyO.d.ts → response-BmBc0r8_.d.ts} +8 -1
  74. package/dist/retryPlugin-Df4T3WEv.d.ts +6 -0
  75. package/dist/retryPlugin-Ir1VPUHq.d.cts +6 -0
  76. package/dist/testing.d.cts +1 -1
  77. package/dist/testing.d.ts +1 -1
  78. package/dist/{uploadPlugin-BrzbWtAN.d.ts → uploadPlugin-C8CgYCKh.d.ts} +1 -1
  79. package/dist/{uploadPlugin-Ci0ys-ng.d.cts → uploadPlugin-CAHUGiz4.d.cts} +1 -1
  80. package/package.json +11 -2
  81. package/dist/cachePlugin-B-5paXgx.cjs +0 -1
  82. package/dist/cachePlugin-CV1r0vZB.js +0 -1
  83. package/dist/createClient-Bl9NkFlS.cjs +0 -1
  84. package/dist/createClient-DoNjfuKQ.js +0 -1
  85. package/dist/loggerPlugin-CBbwGZme.d.ts +0 -6
  86. package/dist/loggerPlugin-CZpdXtBt.d.cts +0 -6
  87. package/dist/retryPlugin-C0dORYIQ.d.cts +0 -6
  88. package/dist/retryPlugin-CVelhp0f.d.ts +0 -6
package/README.md CHANGED
@@ -7,78 +7,22 @@
7
7
  [![license](https://img.shields.io/npm/l/@npora/request.svg)](LICENSE)
8
8
 
9
9
  A production-focused, TypeScript-first HTTP client built on the standard Fetch
10
- API, with zero runtime dependencies.
11
-
12
- Npora Request keeps the native Fetch model while adding the contracts and
13
- resilience needed by real applications: inferred response types, runtime
14
- validation, incremental streaming, stable errors, deterministic extension
15
- ordering, retries, caching, concurrency control, circuit breaking,
16
- authentication, and upload/download progress.
17
-
18
- ## Why Npora Request
19
-
20
- - **Trust responses at runtime.** Standard Schema v1 validation checks and can
21
- transform untrusted data while preserving full response and error metadata.
22
- - **Stream without buffering everything.** File downloads, SSE, and NDJSON can
23
- be consumed lazily with backpressure, cancellation, timeout, progress, and
24
- response-size enforcement.
25
- - **Add resilience without hiding the transport.** Retry, cache, circuit
26
- breaker, concurrency, authentication, logging, and progress are isolated,
27
- composable plugins over the standard Fetch API.
28
- - **Use one predictable contract everywhere.** Browsers, Web Workers, Node.js,
29
- ESM, and CommonJS share the same typed lifecycle and stable error codes.
30
- - **Keep native platform values native.** `URL`, `Request`, `Headers`,
31
- `FormData`, `Blob`, `ArrayBuffer`, and `ReadableStream` retain their Fetch
32
- semantics, including supported cross-realm inputs.
33
- - **Bound untrusted traffic.** Separate request, successful response, and error
34
- response limits prevent accidental buffering while preserving meaningful
35
- error codes and cancellation.
36
- - **Ship less supply-chain risk.** The package has no runtime dependencies and
37
- verifies public exports, browser behavior, security regressions, and size
38
- budgets before release.
39
-
40
- ## Design focus
41
-
42
- Npora Request combines runtime validation, incremental streaming, persistent
43
- cache correctness, resilience, observability, and cancellation under one
44
- typed, deterministic lifecycle. It keeps the standard Fetch model, ships with
45
- zero runtime dependencies, supports ESM and CommonJS, and exposes optional
46
- capabilities through tree-shakeable subpath exports.
47
-
48
- The current stress gate completed **10,000,000 logical operations at concurrency
49
- 256 with zero unexpected failures**, followed by **100,000 real localhost HTTP
50
- requests at concurrency 256**. These are reproducible engineering checks, not
51
- claims about every remote workload; commands and limitations are in the
52
- [benchmark documentation](docs/benchmark.md).
53
-
54
- ## Features
55
-
56
- - Data-first and complete-response APIs with TypeScript inference.
57
- - Native `URL` and `Request` inputs with explicit per-call overrides and stable
58
- lifecycle snapshots.
59
- - First-class RFC 10008 `QUERY` helpers with JSON bodies and safe retries for
60
- replayable content.
61
- - Query- and fragment-safe `baseURL` prefix composition.
62
- - Object query merging plus native ordered `URLSearchParams` through
63
- `searchParams`.
64
- - Native multipart and URL-encoded response parsing through `formData`.
65
- - Raw binary response parsing as a portable `Uint8Array` through `bytes`.
66
- - Response-type-driven `Accept` negotiation with custom-header precedence.
67
- - Standards-correct opaque and manual-redirect Fetch responses without false
68
- HTTP or parser failures.
69
- - Optional non-throwing HTTP status handling with parsed response data and
70
- complete metadata.
71
- - Standard Schema v1 validation and transformation for untrusted responses.
72
- - Incremental SSE and NDJSON async iterables with cancellation and size limits.
73
- - Progress-aware file download streams that preserve backpressure and avoid
74
- buffering the complete response in memory.
75
- - Unified errors across Fetch, XHR, parsing, validation, timeouts, and aborts.
76
- - Request/response/error interceptors with deterministic priority ordering.
77
- - Shallow-merged local request context for tracing and lifecycle policies.
78
- - Official retry, cache, circuit-breaker, concurrency, authentication, logger,
79
- upload, and download plugins.
80
- - Method-aware `MockAdapter` routing, matching, delays, failures, and history.
81
- - Browser, Web Worker, ESM, and CommonJS support with zero runtime dependencies.
10
+ API. It adds typed responses, runtime validation, streaming, stable errors, and
11
+ composable resilience while keeping native platform values visible. The package
12
+ has zero runtime dependencies.
13
+
14
+ ## Start here
15
+
16
+ | Goal | Documentation |
17
+ | --- | --- |
18
+ | Send the first request | [Quick start](#quick-start) |
19
+ | Build a client for an application | [Common workflows](docs/workflows.md) |
20
+ | Find a client or response API | [API reference](docs/api.md) |
21
+ | Configure URLs, bodies, timeouts, or parsing | [Configuration reference](docs/configuration.md) |
22
+ | Add retry, cache, authentication, or observability | [Plugins](#plugins) |
23
+ | Handle stable error codes | [Errors](#errors) |
24
+ | Configure Node.js proxying, pooling, mTLS, or DNS | [Undici integration](docs/undici.md) |
25
+ | Review runtime boundaries and release checks | [Testing](docs/testing.md) and [security](docs/security.md) |
82
26
 
83
27
  ## Install
84
28
 
@@ -94,18 +38,6 @@ Node.js 22 or newer is required. Modern Chromium-based browsers, Firefox,
94
38
  Safari/WebKit, and Web Workers are supported through their native Fetch
95
39
  implementations.
96
40
 
97
- ## Version support
98
-
99
- | Version | Status | Guidance |
100
- | --- | --- | --- |
101
- | `latest` | Current | Recommended for all new and existing applications. |
102
- | Earlier releases `>=1.0.0` | Historical stable | Upgrade to `latest` for current fixes and security hardening. |
103
- | `<1.0.0` | Deprecated and unsupported | Upgrade immediately; 0.x receives no fixes or security updates. |
104
-
105
- All published releases before `1.0.0` are deprecated by project policy. Do not
106
- use a 0.x release in production, documentation examples, dependency templates,
107
- or new lockfiles.
108
-
109
41
  ## Quick start
110
42
 
111
43
  ```ts
@@ -127,8 +59,34 @@ const api = createClient({
127
59
  const user = await api.get<User>('/users/1')
128
60
  ```
129
61
 
130
- Data-first methods return the parsed response body. Use a response method when
131
- status, headers, or the native `Response` is needed:
62
+ Data-first methods return the parsed response body. The `User` generic gives
63
+ TypeScript a type; it does **not** check the server response at runtime. For
64
+ untrusted data, pass a [Standard Schema](#response-validation) validator:
65
+
66
+ ```ts
67
+ import { z } from 'zod'
68
+
69
+ const userSchema = z.object({
70
+ id: z.number(),
71
+ name: z.string()
72
+ })
73
+
74
+ const validatedUser = await api.get('/users/1', {
75
+ schema: userSchema
76
+ }) // inferred from the schema and checked at runtime
77
+ ```
78
+
79
+ Request JSON with the dedicated `json` option:
80
+
81
+ ```ts
82
+ const created = await api.post<User>('/users', {
83
+ json: {
84
+ name: 'Ada'
85
+ }
86
+ })
87
+ ```
88
+
89
+ Use a response method when status, headers, or the native `Response` is needed:
132
90
 
133
91
  ```ts
134
92
  const response = await api.getResponse<User>('/users/1')
@@ -139,6 +97,36 @@ console.log(response.headers)
139
97
  console.log(response.raw)
140
98
  ```
141
99
 
100
+ ## Why Npora Request
101
+
102
+ - **Runtime-safe responses.** Standard Schema v1 validates and transforms
103
+ untrusted data while preserving response and error metadata.
104
+ - **Incremental streaming.** File downloads, SSE, and NDJSON preserve
105
+ backpressure, cancellation, timeouts, progress, and response-size limits.
106
+ - **Composable resilience.** Retry, cache, circuit breaker, concurrency,
107
+ rate limiting, authentication, logging, and observability are isolated
108
+ plugins over the standard Fetch lifecycle.
109
+ - **Native platform contracts.** `URL`, `Request`, `Headers`, `FormData`,
110
+ `Blob`, `ArrayBuffer`, and `ReadableStream` retain their Fetch semantics.
111
+ - **Bounded traffic and stable failures.** Separate request, successful
112
+ response, and error response limits use typed errors with documented codes.
113
+ - **Portable, verifiable delivery.** Browser, Web Worker, Node.js, ESM, and
114
+ CommonJS behavior is checked alongside public exports, security regressions,
115
+ and package-size budgets.
116
+
117
+ ## Version support
118
+
119
+ | Version | Status | Guidance |
120
+ | --- | --- | --- |
121
+ | `latest` | Current stable 1.x | Recommended for new and existing applications. |
122
+ | Earlier releases `>=1.0.0` | Historical | Upgrade to `latest` for current fixes and security hardening. |
123
+ | `<1.0.0` | Unsupported | Upgrade immediately; 0.x receives no fixes or security updates. |
124
+
125
+ The current 1.x line is in active maintenance. Backward-compatible fixes ship
126
+ as patch releases; new public capabilities require a minor release, and
127
+ breaking public API changes require a new major version. All published releases
128
+ before `1.0.0` are deprecated.
129
+
142
130
  ## Native Fetch inputs
143
131
 
144
132
  Use a native `Request` directly when another platform layer already owns the
@@ -341,6 +329,19 @@ import { retryPlugin } from '@npora/request/plugins/retry'
341
329
  const request = createClient().use(retryPlugin({ retries: 2 }))
342
330
  ```
343
331
 
332
+ Retry is opt-in: installing `retryPlugin()` without a `retries` value leaves
333
+ the default at zero. Cache is also opt-in per request, or through a client
334
+ default under `extensions.cache`. See the
335
+ [configuration reference](docs/configuration.md#extension-options) for the
336
+ precise defaults and method rules.
337
+
338
+ For a smaller memory-only cache, import `memoryCachePlugin` from
339
+ `@npora/request/plugins/memory-cache` and enable `extensions.memoryCache`.
340
+ It stores successful `GET` and `HEAD` responses with a TTL and bounded LRU
341
+ capacity. Set `fetchOptions.credentials: 'omit'` for requests without implicit
342
+ credentials; requests with credentials need an explicit, correctly scoped
343
+ `memoryCache.key`. See the [runnable example](examples/memory-cache.ts).
344
+
344
345
  `MockAdapter` is also available from `@npora/request/testing` and
345
346
  `@npora/request/adapters/mock` so test-only utilities do not need to be
346
347
  imported through the production entry point.
@@ -812,6 +813,7 @@ allowlist, and size budgets.
812
813
  - [API reference](https://github.com/npora/request/blob/main/docs/api.md)
813
814
  - [Architecture](https://github.com/npora/request/blob/main/docs/architecture.md)
814
815
  - [Migration from 0.x](https://github.com/npora/request/blob/main/docs/migration.md)
816
+ - [Common workflows](https://github.com/npora/request/blob/main/docs/workflows.md)
815
817
  - [Security model](https://github.com/npora/request/blob/main/docs/security.md)
816
818
  - [Testing and release gates](https://github.com/npora/request/blob/main/docs/testing.md)
817
819
  - [Performance benchmarks](https://github.com/npora/request/blob/main/docs/benchmark.md)
@@ -1,5 +1,5 @@
1
- import { U as HttpMethod, f as RequestConfig, l as QueryParams, t as NporaResponse } from "./response-B6Z3qxyO.js";
2
- import { t as Adapter } from "./adapter-YnK7Xzw4.js";
1
+ import { W as HttpMethod, f as RequestConfig, l as QueryParams, t as NporaResponse } from "./response-BmBc0r8_.js";
2
+ import { t as Adapter } from "./adapter-CBaLHCEm.js";
3
3
  //#region src/adapters/MockAdapter.d.ts
4
4
  type MockHandler<T = unknown> = (config: RequestConfig) => T | Promise<T>;
5
5
  type MockURLMatcher = string | RegExp;
@@ -1,5 +1,5 @@
1
- import { U as HttpMethod, f as RequestConfig, l as QueryParams, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
2
- import { t as Adapter } from "./adapter-Bshqh0DY.cjs";
1
+ import { W as HttpMethod, f as RequestConfig, l as QueryParams, t as NporaResponse } from "./response-BmBc0r8_.cjs";
2
+ import { t as Adapter } from "./adapter-DlZ5Qbou.cjs";
3
3
  //#region src/adapters/MockAdapter.d.ts
4
4
  type MockHandler<T = unknown> = (config: RequestConfig) => T | Promise<T>;
5
5
  type MockURLMatcher = string | RegExp;
@@ -1,4 +1,4 @@
1
- import { f as RequestConfig, t as NporaResponse } from "./response-B6Z3qxyO.js";
1
+ import { f as RequestConfig, t as NporaResponse } from "./response-BmBc0r8_.js";
2
2
  //#region src/interceptors/InterceptorManager.d.ts
3
3
  type Interceptor<T> = (value: T) => T | Promise<T>;
4
4
  interface InterceptorOptions {
@@ -1,4 +1,4 @@
1
- import { f as RequestConfig, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
1
+ import { f as RequestConfig, t as NporaResponse } from "./response-BmBc0r8_.cjs";
2
2
  //#region src/interceptors/InterceptorManager.d.ts
3
3
  type Interceptor<T> = (value: T) => T | Promise<T>;
4
4
  interface InterceptorOptions {
@@ -1,6 +1,6 @@
1
- import { H as StandardSchemaV1, f as RequestConfig, h as RequestURL, m as RequestInputConfig, n as ServerSentEvent, r as StreamingSchemaLocation, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
2
- import { t as Adapter } from "./adapter-Bshqh0DY.cjs";
3
- import { s as InterceptorManager, t as Plugin } from "./Plugin-Cxb-obdZ.cjs";
1
+ import { U as StandardSchemaV1, f as RequestConfig, h as RequestURL, m as RequestInputConfig, n as ServerSentEvent, r as StreamingSchemaLocation, t as NporaResponse } from "./response-BmBc0r8_.cjs";
2
+ import { t as Adapter } from "./adapter-DlZ5Qbou.cjs";
3
+ import { s as InterceptorManager, t as Plugin } from "./Plugin-DYSeSZ6O.cjs";
4
4
  //#region src/types/client.d.ts
5
5
  /**
6
6
  * Client creation options.
@@ -1,6 +1,6 @@
1
- import { H as StandardSchemaV1, f as RequestConfig, h as RequestURL, m as RequestInputConfig, n as ServerSentEvent, r as StreamingSchemaLocation, t as NporaResponse } from "./response-B6Z3qxyO.js";
2
- import { t as Adapter } from "./adapter-YnK7Xzw4.js";
3
- import { s as InterceptorManager, t as Plugin } from "./Plugin-C9ZQzyF6.js";
1
+ import { U as StandardSchemaV1, f as RequestConfig, h as RequestURL, m as RequestInputConfig, n as ServerSentEvent, r as StreamingSchemaLocation, t as NporaResponse } from "./response-BmBc0r8_.js";
2
+ import { t as Adapter } from "./adapter-CBaLHCEm.js";
3
+ import { s as InterceptorManager, t as Plugin } from "./Plugin-C5P_tBXo.js";
4
4
  //#region src/types/client.d.ts
5
5
  /**
6
6
  * Client creation options.
@@ -1,4 +1,4 @@
1
- import { f as RequestConfig, t as NporaResponse } from "./response-B6Z3qxyO.js";
1
+ import { f as RequestConfig, t as NporaResponse } from "./response-BmBc0r8_.js";
2
2
  //#region src/types/adapter.d.ts
3
3
  /**
4
4
  * Request adapter.
@@ -1,4 +1,4 @@
1
- import { f as RequestConfig, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
1
+ import { f as RequestConfig, t as NporaResponse } from "./response-BmBc0r8_.cjs";
2
2
  //#region src/types/adapter.d.ts
3
3
  /**
4
4
  * Request adapter.
@@ -1,4 +1,4 @@
1
- import { t as Plugin } from "./Plugin-Cxb-obdZ.cjs";
1
+ import { t as Plugin } from "./Plugin-DYSeSZ6O.cjs";
2
2
  //#region src/plugins/authPlugin.d.ts
3
3
  type MaybePromise<T> = T | Promise<T>;
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as Plugin } from "./Plugin-C9ZQzyF6.js";
1
+ import { t as Plugin } from "./Plugin-C5P_tBXo.js";
2
2
  //#region src/plugins/authPlugin.d.ts
3
3
  type MaybePromise<T> = T | Promise<T>;
4
4
  /**
@@ -1,5 +1,73 @@
1
- import { U as HttpMethod, f as RequestConfig } from "./response-B6Z3qxyO.cjs";
2
- import { t as Plugin } from "./Plugin-Cxb-obdZ.cjs";
1
+ import { W as HttpMethod, f as RequestConfig } from "./response-BmBc0r8_.cjs";
2
+ import { t as Plugin } from "./Plugin-DYSeSZ6O.cjs";
3
+ //#region src/plugins/cacheStores.d.ts
4
+ type MaybePromise$1<T> = T | Promise<T>;
5
+ interface CacheEntry {
6
+ data: unknown;
7
+ expiresAt: number;
8
+ status: number;
9
+ statusText: string;
10
+ headers: Array<[string, string]>;
11
+ tags?: readonly string[];
12
+ raw?: Response;
13
+ }
14
+ interface CacheStore {
15
+ get(key: string): MaybePromise$1<CacheEntry | undefined>;
16
+ set(key: string, entry: CacheEntry): MaybePromise$1<void>;
17
+ delete(key: string): MaybePromise$1<void>;
18
+ /** Optional capability required by cache.invalidateTags(). */
19
+ invalidateTags?(tags: readonly string[]): MaybePromise$1<number>;
20
+ /** Optional cross-context lease used to coalesce cache refreshes. */
21
+ acquireRefreshLease?(key: string, signal?: AbortSignal): Promise<CacheRefreshLease>;
22
+ clear(): MaybePromise$1<void>;
23
+ }
24
+ interface CacheRefreshLease {
25
+ /** Whether this lease waited for another context to release the key. */
26
+ readonly contended: boolean;
27
+ /** Release the lease. Calling this more than once has no effect. */
28
+ release(): void;
29
+ }
30
+ interface MemoryCacheStoreOptions {
31
+ /**
32
+ * Maximum entries retained by the in-memory LRU store.
33
+ * Use `Infinity` for no practical limit.
34
+ *
35
+ * @default 1000
36
+ */
37
+ maxEntries?: number;
38
+ }
39
+ declare class MemoryCacheStore implements CacheStore {
40
+ private readonly entries;
41
+ private readonly maxEntries;
42
+ private newestKey;
43
+ constructor(options?: MemoryCacheStoreOptions);
44
+ get(key: string): CacheEntry | undefined;
45
+ set(key: string, entry: CacheEntry): void;
46
+ delete(key: string): void;
47
+ invalidateTags(tags: readonly string[]): number;
48
+ clear(): void;
49
+ }
50
+ interface WebStorageCacheStoreOptions {
51
+ /** Isolates this cache from other applications using the same storage. */
52
+ namespace?: string;
53
+ /** Maximum persisted entries retained with LRU eviction. @default 1000 */
54
+ maxEntries?: number;
55
+ }
56
+ /** A namespaced persistent cache for localStorage or sessionStorage. */
57
+ declare class WebStorageCacheStore implements CacheStore {
58
+ private readonly storage;
59
+ private readonly prefix;
60
+ private readonly maxEntries;
61
+ constructor(storage: Storage, options?: WebStorageCacheStoreOptions);
62
+ get(key: string): CacheEntry | undefined;
63
+ set(key: string, entry: CacheEntry): void;
64
+ delete(key: string): void;
65
+ invalidateTags(tags: readonly string[]): number;
66
+ clear(): void;
67
+ private keys;
68
+ private read;
69
+ }
70
+ //#endregion
3
71
  //#region src/plugins/indexedDBCacheStore.d.ts
4
72
  interface IndexedDBCacheStoreOptions {
5
73
  /** Database shared by cache namespaces. @default @npora/request-cache */
@@ -83,7 +151,7 @@ declare class IndexedDBCacheStore implements CacheStore {
83
151
  }
84
152
  //#endregion
85
153
  //#region src/plugins/tieredCacheStore.d.ts
86
- type MaybePromise$1<T> = T | Promise<T>;
154
+ type MaybePromise<T> = T | Promise<T>;
87
155
  interface TieredCacheStoreOptions {
88
156
  /** Fast first-level store, usually MemoryCacheStore. */
89
157
  primary: CacheStore;
@@ -120,11 +188,11 @@ declare class TieredCacheStore implements CacheStore {
120
188
  private readonly maxTrackedKeys;
121
189
  private trackedKeyCount;
122
190
  constructor(options: TieredCacheStoreOptions);
123
- get(key: string): MaybePromise$1<CacheEntry | undefined>;
124
- set(key: string, entry: CacheEntry): MaybePromise$1<void>;
125
- delete(key: string): MaybePromise$1<void>;
126
- invalidateTags(tags: readonly string[]): MaybePromise$1<number>;
127
- clear(): MaybePromise$1<void>;
191
+ get(key: string): MaybePromise<CacheEntry | undefined>;
192
+ set(key: string, entry: CacheEntry): MaybePromise<void>;
193
+ delete(key: string): MaybePromise<void>;
194
+ invalidateTags(tags: readonly string[]): MaybePromise<number>;
195
+ clear(): MaybePromise<void>;
128
196
  private acquireCoordinatedLease;
129
197
  /** Stop listening for cross-context invalidation messages. */
130
198
  dispose(): void;
@@ -144,72 +212,6 @@ declare class TieredCacheStore implements CacheStore {
144
212
  }
145
213
  //#endregion
146
214
  //#region src/plugins/cachePlugin.d.ts
147
- type MaybePromise<T> = T | Promise<T>;
148
- interface CacheEntry {
149
- data: unknown;
150
- expiresAt: number;
151
- status: number;
152
- statusText: string;
153
- headers: Array<[string, string]>;
154
- tags?: readonly string[];
155
- raw?: Response;
156
- }
157
- interface CacheStore {
158
- get(key: string): MaybePromise<CacheEntry | undefined>;
159
- set(key: string, entry: CacheEntry): MaybePromise<void>;
160
- delete(key: string): MaybePromise<void>;
161
- /** Optional capability required by cache.invalidateTags(). */
162
- invalidateTags?(tags: readonly string[]): MaybePromise<number>;
163
- /** Optional cross-context lease used to coalesce cache refreshes. */
164
- acquireRefreshLease?(key: string, signal?: AbortSignal): Promise<CacheRefreshLease>;
165
- clear(): MaybePromise<void>;
166
- }
167
- interface CacheRefreshLease {
168
- /** Whether this lease waited for another context to release the key. */
169
- readonly contended: boolean;
170
- /** Release the lease. Calling this more than once has no effect. */
171
- release(): void;
172
- }
173
- interface MemoryCacheStoreOptions {
174
- /**
175
- * Maximum entries retained by the in-memory LRU store.
176
- * Use `Infinity` for no practical limit.
177
- *
178
- * @default 1000
179
- */
180
- maxEntries?: number;
181
- }
182
- declare class MemoryCacheStore implements CacheStore {
183
- private readonly entries;
184
- private readonly maxEntries;
185
- private newestKey;
186
- constructor(options?: MemoryCacheStoreOptions);
187
- get(key: string): CacheEntry | undefined;
188
- set(key: string, entry: CacheEntry): void;
189
- delete(key: string): void;
190
- invalidateTags(tags: readonly string[]): number;
191
- clear(): void;
192
- }
193
- interface WebStorageCacheStoreOptions {
194
- /** Isolates this cache from other applications using the same storage. */
195
- namespace?: string;
196
- /** Maximum persisted entries retained with LRU eviction. @default 1000 */
197
- maxEntries?: number;
198
- }
199
- /** A namespaced persistent cache for localStorage or sessionStorage. */
200
- declare class WebStorageCacheStore implements CacheStore {
201
- private readonly storage;
202
- private readonly prefix;
203
- private readonly maxEntries;
204
- constructor(storage: Storage, options?: WebStorageCacheStoreOptions);
205
- get(key: string): CacheEntry | undefined;
206
- set(key: string, entry: CacheEntry): void;
207
- delete(key: string): void;
208
- invalidateTags(tags: readonly string[]): number;
209
- clear(): void;
210
- private keys;
211
- private read;
212
- }
213
215
  interface CachePluginOptions {
214
216
  /**
215
217
  * HTTP methods that may be cached.
@@ -250,15 +252,15 @@ interface CachePluginOptions {
250
252
  onEvent?: (event: CacheEvent) => void | Promise<void>;
251
253
  }
252
254
  interface CachePlugin extends Plugin {
253
- clear(): MaybePromise<void>;
255
+ clear(): MaybePromise$1<void>;
254
256
  /** Delete the entry matching an effective request configuration. */
255
- delete(config: RequestConfig): MaybePromise<void>;
257
+ delete(config: RequestConfig): MaybePromise$1<void>;
256
258
  /** Store parsed response data for an effective request configuration. */
257
- set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise<void>;
259
+ set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise$1<void>;
258
260
  /** Update or delete an existing parsed cache value. */
259
- update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise<boolean>;
261
+ update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise$1<boolean>;
260
262
  /** Delete entries carrying any of the supplied tags. */
261
- invalidateTags(tags: string | readonly string[]): MaybePromise<number>;
263
+ invalidateTags(tags: string | readonly string[]): MaybePromise$1<number>;
262
264
  getStats(): Readonly<CacheStats>;
263
265
  resetStats(): void;
264
266
  }
@@ -294,4 +296,4 @@ interface CacheStats {
294
296
  }
295
297
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
296
298
  //#endregion
297
- export { IndexedDBCacheStoreOptions as C, IndexedDBCacheStoreEvent as S, TieredCacheStore as _, CachePluginOptions as a, IndexedDBCacheCompactionResult as b, CacheStats as c, MemoryCacheStoreOptions as d, WebStorageCacheStore as f, TieredCacheCoordinationOptions as g, TieredCacheBroadcastOptions as h, CachePlugin as i, CacheStore as l, cachePlugin as m, CacheEvent as n, CacheRefreshLease as o, WebStorageCacheStoreOptions as p, CacheEventType as r, CacheSetOptions as s, CacheEntry as t, MemoryCacheStore as u, TieredCacheStoreOptions as v, IndexedDBCacheUsage as w, IndexedDBCacheStore as x, IndexedDBCacheCompactionOptions as y };
299
+ export { WebStorageCacheStore as C, MemoryCacheStoreOptions as S, IndexedDBCacheUsage as _, CacheSetOptions as a, CacheStore as b, TieredCacheBroadcastOptions as c, TieredCacheStoreOptions as d, IndexedDBCacheCompactionOptions as f, IndexedDBCacheStoreOptions as g, IndexedDBCacheStoreEvent as h, CachePluginOptions as i, TieredCacheCoordinationOptions as l, IndexedDBCacheStore as m, CacheEventType as n, CacheStats as o, IndexedDBCacheCompactionResult as p, CachePlugin as r, cachePlugin as s, CacheEvent as t, TieredCacheStore as u, CacheEntry as v, WebStorageCacheStoreOptions as w, MemoryCacheStore as x, CacheRefreshLease as y };
@@ -0,0 +1 @@
1
+ const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./isBinaryBody-B0414zDU.cjs"),n=require("./isPromiseLike-C8e95Or2.cjs"),r=require("./waitForSignal-D5eX-NMv.cjs"),i=require("./resolveExtensionConfig-BHHfQwjF.cjs"),a={persist:!1,ttl:0};function resolveRequestCachePolicy(e){let t=new Headers(e.headers),n=t.get(`cache-control`),r=!1;if(n)for(let e of n.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),i=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(i===`no-store`)return`no-store`;if(i===`no-cache`){r=!0;continue}if(i===`max-age`&&n!==-1){let e=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function resolveResponseCachePolicy(e,t,n,r){let i=e.headers.get(`cache-control`),o,s=!1;if(i)for(let e of i.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),r=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(r===`no-store`)return a;if(r===`no-cache`){s=!0;continue}if(r!==`max-age`)continue;if(o!==void 0)return a;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return a;o=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||isRequestCacheControlHeader$1(t)})||t<=0||o!==void 0&&!Number.isSafeInteger(o))return a;let c=s?0:o===void 0?t:Math.min(t,Math.max(0,(o-parseAge(e.headers.get(`age`)))*1e3));return{ttl:c,persist:c>0||hasResponseValidator$1(e.headers)||resolveStaleIfErrorWindow(e.headers,n)>0||!s&&resolveStaleWhileRevalidateWindow(e.headers,r)>0}}function resolveStaleIfErrorWindow(e,t){return resolveWindow(e,t,`stale-if-error`)}function resolveStaleWhileRevalidateWindow(e,t){return resolveWindow(e,t,`stale-while-revalidate`)}function hasCacheControlDirective(e,t){return e.get(`cache-control`)?.split(`,`).some(e=>{let n=e.indexOf(`=`);return(n===-1?e:e.slice(0,n)).trim().toLowerCase()===t})??!1}function resolveWindow(e,t,n){let r=parseCacheDeltaSeconds(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function parseCacheDeltaSeconds(e,t){let n;if(!e)return;for(let r of e.split(`,`)){let e=r.trim(),i=e.indexOf(`=`);if(i===-1||e.slice(0,i).trim().toLowerCase()!==t)continue;if(n!==void 0)return;let a=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function parseAge(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function hasResponseValidator$1(e){return e.has(`etag`)||e.has(`last-modified`)}function isRequestCacheControlHeader$1(e){return e===`cache-control`||e===`pragma`}function isCacheableRequest(e,t,n){return t.has(e.method??`GET`)&&(!hasRequestBody(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`}function hasRequestBody(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function isSchemaValidationFailure(t){return e.n(t)&&t.code===`SCHEMA_ERROR`}function canUseStaleIfError(e,t,n,r){try{if(n&&!e.raw||hasConditionalRequestHeaders(t))return!1;let i=resolveStaleIfErrorWindow(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function canUseStaleWhileRevalidate(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(hasConditionalRequestHeaders(t)||hasCacheControlDirective(i,`no-cache`)||hasCacheControlDirective(i,`must-revalidate`))return!1;let a=resolveStaleWhileRevalidateWindow(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function startBackgroundRefresh(e,t,n,r,i,a){if(t.has(n))return;let o=new AbortController,s={...r,signal:o.signal};t.set(n,o),a(`background-refresh`),Promise.resolve().then(()=>e.dispatch(s,{background:!0,preserveRaw:i})).then(()=>a(`background-refresh-success`),()=>a(`background-refresh-error`)).finally(()=>{t.get(n)===o&&t.delete(n)})}function abortBackgroundRefreshes(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function isEligibleStaleIfError(t){return e.n(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function canRevalidateCacheEntry(e,t,n){try{return n&&!e.raw||hasConditionalRequestHeaders(t)?!1:hasResponseValidator(new Headers(e.headers))}catch{return!1}}function prepareConditionalRevalidation(e,t){let n=new Headers(t.headers),r=n.get(`etag`),i=n.get(`last-modified`);if(!r&&!i)return!1;let a=new Headers(e.headers);r&&a.set(`if-none-match`,r),i&&a.set(`if-modified-since`,i);let o=e.validateStatus,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function hasResponseValidator(e){return e.has(`etag`)||e.has(`last-modified`)}function hasConditionalRequestHeaders(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function normalizeCacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e.t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeCacheStatus(t,n){let r=t??200;if(!Number.isInteger(r)||r<200||r>599)throw new e.t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeStaleIfError(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeStaleWhileRevalidate(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeCacheTags(t,n){if(t===void 0)return[];if(typeof t!=`string`&&!Array.isArray(t))throw new e.t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof t==`string`?[t]:t;if(r.length>32)throw new e.t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let t of r){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(t)}return[...i]}function isExpired(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=normalizeMaxEntries(e.maxEntries)}get(e){let t=this.entries.get(e);if(t)return this.newestKey!==e&&(this.entries.delete(e),this.entries.set(e,t),this.newestKey=e),t}set(e,t){if(this.maxEntries!==0){for(this.entries.delete(e);this.entries.size>=this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}this.entries.set(e,t),this.newestKey=e}}delete(e){this.entries.delete(e),this.newestKey===e&&(this.newestKey=void 0)}invalidateTags(e){let t=new Set(e),n=0;for(let[e,r]of this.entries)r.tags?.some(e=>t.has(e))&&(this.entries.delete(e),n+=1,this.newestKey===e&&(this.newestKey=void 0));return n}clear(){this.entries.clear(),this.newestKey=void 0}},WebStorageCacheStore=class{constructor(e,t={}){this.storage=e,this.prefix=createWebStoragePrefix(t.namespace),this.maxEntries=normalizeMaxEntries(t.maxEntries)}get(e){if(this.maxEntries===0)return;let t=this.prefix+e,n=this.read(t);if(n){try{this.storage.setItem(t,serializeWebStorageEntry(n.entry,Date.now()))}catch{}return n.entry}}set(e,t){if(this.maxEntries===0)return;let n=this.prefix+e,r=this.keys(),i=r.includes(n),a=Math.max(0,r.length-this.maxEntries+ +!i);if(a>0){let e=r.map(e=>({key:e,accessedAt:this.read(e)?.accessedAt??0})).filter(e=>e.key!==n).sort((e,t)=>e.accessedAt-t.accessedAt);for(let t of e.slice(0,a))this.storage.removeItem(t.key)}this.storage.setItem(n,serializeWebStorageEntry(t,Date.now()))}delete(e){this.storage.removeItem(this.prefix+e)}invalidateTags(e){let t=new Set(e),n=0;for(let e of this.keys())this.read(e)?.entry.tags?.some(e=>t.has(e))&&(this.storage.removeItem(e),n+=1);return n}clear(){for(let e of this.keys())this.storage.removeItem(e)}keys(){let e=[];for(let t=0;t<this.storage.length;t+=1){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}return e}read(e){let t=this.storage.getItem(e);if(t!==null)try{return parseWebStorageEntry(t)}catch{this.storage.removeItem(e);return}}};function normalizeMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function createWebStoragePrefix(t=`default`){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(t)}:`}function serializeWebStorageEntry(e,t){return JSON.stringify({version:1,data:e.data,expiresAt:e.expiresAt===1/0?null:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags,accessedAt:t})}function parseWebStorageEntry(e){let t=JSON.parse(e),n=t.expiresAt===null?1/0:t.expiresAt;if(t.version!==1||n!==1/0&&(typeof n!=`number`||!Number.isFinite(n))||typeof t.status!=`number`||!Number.isInteger(t.status)||t.status<200||t.status>599||typeof t.statusText!=`string`||!Array.isArray(t.headers)||typeof t.accessedAt!=`number`||!Number.isFinite(t.accessedAt))throw TypeError(`Invalid web storage cache entry`);let r=t.tags===void 0?void 0:normalizeCacheTags(t.tags);return{entry:{data:t.data,expiresAt:n,status:t.status,statusText:t.statusText,headers:[...new Headers(t.headers).entries()],tags:r&&r.length>0?r:void 0},accessedAt:t.accessedAt}}const o=[];function createCacheKey(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,s=String(e.url),c=e.responseType??`auto`,l=!e.headers&&!e.query&&!e.searchParams;if(l&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===s&&i.responseType===c)return i.key;let u=JSON.stringify({method:a,baseURL:e.baseURL,url:s,query:l?o:normalizeQuery(e.searchParams??e.query),responseType:c,headers:e.headers?normalizeCacheHeaders(new Headers(e.headers),n):r});return l&&(i.method=a,i.baseURL=e.baseURL,i.url=s,i.responseType=c,i.key=u),u}function normalizeCacheHeaders(e,t){let n=[];e?.forEach((e,t)=>{isRequestCacheControlHeader(t)||n.push([t,e])});for(let r of t)!isRequestCacheControlHeader(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function isRequestCacheControlHeader(e){return e===`cache-control`||e===`pragma`}function normalizeVaryHeaders(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function normalizeQuery(e){if(!e)return o;if(t.r(e))return[...e.entries()];let n=[];for(let t of Object.keys(e).sort())appendQueryValue(n,t,e[t]);return n}function appendQueryValue(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)appendQueryValue(e,t,r);return}e.push([t,String(n)])}}function acquireCacheGeneration(e,t,n,r){let i=n.get(t);i||(i={activeRequests:0,tags:new Set},n.set(t,i)),i.activeRequests+=1;for(let e of r)i.tags.add(e);return{global:e,key:t,token:i}}function isCurrentCacheGeneration(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function releaseCacheGeneration(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function createInFlightRequest(e,t,n){return{owner:e,key:t,generation:n}}function getInFlightPromise(e){if(e.promise)return e.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.catch(()=>{}),e.promise=r,e.resolve=t,e.reject=n,r}function readStore(e,t){try{let r=e.get(t);return n.t(r)?Promise.resolve(r).catch(()=>void 0):r}catch{return}}function writeStore(e,t,r){try{let i=e.set(t,r);if(n.t(i))return Promise.resolve(i).catch(ignoreStoreError)}catch{}}function deleteStore(e,t){try{let r=e.delete(t);if(n.t(r))return Promise.resolve(r).catch(ignoreStoreError)}catch{}}function ignoreStoreError(){}function waitForSharedRecord(e,t){let n=t.signal;return n?n.aborted?Promise.reject(createSharedAbortError(n.reason,t)):new Promise((r,i)=>{let a=!1,cleanup=()=>{try{n.removeEventListener(`abort`,onAbort)}catch{}},resolveOnce=e=>{a||(a=!0,cleanup(),r(e))},rejectOnce=e=>{a||(a=!0,cleanup(),i(e))},onAbort=()=>{rejectOnce(createSharedAbortError(n.reason,t))};try{n.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}n.aborted&&onAbort(),!a&&e.then(resolveOnce,e=>{rejectOnce(cloneSharedError(e,t))})}):e.catch(e=>{throw cloneSharedError(e,t)})}function createSharedAbortError(t,n){return new e.t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:t})}function cloneSharedError(t,n){return e.n(t)?new e.t(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:n,cause:t}):t}function createCacheEntry(e,t,n,r){return{data:cloneCacheValue(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?cloneResponse(e.raw):void 0}}function createCachedResponse(e,t){return{data:cloneCacheValue(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:cloneRawResponse(e)}}function restoreCacheEntry(e,t){try{return createCachedResponse(e,t)}catch{return}}function createRevalidatedResponse(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),createCachedResponse({...e,headers:[...r.entries()]},n)}function cloneRawResponse(e){if(e.raw){let t=cloneResponse(e.raw);if(t)return new Response(t.body,{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}function cloneResponse(e){try{return e.clone()}catch{return}}function cloneCacheValue(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}const s=`entries`,c=`namespace`;var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=normalizeIndexedDBName(t.namespace,`namespace`,`default`),this.maxEntries=normalizeIndexedDBMaxEntries(t.maxEntries),this.maxBytes=normalizeIndexedDBMaxBytes(t.maxBytes),this.quotaRecovery=normalizeQuotaRecovery(t.quotaRecovery),this.shouldPersist=normalizeIndexedDBAdmissionPolicy(t.shouldPersist),this.onEvent=normalizeIndexedDBEventObserver(t.onEvent),this.schemaVersion=normalizeIndexedDBSchemaVersion(t.schemaVersion),this.databaseName=normalizeIndexedDBName(t.databaseName,`database name`,`@npora/request-cache`),this.factory=e}async get(e){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let t=(await this.getDatabase()).transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s),i=this.createKey(e),a=await waitForRequest(r.get(i)),o=isFutureIndexedDBRecord(a,this.schemaVersion);if(!isValidIndexedDBRecord(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:readIndexedDBRecordSize(a)});return}return a.accessedAt=Date.now(),a.size=readIndexedDBRecordSize(a),r.put(a),await n,toPortableCacheEntry(a)}async set(t,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(t);return}let r=await this.getDatabase(),i={...toPortableCacheEntry(n),key:this.createKey(t),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=estimateStructuredCloneSize(i),i.size>this.maxBytes){await this.delete(t),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(toPortableCacheEntry(i),i.size);if(typeof a!=`boolean`)throw new e.t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(t),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!isQuotaExceededError(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s),i=this.createKey(e);isFutureIndexedDBRecord(await waitForRequest(r.get(i)),this.schemaVersion)||r.delete(i),await n}async invalidateTags(e){let t=new Set(e),n=0;return await this.visitNamespace(e=>e.tags?.some(e=>t.has(e))?(n+=1,!0):!1),n}async clear(){await this.visitNamespace(()=>!0)}async getUsage(){let e=(await this.getDatabase()).transaction(s,`readonly`),t=waitForTransaction(e),n=e.objectStore(s).index(c).openCursor(this.namespace),r=0,i=0;return await visitCursor(n,e=>{let t=e.value;isValidIndexedDBRecord(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=addSizes(i,readIndexedDBRecordSize(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=normalizeCompactionBoundary(e.expiredBefore),n=normalizeCompactionMaxRemovals(e.maxRemovals),r=(await this.getDatabase()).transaction(s,`readwrite`),i=waitForTransaction(r),a=r.objectStore(s).index(c).openCursor(this.namespace),o=new Map,l=0,u=0,d=0,f=!1;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,this.namespace,this.schemaVersion);if(l+=1,i===`malformed`||i===`schema-version`)e.delete(),addCleanupSummary(o,i,r),u+=1,d=addSizes(d,readIndexedDBRecordSize(r));else if(i===`current`&&r.expiresAt<=t){let t=readIndexedDBRecordSize(r);e.delete(),addCleanupSummary(o,`expired`,r),u+=1,d=addSizes(d,t)}if(u>=n)return f=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:l,removedEntries:u,estimatedBytesFreed:d,expiredBefore:t,hasMore:f}}async close(){let e=this.database;e&&(this.database=void 0,(await e).close())}createKey(e){return this.schemaVersion===1?`${this.namespace}\0${e}`:`${this.namespace}\0@npora-schema:${this.schemaVersion}\0${e}`}async writeRecord(e,t){let n=e.transaction(s,`readwrite`),r=waitForTransaction(n),i=n.objectStore(s),a=new Map;if(isFutureIndexedDBRecord(await waitForRequest(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await waitForRequest(i.index(c).getAll(this.namespace)),n=[];for(let t of e){let e=classifyIndexedDBRecord(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),addCleanupSummary(a,e,t)):e===`current`&&n.push(t)}n.sort((e,n)=>e.key===t.key?1:n.key===t.key?-1:e.accessedAt-n.accessedAt||e.key.localeCompare(n.key));let r=n.reduce((e,t)=>addSizes(e,readIndexedDBRecordSize(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),addCleanupSummary(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-readIndexedDBRecordSize(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s),i=await waitForRequest(r.index(c).getAll(this.namespace)),a=[],o=new Map,l=!1;for(let e of i){let t=classifyIndexedDBRecord(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),addCleanupSummary(o,t,e),l=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),addCleanupSummary(o,`quota-recovery`,e),l=!0;return await n,this.emitCleanupSummaries(o.values()),l}emitCleanupSummaries(e){for(let t of e)this.emitEvent({type:`eviction`,...t})}emitEvent(e){if(this.onEvent)try{Promise.resolve(this.onEvent({...e,timestamp:Date.now()})).catch(()=>{})}catch{}}async visitNamespace(e){let t=(await this.getDatabase()).transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s).index(c).openCursor(this.namespace),i=new Map;await visitCursor(r,t=>{let n=t.value,r=classifyIndexedDBRecord(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&addCleanupSummary(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=openCacheDatabase(this.factory,this.databaseName).then(async e=>{try{let t=await pruneOlderSchemaRecords(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}};function openCacheDatabase(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(s)||e.createObjectStore(s,{keyPath:`key`}).createIndex(c,c,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function waitForRequest(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function waitForTransaction(e){let t=new Promise((t,n)=>{let rejectWithTransactionError=t=>{n(e.error??readIDBRequestError(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=rejectWithTransactionError,e.onerror=rejectWithTransactionError,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function readIDBRequestError(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function visitCursor(e,t){return new Promise((n,r)=>{e.onerror=()=>r(e.error),e.onsuccess=()=>{let i=e.result;if(!i){n();return}try{if(t(i)===!1){n();return}}catch(t){try{readCursorTransaction(e)?.abort()}catch{}r(t);return}i.continue()}})}function readCursorTransaction(e){let t=e.source;if(t)return`transaction`in t?t.transaction:`objectStore`in t?t.objectStore.transaction:`transaction`in t.source?t.source.transaction:t.source.objectStore.transaction}function toPortableCacheEntry(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function isValidIndexedDBRecord(e,t,n,r=1){if(!e||typeof e!=`object`)return!1;let i=e;if(!(typeof i.key==`string`&&(n===void 0||i.key===n)&&i.namespace===t&&readIndexedDBSchemaVersion(i)===r&&(i.expiresAt===1/0||Number.isFinite(i.expiresAt))&&Number.isInteger(i.status)&&i.status>=200&&i.status<=599&&typeof i.statusText==`string`&&Array.isArray(i.headers)&&(i.tags===void 0||Array.isArray(i.tags)&&i.tags.length<=32&&i.tags.every(e=>typeof e==`string`&&e.length>0&&e.length<=128))&&Number.isFinite(i.accessedAt)))return!1;try{return new Headers(i.headers),!0}catch{return!1}}function readIndexedDBSchemaVersion(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function classifyIndexedDBRecord(e,t,n){let r=readIndexedDBSchemaVersion(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:isValidIndexedDBRecord(e,t,void 0,n)?`current`:`malformed`}function isFutureIndexedDBRecord(e,t){let n=readIndexedDBSchemaVersion(e);return n!==void 0&&n>t}function readIndexedDBRecordSize(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:estimateStructuredCloneSize(e)}function estimateStructuredCloneSize(e,n=new WeakSet){if(e==null)return 0;if(typeof e==`string`)return Math.min(2**53-1,e.length*2);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 4;if(typeof e!=`object`)return 0;if(n.has(e)||(n.add(e),e instanceof Date))return 8;if(t.n(e))return e.size;if(t.t(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let t=16;for(let[r,i]of e)t=addSizes(t,estimateStructuredCloneSize(r,n),estimateStructuredCloneSize(i,n));return t}if(e instanceof Set){let t=16;for(let r of e)t=addSizes(t,estimateStructuredCloneSize(r,n));return t}let r=Array.isArray(e)?16:32;for(let[t,i]of Object.entries(e))r=addSizes(r,t.length*2,estimateStructuredCloneSize(i,n));return r}function addSizes(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function addCleanupSummary(e,t,n){let r=e.get(t),i=readIndexedDBRecordSize(n);if(r){r.entries+=1,r.estimatedBytes=addSizes(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function isQuotaExceededError(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}async function pruneOlderSchemaRecords(e,t,n){let r=e.transaction(s,`readwrite`),i=waitForTransaction(r),a=r.objectStore(s).index(c).openCursor(t),o=new Map;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),addCleanupSummary(o,i,r))}),await i,[...o.values()]}function normalizeIndexedDBName(t,n,r){let i=t??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new e.t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function normalizeIndexedDBMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeIndexedDBMaxBytes(t){if(t===void 0)return 1/0;if(t===1/0)return t;if(!Number.isSafeInteger(t)||t<0)throw new e.t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeQuotaRecovery(t){if(t===void 0)return!0;if(typeof t!=`boolean`)throw new e.t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBEventObserver(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBAdmissionPolicy(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeCompactionBoundary(t){let n=t??Date.now();if(!Number.isFinite(n))throw new e.t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function normalizeCompactionMaxRemovals(t){if(t===void 0||t===1/0)return 1/0;if(!Number.isSafeInteger(t)||t<1)throw new e.t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBSchemaVersion(t){let n=t??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new e.t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}var TieredCacheStore=class{constructor(t){if(this.leaseReleases=new Set,this.source=`${Date.now()}:${Math.random()}`,this.trackedKeys=new Map,this.trackedKeyCount=0,this.handleMessage=e=>{let t=e.data;if(!isTieredCacheMessage(t)||t.source===this.source)return;if(t.action===`clear`){this.clearPrimary();return}let n=this.trackedKeys.get(t.fingerprint);if(!n){this.clearPrimary();return}this.trackedKeys.delete(t.fingerprint),this.trackedKeyCount-=n.size;for(let e of n)ignoreStoreResult(()=>this.primary.delete(e))},!t||!t.primary||!t.secondary||t.primary===t.secondary)throw new e.t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=t.primary,this.secondary=t.secondary,t.broadcast&&!t.broadcast.channel)throw new e.t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(t.coordination&&!t.coordination.locks)throw new e.t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=t.broadcast?.channel,this.locks=t.coordination?.locks,this.lockNamespace=normalizeLockNamespace(t.coordination?.namespace),this.maxTrackedKeys=normalizeTrackedKeys(t.broadcast?.maxTrackedKeys),this.locks&&(this.acquireRefreshLease=(e,t)=>this.acquireCoordinatedLease(e,t)),this.channel?.addEventListener(`message`,this.handleMessage)}get(e){let t;try{t=this.primary.get(e)}catch{return this.readSecondary(e)}return n.t(t)?Promise.resolve(t).then(t=>t?this.remember(e,t):this.readSecondary(e),()=>this.readSecondary(e)):t?this.remember(e,t):this.readSecondary(e)}set(e,t){let writePrimary=()=>{let r;try{r=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return n.t(r)?Promise.resolve(r).catch(t=>{throw this.recoverPrimaryWrite(e),t}):r},r=this.secondary.set(e,t),i=n.t(r)?Promise.resolve(r).then(writePrimary):writePrimary();return this.afterSuccess(i,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(t){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new e.t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>combineStoreOperations([()=>n.call(this.primary,t),()=>r.call(this.secondary,t)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(t,n){let r=`${this.lockNamespace}:${fingerprintCacheKey(t)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new e.t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ignoreStoreFailure(()=>this.primary.delete(t)),a}dispose(){this.channel?.removeEventListener(`message`,this.handleMessage);for(let e of this.leaseReleases)e();this.leaseReleases.clear(),this.trackedKeys.clear(),this.trackedKeyCount=0}requestLease(e,t,n){return new Promise((r,i)=>{let a=!1,o=createDeferred(),s={mode:`exclusive`,ifAvailable:t};n&&(s.signal=n),this.locks.request(e,s,async e=>{if(!e){a=!0,r(void 0);return}let n=!0,release=()=>{n&&(n=!1,this.leaseReleases.delete(release),o.resolve())};this.leaseReleases.add(release),a=!0,r({contended:!t,release}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let promote=t=>{if(t){try{let r=this.primary.set(e,t);if(n.t(r))return Promise.resolve(r).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},t=this.secondary.get(e);return n.t(t)?Promise.resolve(t).then(promote):promote(t)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);if(n?.has(e)){this.trackedKeys.delete(t),this.trackedKeys.set(t,n);return}for(;this.trackedKeyCount>=this.maxTrackedKeys;){let e=this.trackedKeys.entries().next().value;if(!e)break;this.trackedKeys.delete(e[0]),this.trackedKeyCount-=e[1].size}n??(n=new Set),n.add(e),this.trackedKeys.delete(t),this.trackedKeys.set(t,n),this.trackedKeyCount+=1}untrackKey(e){let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);n?.delete(e)&&(--this.trackedKeyCount,n.size===0&&this.trackedKeys.delete(t))}broadcastKey(e){this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`delete`,fingerprint:fingerprintCacheKey(e)})}broadcastClear(){this.trackedKeys.clear(),this.trackedKeyCount=0,this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`clear`})}postMessage(e){try{this.channel?.postMessage(e)}catch{}}clearPrimary(){this.trackedKeys.clear(),this.trackedKeyCount=0,ignoreStoreResult(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ignoreStoreResult(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return n.t(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let r;try{r=e()}catch(e){throw t(),e}return n.t(r)?Promise.resolve(r).then(e=>(t(),e),e=>{throw t(),e}):(t(),r)}};function combineStoreOperations(e,t){let r=[],i=[],a,o=!1;for(let t of e)try{let e=t();n.t(e)?i.push(Promise.resolve(e).then(e=>{r.push(e)},e=>{o||(o=!0,a=e)})):r.push(e)}catch(e){o||(o=!0,a=e)}let finish=()=>{if(o)throw a;return t(r)};return i.length>0?Promise.all(i).then(finish):finish()}function fingerprintCacheKey(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function isTieredCacheMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.protocol===`npora-cache:1`&&typeof t.source==`string`&&(t.action===`clear`||t.action===`delete`&&typeof t.fingerprint==`string`&&t.fingerprint.length<=16)}function normalizeTrackedKeys(t){let n=t??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new e.t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function normalizeLockNamespace(t){let n=t??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new e.t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function createDeferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ignoreStoreResult(e){try{let t=e();n.t(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ignoreStoreFailure(e){try{await e()}catch{}}const l=[`GET`,`HEAD`],u=[`authorization`,`cookie`,`accept`,`accept-language`],d={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function createCacheStats(){return{hits:0,misses:0,bypasses:0,invalidations:0,invalidationErrors:0,deduplicated:0,revalidations:0,staleIfError:0,staleWhileRevalidate:0,backgroundRefreshes:0,backgroundRefreshSuccesses:0,backgroundRefreshErrors:0}}function resetCacheStats(e){Object.assign(e,createCacheStats())}function createCacheEventRecorder(e,t){return r=>{if(incrementCacheStat(e,r),t)try{let e=t({type:r,timestamp:Date.now()});n.t(e)&&Promise.resolve(e).catch(ignoreCacheEventError)}catch{}}}function incrementCacheStat(e,t){let n=d[t];e[n]=Math.min(2**53-1,e[n]+1)}function ignoreCacheEventError(){}function cachePlugin(t={}){let a=t.store??new MemoryCacheStore({maxEntries:t.maxEntries}),o=new WeakSet,s=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap,h=new WeakSet,g=new WeakSet,_=new WeakMap,v=new WeakMap,y=new WeakSet,b=new WeakSet,x=new Map,S=new Map,C=new WeakSet,w=new Map,T=new Map,E=new Map,D=new Map,O=createCacheStats(),k=createCacheEventRecorder(O,t.onEvent),A=0,j=new Set(t.methods??l),M=normalizeVaryHeaders(t.varyHeaders??u),N=normalizeCacheHeaders(void 0,M),P={};function trackKeyOperation(e,t,n,r){let i=Promise.resolve(t),a;return a=i.then(()=>n&&k(n),()=>r&&k(r)).finally(()=>{E.get(e)===a&&E.delete(e)}),E.set(e,a),i}function runKeyOperation(e,t,r=[],i,a){let o=new Set(r),s=E.get(e);if(s&&o.add(s),o.size>0)return trackKeyOperation(e,Promise.all(o).then(t),i,a);let c;try{c=t()}catch(e){throw a&&k(a),e}return n.t(c)?trackKeyOperation(e,c,i,a):(i&&k(i),c)}function invalidateKeyState(e,t){T.delete(e),x.delete(e),S.delete(e);let n=w.get(e);n&&(w.delete(e),n.abort(t))}function trackTagInvalidation(e,t){let n=Promise.resolve(t),r;r=n.then(()=>k(`invalidated`),()=>k(`invalidation-error`)).finally(()=>{for(let t of e)D.get(t)===r&&D.delete(t)});for(let t of e)D.set(t,r);return n}let F={name:`cache`,clear(){return A+=1,x.clear(),S.clear(),T.clear(),abortBackgroundRefreshes(w),a.clear()},delete(e){let t=createCacheKey(e,i.t(e,`cache`)??{},M,N,P);return invalidateKeyState(t,`Cache entry invalidated`),runKeyOperation(t,()=>a.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,n={}){let r=i.t(e,`cache`)??{},o=createCacheKey(e,r,M,N,P),s=normalizeCacheTtl(n.ttl??r.ttl,e),c=normalizeCacheStatus(n.status,e),l=normalizeCacheTags(n.tags??r.tags,e),u={data:cloneCacheValue(t),expiresAt:s===1/0?s:Date.now()+s,status:c,statusText:n.statusText??(c===200?`OK`:``),headers:[...new Headers(n.headers).entries()],tags:l.length>0?l:void 0},d=l.map(e=>D.get(e)).filter(e=>!!e);return invalidateKeyState(o,`Cache entry replaced`),runKeyOperation(o,()=>a.set(o,u),d)},update(e,t){let r=createCacheKey(e,i.t(e,`cache`)??{},M,N,P);return invalidateKeyState(r,`Cache entry updated`),runKeyOperation(r,()=>{let updateEntry=e=>{if(!e)return!1;let i=t(cloneCacheValue(e.data));if(i===void 0){let e=a.delete(r);return!n.t(e)||Promise.resolve(e).then(()=>!0)}let o=a.set(r,{...e,data:cloneCacheValue(i),raw:void 0});return!n.t(o)||Promise.resolve(o).then(()=>!0)},e=a.get(r);return n.t(e)?Promise.resolve(e).then(updateEntry):updateEntry(e)},D.values())},invalidateTags(t){let r=normalizeCacheTags(t);if(r.length===0)throw new e.t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let i=a.invalidateTags;if(!i)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of T)r.some(e=>t.tags.has(e))&&invalidateKeyState(e,`Cache tags invalidated`);let o=new Set(r.map(e=>D.get(e)).filter(e=>!!e));for(let e of E.values())o.add(e);if(o.size>0)return trackTagInvalidation(r,Promise.all(o).then(()=>i.call(a,r)));let s;try{s=i.call(a,r)}catch(e){throw k(`invalidation-error`),e}return n.t(s)?trackTagInvalidation(r,s):(k(`invalidated`),s)},getStats(){return{...O}},resetStats(){resetCacheStats(O)},install(l){let u=new Set,O=new Set,I=!0;l.hooks.onRequest(t=>{let o=i.t(t.config,`cache`);if(!o)return;let s=normalizeCacheTags(o.invalidateTags,t.config);if(s.length>0){if(!a.invalidateTags)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:t.config});d.set(t,s)}if(!o.enabled||!isCacheableRequest(t.config,j,o))return;normalizeCacheTtl(o.ttl,t.config),normalizeStaleIfError(o.staleIfError,t.config),normalizeStaleWhileRevalidate(o.staleWhileRevalidate,t.config);let l=normalizeCacheTags(o.tags,t.config),u=resolveRequestCachePolicy(t.config);if(u===`no-store`){k(`bypass`),g.add(t);return}(u===`revalidate`||t.background)&&h.add(t);let f=createCacheKey(t.config,o,M,N,P),p=acquireCacheGeneration(A,f,T,l);c.set(t,p);let read=()=>{let e=readStore(a,f);return t.config.signal&&n.t(e)?r.t(()=>e,t.config).then(e=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(t,o,f,e,p)}):n.t(e)?Promise.resolve(e).then(e=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(t,o,f,e,p)}):handleCacheRecord(t,o,f,e,p)},m=new Set,_=E.get(f);_&&m.add(_);for(let e of l){let t=D.get(e);t&&m.add(t)}if(m.size>0){let e=Promise.all(m).then(()=>{});return t.config.signal?r.t(()=>e,t.config).then(read):e.then(read)}return read()}),l.hooks.onResponse(e=>{if(y.has(e)&&e.fallbackResponse){k(`stale-if-error`),o.add(e),e.cacheHit=!0,s.get(e)?.owner===e&&b.add(e);return}if(o.has(e))return;let t=i.t(e.config,`cache`);if(!t?.enabled||!e.response||!isCacheableRequest(e.config,j,t)||g.has(e))return;let l=m.get(e);if(e.response.raw.type===`opaque`||e.response.raw.type===`opaqueredirect`){s.get(e)?.owner===e&&b.add(e);return}l&&e.response.status===304&&(k(`revalidated`),e.response=createRevalidatedResponse(l,e.response,e.config));let u=s.get(e),d=u?.key??createCacheKey(e.config,t,M,N,P),h=isCurrentCacheGeneration(u?.generation??f.get(e)??c.get(e),A,T),_=(u?.generation??c.get(e))?.token.tags,v=_&&_.size>0?[..._]:l?.tags;if(isAsyncIterable(e.response.data)){if(b.add(e),!h)return;let t=deleteStore(a,d);return n.t(t)?e.config.signal?r.t(()=>t,e.config):t:void 0}let x=normalizeCacheTtl(t.ttl,e.config),S=normalizeStaleIfError(t.staleIfError,e.config),C=normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config),w=resolveResponseCachePolicy(e.response,x,S,C),E=w.ttl;if(!w.persist){let t=h?deleteStore(a,d):void 0,i=n.t(t),o=u;return o?.owner===e&&(o.promise!==void 0||i)?p.set(e,createCacheEntry(e.response,Date.now()+Math.max(0,E),e.preserveRaw,v)):o?.owner===e&&b.add(e),i?e.config.signal?r.t(()=>t,e.config):t:void 0}let D=createCacheEntry(e.response,Date.now()+E,e.preserveRaw,v);if(p.set(e,D),!h||u?.rawDemanded)return;let O=writeStore(a,d,D);if(n.t(O))return e.config.signal?r.t(()=>O,e.config):O},{requiresRawResponse:!1});function handleCacheRecord(e,t,i,s,c){if(!(!I||!isCurrentCacheGeneration(c,A,T))){if(s){let u=!isExpired(s.expiresAt),d=h.has(e);if(u&&!d){if(e.preserveRaw&&!s.raw)return prepareCacheMiss(e,t,i,c);let n=restoreCacheEntry(s,e.config);if(n){k(`hit`),e.response=n,o.add(e),e.cacheHit=!0;return}}if(!e.background&&!d&&canUseStaleWhileRevalidate(s,e.config,e.preserveRaw,normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config))){let t=restoreCacheEntry(s,e.config);if(t){k(`stale-while-revalidate`),e.response=t,o.add(e),e.cacheHit=!0,startBackgroundRefresh(l,w,i,e.initialConfig,e.preserveRaw,k);return}}if(!e.background&&canUseStaleIfError(s,e.config,e.preserveRaw,normalizeStaleIfError(t.staleIfError,e.config))&&_.set(e,s),canRevalidateCacheEntry(s,e.config,e.preserveRaw)&&restoreCacheEntry(s,e.config))return prepareCacheMiss(e,t,i,c,s);if(u&&d||e.background)return prepareCacheMiss(e,t,i,c);let f=deleteStore(a,i);if(n.t(f))return(e.config.signal?r.t(()=>f,e.config):Promise.resolve(f)).then(()=>prepareCacheMiss(e,t,i,c))}return prepareCacheMiss(e,t,i,c)}}function prepareCacheMiss(e,n,i,c,l){if(!I||!isCurrentCacheGeneration(c,A,T))return;if(!(n.dedupe??t.dedupe??!0)){e.background||k(`miss`),f.set(e,c);return}let d=e.preserveRaw?S.get(i):x.get(i)??S.get(i);if(d)return k(`deduplicated`),waitForSharedRecord(getInFlightPromise(d),e.config).then(t=>{t&&(e.response=createCachedResponse(t,e.config),o.add(e),e.cacheHit=!0)});let p=a.acquireRefreshLease;if(p&&!v.has(e)){let t;try{let n=p.call(a,i,e.config.signal);t=e.config.signal?r.t(()=>n,e.config):n}catch{return v.set(e,{contended:!1,release(){}}),handleCacheRecord(e,n,i,l,c)}return t.then(t=>(v.set(e,t),O.add(t),t.contended&&(h.delete(e),k(`deduplicated`)),Promise.resolve(readStore(a,i)).then(t=>handleCacheRecord(e,n,i,t,c))),t=>{if(e.config.signal?.aborted)throw t;return v.set(e,{contended:!1,release(){}}),handleCacheRecord(e,n,i,l,c)})}if(e.preserveRaw){let e=x.get(i);e&&(e.rawDemanded=!0)}let g=createInFlightRequest(e,i,c);e.preserveRaw?(S.set(i,g),C.add(e)):x.set(i,g),s.set(e,g),u.add(e),e.background||k(`miss`),l&&prepareConditionalRevalidation(e.config,l)&&m.set(e,l)}return l.hooks.onError(e=>{let t=_.get(e);if(!t||!isEligibleStaleIfError(e.error))return;let n=restoreCacheEntry(t,e.config);n&&(y.add(e),e.fallbackResponse=n)}),l.hooks.onSettled(t=>{let r=v.get(t);r&&(r.release(),O.delete(r)),v.delete(t),h.delete(t),g.delete(t),_.delete(t),y.delete(t);let i=c.get(t),invalidateAfterSuccess=()=>{let e=d.get(t);if(d.delete(t),!(!e||t.background||t.error||!t.response))try{let t=F.invalidateTags(e);if(n.t(t))return Promise.resolve(t).then(()=>{}).catch(ignoreCacheEventError)}catch{}};i&&(c.delete(t),releaseCacheGeneration(i,T));let a=s.get(t);if(!a)return invalidateAfterSuccess();s.delete(t),u.delete(t),m.delete(t);let o=a.key,l=C.delete(t)?S:x;if(l.get(o)===a&&l.delete(o),b.delete(t))return a.resolve?.(void 0),invalidateAfterSuccess();let f=p.get(t);return p.delete(t),f&&t.response&&(!t.error||isSchemaValidationFailure(t.error))?(a.resolve?.(f),invalidateAfterSuccess()):(a.reject?.(t.error??new e.t(`Shared request failed`,{code:`NETWORK_ERROR`,config:t.config})),invalidateAfterSuccess())}),()=>{I=!1;for(let e of O)e.release();O.clear();for(let t of u){let n=s.get(t);if(s.delete(t),!n)continue;let r=n.key,i=C.delete(t)?S:x;i.get(r)===n&&i.delete(r),n.reject?.(new e.t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}u.clear(),T.clear(),abortBackgroundRefreshes(w)}}};return F}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return WebStorageCacheStore}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return MemoryCacheStore}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return TieredCacheStore}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return IndexedDBCacheStore}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return cachePlugin}});