@0xdoublesharp/lru-cache-clustered 2.1.2 → 2.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,43 @@
1
+ # 2.1.4 / 2026-11-23
2
+
3
+ ## Primary and single-flight fixes
4
+
5
+ - Deduplicate cluster worker `message` listener attachment so importing or bootstrapping the primary in the same turn as `cluster.fork()` never executes worker requests twice.
6
+ - Release timed-out leader fetch claims immediately via `ownerRequestId`, prune promoted followers from follower sets before leadership promotion, and prevent polling followers from inflating primary `misses` statistics.
7
+ - Deliver oversized (`size > maxEntrySize`) `fetch()` results to registered followers per follower (preserving them even across an intervening `forceRefresh`) and prune the fetch lock once they drain, without admitting oversized entries into the cache or inflating `sets`.
8
+ - Report `false` from `set()` and `setIfAbsent()` when `size > maxEntrySize` prevents admission; keep readable stale entries intact on oversized `setIfAbsent()` under `allowStale` + `noDeleteOnStaleGet`; reject oversized `incr()`/`decr()` with `RangeError` without deleting an existing counter.
9
+ - Validate non-negative integer TTLs across `set`, `setIfAbsent`, `mSet`, `fetchStore`, `load`, `ttl()`, and constructor options, rejecting JSON-coerced `null` TTL/size inputs, rejecting `ttl(0)` on TTL-only caches (while preserving non-expiring entries in `load()`), and rejecting TTLs exceeding Node.js's 32-bit timer limit (`2_147_483_646` ms) when `ttlAutopurge` is enabled.
10
+ - Validate `maxEntrySize <= maxSize` on cache creation, keep `maxEntrySize: 0` option compatibility checks accurate, reject non-finite counter amounts or overflow in `incr()`/`decr()`, validate all `mGet()` keys before mutating stats, and reject nullish entries in `load()` before clearing the cache.
11
+ - Update stored entry sizes on same-value writes across `maxSize`, `maxEntrySize`, and `incr(key, 0, { size })` while preserving exact original expiry timestamps and autopurge timer bounds, avoid mutating caller `load()` entry objects in place, preserve non-expiring entries across `load()` and `max()` rebuilds, and clear discarded caches on `destroy()` and `max()` rebuilds so autopurge timers are released.
12
+ - Keep recreated namespace version records when a reentrant invalidation listener writes during `destroy()`.
13
+
14
+ ## Local L1, client, and codec fixes
15
+
16
+ - Reject non-finite or non-positive `localL1.ttl`, honor explicit `localL1.ttl` values below 100 ms (clamped to primary TTL and >= 1 ms), reject non-finite versions on invalidation pushes, sample fresh primary TTLs for L1 fills so local entries never outlive their primary deadline, and preserve `l1:evict` consistency via `disposeAfter`.
17
+ - Populate eager worker L1 fills (`set(..., { updateL1: true })` and `fetch()` leader fills) from the primary-acknowledged value returned in the IPC response so L1 matches the primary across JSON and advanced IPC, runs `toJSON()` once, and stays isolated from caller mutations.
18
+ - Prevent `destroy()` during an in-flight `fetch()` from re-subscribing the destroyed instance, bypass local in-flight `fetch()` deduplication on `bypassL1` / `withoutLocal()`, unblock same-instance fetches after mutation or lease expiry, and preserve the bypass wrapper when chaining `on()`, `off()`, and `once()` on `withoutLocal()`.
19
+ - Self-invalidate `ttl-only` L1 entries on `fetch()` leader stores, `forceRefresh` bypasses, and oversized writes, and prevent `init()`/`destroy()` races from leaking L1 subscriptions.
20
+ - Handle `failsafe: 'resolve'` timeouts safely in `wrap().values()` and `wrap().entries()`, allow `memoize()` to accept `WrappedCache`, and export `L1Stats`, `SerializableLruOptions`, `Stats`, `FetchOptions`, `ReadOptions`, `WriteOptions`, `LocalL1Options`, and `MSetEntry`.
21
+
22
+ ## Tooling and formal verification
23
+
24
+ - Dereference symlinked `dist/` directories during `pnpm prepare:publish` staging and verify staged regular build artifacts before packaging.
25
+ - Add TLA+ model checks (`formal/tla/L1Coherence.tla`, `formal/tla/FetchSingleFlight.tla`) and Lean 4 proofs (`formal/lean/Formal/*.lean`) run via `pnpm formal`, covering L1 version fencing, non-vacuous queue drainage, TTL bounds, key-encoding injectivity (including signed decimal bigints), and single-flight leader/follower/oversize lifecycle safety.
26
+
27
+ The runtime dependencies and Node.js 22 minimum are unchanged.
28
+
29
+ # 2.1.3 / 2026-11-08
30
+
31
+ - Simplify the README, consolidate runnable examples, and redraw the cache topology with larger labels and a high-resolution PNG embed linked to the SVG.
32
+ - Update README links and npm repository metadata to the canonical `0xdoublesharp/lru-cache-clustered` repository.
33
+ - Update seven development dependencies within their existing major versions while preserving the seven-day release waiting policy.
34
+ - Resolve Zod 4.6.7 and override affected glob and minimatch versions with 14.0.3 and 11.0.3 to address development-tool resource-exhaustion and cancellation advisories.
35
+ - Backport the import plugin's minimatch 11 compatibility fix while its upstream release completes the waiting period.
36
+ - Add a deterministic regression test proving that an asynchronous IPC response failure does not resend the response or apply a counter mutation twice.
37
+ - Authenticate Codecov uploads with GitHub OIDC and scope coverage and Pages permissions to their respective jobs.
38
+
39
+ The runtime API, runtime dependencies, and Node.js 22 minimum are unchanged.
40
+
1
41
  # 2.1.2 / 2026-10-15
2
42
 
3
43
  - Handle asynchronous primary response and invalidation send failures when workers disconnect, without retrying mutations.
package/README.md CHANGED
@@ -1,28 +1,22 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/LRUCacheClustered.png" alt="A pika, the project mascot" width="180" height="180">
2
+ <img src="https://raw.githubusercontent.com/0xdoublesharp/lru-cache-clustered/main/assets/LRUCacheClustered.png" alt="A pika, the project mascot" width="128" height="128">
3
3
  </p>
4
4
 
5
5
  # @0xdoublesharp/lru-cache-clustered
6
6
 
7
7
  [![npm](https://img.shields.io/npm/v/%400xdoublesharp%2Flru-cache-clustered.svg)](https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered)
8
- [![CI](https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml/badge.svg)](https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml)
9
- [![Coverage](https://codecov.io/gh/doublesharp/lru-cache-clustered/branch/main/graph/badge.svg)](https://codecov.io/gh/doublesharp/lru-cache-clustered)
8
+ [![CI](https://github.com/0xdoublesharp/lru-cache-clustered/actions/workflows/ci.yml/badge.svg)](https://github.com/0xdoublesharp/lru-cache-clustered/actions/workflows/ci.yml)
9
+ [![Coverage](https://codecov.io/gh/0xdoublesharp/lru-cache-clustered/branch/main/graph/badge.svg)](https://codecov.io/gh/0xdoublesharp/lru-cache-clustered)
10
10
  [![Downloads](https://img.shields.io/npm/dt/%400xdoublesharp%2Flru-cache-clustered.svg)](https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered)
11
11
 
12
- Let your Node.js workers share what they have already learned. When one worker caches a database result, the others can reuse it instead of loading and storing their own copies.
12
+ Shared in-memory [LRU caches](https://github.com/isaacs/node-lru-cache) for Node.js cluster workers, with atomic counters, coordinated fetches, and optional worker-local caching.
13
13
 
14
- This package keeps namespaced [LRU caches](https://github.com/isaacs/node-lru-cache) in a Node.js cluster's primary process. LRU means least recently used: when the cache fills up, it removes the entries you have used least recently. Workers access the shared cache through an asynchronous API over inter-process communication, or IPC. Atomic counters and fetch coordination also run in the primary.
14
+ The primary process holds one cache per namespace. Workers share its entries through an asynchronous API over inter-process communication (IPC), so a value loaded by one worker is available to the others. No separate cache service is required; data stays in memory for the lifetime of the primary.
15
15
 
16
- No separate cache service is required. The shared data lives in memory for the lifetime of the primary process. Optional local L1 caches keep hot values inside individual workers to avoid repeated IPC reads.
17
-
18
- <p align="center">
19
- <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/topology.svg" alt="The primary owns shared namespaced caches. Workers read and write through IPC, with optional local caches and invalidation messages." width="100%">
20
- </p>
16
+ [Quick start](#quick-start) · [How it works](#how-it-works) · [Examples](#use-cases) · [Local L1](#local-l1-mode) · [API](#api)
21
17
 
22
18
  ## What you get
23
19
 
24
- Each worker can reuse the same cached data, take a turn loading a missing value, and update shared counters without racing another worker.
25
-
26
20
  | Capability | How it works |
27
21
  | ---------------------- | ------------------------------------------------------------------------------------------------ |
28
22
  | Shared cache storage | One primary-owned cache per namespace, with optional extra copies in worker L1 caches. |
@@ -36,18 +30,18 @@ Each worker can reuse the same cached data, take a turn loading a missing value,
36
30
 
37
31
  ## Install
38
32
 
39
- Install this package and the cache engine it uses. Both JavaScript and TypeScript applications can use it.
40
-
41
33
  ```sh
42
34
  npm install @0xdoublesharp/lru-cache-clustered lru-cache@^11
43
35
  ```
44
36
 
45
37
  For pnpm or Yarn, use `pnpm add` or `yarn add` with the same package names. `lru-cache` is a peer dependency, so your application controls its installed version within the supported range.
46
38
 
47
- Requires Node.js 22 or newer. Includes ESM and CommonJS builds and TypeScript declarations.
39
+ Requires **Node.js 22 or newer**. Includes ESM and CommonJS builds and TypeScript declarations.
48
40
 
49
41
  > `@0xdoublesharp/lru-cache-clustered` is the canonical package name. `lru-cache-for-clusters-as-promised` is published from the same build at the same version.
50
42
 
43
+ **2.1.4** hardens primary cache validation, single-flight fetch coordination, worker listener attachment, and local L1 coherence, backed by TLA+ and Lean 4 formal verification. See the [release notes](./CHANGELOG.md#214--2026-11-23) for details.
44
+
51
45
  ## Quick start
52
46
 
53
47
  Start a few workers and give their caches the same name. A write from any worker goes into the shared cache in the primary.
@@ -83,46 +77,46 @@ Both workers read the same entry. `getInstance()` waits for namespace registrati
83
77
 
84
78
  Import the package in the primary before `cluster.fork()`. The import installs the IPC listener; `bootstrap()` makes that setup explicit. Instances that share a namespace must agree on primary cache options such as `max` and `ttl`.
85
79
 
86
- ## Use cases
80
+ ## How it works
87
81
 
88
- Use it when several workers in one Node.js cluster need the same temporary data. The most useful patterns save repeated work or coordinate short-lived state.
82
+ The primary owns the shared caches. Each namespace identifies one cache, and instances using that namespace must agree on options such as `max`, `ttl`, and `allowStale`. Conflicting options throw during initialization.
89
83
 
90
- | Idea | Pattern | Example |
91
- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
92
- | Stop a popular profile from triggering duplicate database queries | `memoize()` or `fetch()` lets workers reuse a cached result and coordinate concurrent misses. | [User lookup server](./examples/clustered-users-server.ts) |
93
- | Limit API requests across workers | `incr()` updates one shared counter. Its first write starts the TTL window; later increments keep that deadline. | [Rate limiter](./examples/clustered-rate-limit-server.ts) |
94
- | Share temporary session data | `set()`, `get()`, and `delete()` share entries across workers. Keep durable session state elsewhere. | [Session server](./examples/clustered-session-server.ts) |
95
- | Suppress repeated job submissions | `setIfAbsent()` lets one worker claim a cached key. Expiration, eviction, or restart can allow another claim. | [Idempotent intake](./examples/clustered-idempotency-server.ts) |
96
- | Keep large generated documents in less cache space | `wrap()` compresses stored values and decodes them on reads. | [Compressed documents](./examples/clustered-compressed-documents-server.ts) |
97
- | Reduce repeated Redis reads | Use this shared cache in front of Redis, then add a small worker L1 for hot reads. | [Multilayer cache](./examples/clustered-multilayer-redis-server.ts) |
84
+ <p align="center">
85
+ <a href="https://raw.githubusercontent.com/0xdoublesharp/lru-cache-clustered/main/assets/topology.svg">
86
+ <img src="https://raw.githubusercontent.com/0xdoublesharp/lru-cache-clustered/main/assets/topology.png" alt="One primary process holds shared namespaced caches. Workers send IPC requests and receive responses. Each worker can optionally keep an L1 cache for local hits; writes reach the primary and trigger asynchronous invalidation." width="800">
87
+ </a>
88
+ </p>
98
89
 
99
- For example, a report endpoint can use the report parameters as a cache key and `fetch()` to coordinate generation. Include tenant and authorization context when they affect the result.
90
+ - **In the primary**, operations call the namespace's `LRUCache` directly.
91
+ - **In a worker**, operations send typed IPC requests and return promises. With L1 enabled, eligible local hits skip IPC. Writes still reach the primary, which broadcasts invalidations by default.
100
92
 
101
- The cache belongs to one primary process. Separate clusters, containers, and machines do not share it. Use a remote cache or database when you need that wider scope, durable state, or coordination that must survive eviction and restarts. Shared counters and claims are atomic while their keys remain present; they do not provide durable quotas or exactly-once job processing.
93
+ > **Initialization.** In a worker, `new LRUCacheClustered(...)` sends an `init` message immediately. `cache.ready` waits for ordering but swallows initialization errors. Use `await LRUCacheClustered.getInstance(...)` or `await cache.healthCheck()` to fail startup when registration fails.
102
94
 
103
- Namespaces separate application data by name. They do not restrict worker access, so all workers must be trusted.
95
+ ## Use cases
104
96
 
105
- ## Runnable examples
97
+ The [example guide](./examples/README.md) includes request commands, ports, and environment settings. Run these commands from a checkout with dependencies installed.
106
98
 
107
- Start an example server, send it requests, and watch workers share cached results. The [example guide](./examples/README.md) has curl commands, ports, and environment settings.
99
+ | Example | Pattern | Run |
100
+ | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------- |
101
+ | [User lookups](./examples/clustered-users-server.ts) | Share database results with `memoize()` and `fetch()`. | `pnpm example:users` |
102
+ | [Rate limiting](./examples/clustered-rate-limit-server.ts) | Use atomic counters with a fixed TTL window. | `pnpm example:rate-limit` |
103
+ | [Sessions](./examples/clustered-session-server.ts) | Share temporary session reads and writes. | `pnpm example:sessions` |
104
+ | [Job intake](./examples/clustered-idempotency-server.ts) | Suppress duplicate submissions with `setIfAbsent()`. | `pnpm example:idempotency` |
105
+ | [Compressed documents](./examples/clustered-compressed-documents-server.ts) | Encode stored values with `wrap()`. | `pnpm example:documents` |
106
+ | [Local L1 controls](./examples/clustered-l1-controls-server.ts) | Try method filters, bypass reads, invalidation, and write-through population. | `pnpm example:l1` |
107
+ | [Redis layers](./examples/clustered-multilayer-redis-server.ts) | Put shared memory and worker L1 in front of Redis. Requires Redis. | `pnpm example:multilayer` |
108
108
 
109
- | Command | What to explore |
110
- | -------------------------- | ------------------------------------------------------------------------------------ |
111
- | `pnpm example:users` | Shared read-through user cache with `memoize()` and `fetch()`. |
112
- | `pnpm example:rate-limit` | Fixed-window counters across workers. |
113
- | `pnpm example:sessions` | Shared session reads and writes. |
114
- | `pnpm example:idempotency` | Temporary job claims with `setIfAbsent()`. |
115
- | `pnpm example:documents` | Compression with `wrap()`. |
116
- | `pnpm example:l1` | Method filtering, bypass reads, local invalidation, and write-through L1 population. |
117
- | `pnpm example:multilayer` | Shared memory caching in front of Redis. Requires Redis. |
109
+ The [basic L1 server](./examples/clustered-l1-server.ts) also runs with `node --import tsx examples/clustered-l1-server.ts`.
118
110
 
119
- The [basic L1 server](./examples/clustered-l1-server.ts) can also run with `node --import tsx examples/clustered-l1-server.ts`.
111
+ For example, a report endpoint can use the report parameters as a cache key and `fetch()` to coordinate generation. Include tenant and authorization context when they affect the result.
120
112
 
121
- ## Local L1 mode
113
+ The cache belongs to one primary process. Separate clusters, containers, and machines do not share it. Use a remote cache or database when you need that wider scope, durable state, or coordination that must survive eviction and restarts. Shared counters and claims are atomic while their keys remain present; they do not provide durable quotas or exactly-once job processing.
122
114
 
123
- Keep a small copy of frequently read values inside each worker. Repeated reads can stay in that worker instead of asking the primary again.
115
+ Namespaces separate application data by name. They do not restrict worker access, so all workers must be trusted.
124
116
 
125
- Enable the optional L1 cache with `localL1`. The primary remains the source of truth and owns every write. Invalidation messages tell workers to drop local entries after changes, but delivery is asynchronous.
117
+ ## Local L1 mode
118
+
119
+ Enable `localL1` to keep frequently read values inside each worker and avoid repeated IPC reads. The primary owns every write. Invalidation messages tell workers to drop local entries after changes, but delivery is asynchronous.
126
120
 
127
121
  ```ts
128
122
  type Product = { sku: string; name: string };
@@ -137,11 +131,11 @@ const products = new LRUCacheClustered<string, Product>({
137
131
 
138
132
  > L1 improves repeated read latency by avoiding IPC, but it can briefly serve stale data. Keep L1 TTL short and bypass L1 for correctness-sensitive reads.
139
133
 
140
- Set `experimental: true` to opt in. Without an explicit local TTL, the default is 10% of a positive primary TTL, up to 5 seconds, with a 100 ms floor. With no primary expiration, including `ttl: 0`, it defaults to 5 seconds. Each local entry is also capped at the remaining lifetime reported by the primary.
134
+ Set `experimental: true` to opt in. Explicit `localL1.ttl` values must be positive finite numbers and are honored directly (clamped to the primary TTL with a 1 ms floor). Without an explicit local TTL, the default is 10% of a positive primary TTL, up to 5 seconds, with a 100 ms floor. With no primary expiration, including `ttl: 0`, it defaults to 5 seconds. Each local entry is also capped at the remaining lifetime reported by the primary.
141
135
 
142
136
  Reuse one cache instance per namespace in each worker. Each constructor or `getInstance()` call creates a separate local L1, so recreating the instance per request loses its warm entries.
143
137
 
144
- A cold `fetch()` claims the key and stores the result in two IPC requests. Followers poll the claim once per cycle and reuse the leader's result.
138
+ A cold `fetch()` claims the key and stores the result in two IPC requests. Followers poll the claim once per cycle without inflating primary miss counts and reuse the leader's result, including oversized values (`size > maxEntrySize`) that are not admitted into the primary cache.
145
139
 
146
140
  L1 misses receive values and remaining TTLs in one primary response. A cold `mGet()` uses one IPC request for the batch, and a fully warm batch uses none. Local hits cannot extend an entry past the primary expiration recorded in that response, even with `updateAgeOnGet` or `allowStale` enabled.
147
141
 
@@ -187,19 +181,6 @@ By default, same-process and cross-worker writes broadcast invalidations so hot
187
181
 
188
182
  See [`docs/l1.md`](docs/l1.md) for the full consistency model, stats, events, method options, and failure modes.
189
183
 
190
- ## How it works
191
-
192
- Think of the primary as a shared cupboard and the workers as people borrowing from it. A namespace names one cupboard. Workers with the same namespace share its contents.
193
-
194
- `new LRUCacheClustered(...)` branches at construction:
195
-
196
- - **In the primary** (`cluster.isPrimary === true`), the instance owns and operates on the in-process `LRUCache` for its namespace directly, without IPC.
197
- - **In a worker**, every operation becomes a typed IPC request to the primary; the returned Promise resolves with the response.
198
-
199
- Instances in different workers that share a `namespace` operate on the same primary-side cache. Those instances should agree on cache options (`max`, `ttl`, `allowStale`, ...): reusing a namespace with conflicting options throws rather than silently keeping whichever process initialized it first.
200
-
201
- > **Initialization semantics.** In a worker, `new LRUCacheClustered(...)` eagerly sends the `init` message, but `cache.ready` is ordering-only and intentionally swallows init failure. Use `await cache.healthCheck()` or `await LRUCacheClustered.getInstance(...)` when startup should fail fast if the primary cannot register the namespace.
202
-
203
184
  ## Performance profile
204
185
 
205
186
  Sharing saves duplicate cache storage, but asking another process for a value takes time. A small local cache can speed up repeated reads, at the cost of extra copies and a brief stale-data window.
@@ -254,7 +235,7 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
254
235
 
255
236
  > **`failsafe: 'resolve'` caveat.** Most single-result operations return `undefined` on an IPC timeout with `'resolve'`, even when their declared return type differs. `mGet()` can return an empty or partial map. `fetch()`, `getInstance()`, and `healthCheck()` reject on IPC timeouts. For `get` / `peek` that is natural; for `has` / `set` / `delete` / `incr` / `decr` / `size` it can surprise callers (`undefined + 1 === NaN`). Use `'reject'` if typed-shape correctness on timeout matters.
256
237
 
257
- > **Size-bounded caches.** When you use `maxSize` or `maxEntrySize`, provide `size` on every write path (`set`, `setIfAbsent`, `mSet`, `fetch`, `memoize`, and the first `incr` / `decr` for a counter key). `sizeCalculation` does not cross IPC, so the primary cannot infer it for you.
238
+ > **Size-bounded caches.** When you use `maxSize` or `maxEntrySize`, provide `size` on every write path (`set`, `setIfAbsent`, `mSet`, `fetch`, `memoize`, and the first `incr` / `decr` for a counter key). `sizeCalculation` does not cross IPC, so the primary cannot infer it for you. `maxEntrySize` cannot exceed `maxSize`. Oversized `set()` and `setIfAbsent()` calls (`size > maxEntrySize`) return `false` without incrementing `sets`, oversized `setIfAbsent()` preserves readable stale entries under `allowStale` + `noDeleteOnStaleGet`, and oversized `incr()` / `decr()` reject with `RangeError` without deleting an existing counter. When `ttlAutopurge: true` is set, TTL values cannot exceed Node.js's 32-bit timer limit (`2_147_483_646` ms).
258
239
 
259
240
  > **Fail-fast startup.** `LRUCacheClustered.getInstance()` and `cache.healthCheck()` always reject if the primary cannot answer, regardless of `failsafe`, so you can use them as hard startup checks.
260
241
 
@@ -266,8 +247,6 @@ The same methods work in the primary and in workers. Await shared-cache operatio
266
247
 
267
248
  ### Static
268
249
 
269
- These helpers set up the shared cache before you start using it.
270
-
271
250
  | Method | Description |
272
251
  | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273
252
  | `LRUCacheClustered.bootstrap()` | Installs the primary-side cluster listener immediately. Useful when you want an explicit bootstrap call instead of relying on module import side effects. |
@@ -276,17 +255,15 @@ These helpers set up the shared cache before you start using it.
276
255
 
277
256
  ### Core
278
257
 
279
- Store a value, read it back, check whether it exists, or remove it.
280
-
281
- | Method | Returns | Notes |
282
- | --------------------------------------------- | ------------------------- | -------------------------------------------------------------- |
283
- | `get(key, { bypassL1? })` | `Promise<V \| undefined>` | |
284
- | `set(key, value, { ttl?, size?, updateL1? })` | `Promise<boolean>` | `updateL1` populates the caller's L1 after a successful write. |
285
- | `setIfAbsent(key, value, { ttl?, size? })` | `Promise<boolean>` | Atomic on the primary. `false` if the key already exists. |
286
- | `delete(key)` | `Promise<boolean>` | |
287
- | `has(key, { bypassL1? })` | `Promise<boolean>` | |
288
- | `peek(key, { bypassL1? })` | `Promise<V \| undefined>` | Does not update LRU position. |
289
- | `clear()` | `Promise<void>` | Clears the primary cache and this instance's L1. |
258
+ | Method | Returns | Notes |
259
+ | --------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------ |
260
+ | `get(key, { bypassL1? })` | `Promise<V \| undefined>` | |
261
+ | `set(key, value, { ttl?, size?, updateL1? })` | `Promise<boolean>` | Returns `false` if `size > maxEntrySize` prevents admission. `updateL1` populates the caller's L1 after admission. |
262
+ | `setIfAbsent(key, value, { ttl?, size? })` | `Promise<boolean>` | Atomic on the primary. `false` if the key already exists. |
263
+ | `delete(key)` | `Promise<boolean>` | |
264
+ | `has(key, { bypassL1? })` | `Promise<boolean>` | |
265
+ | `peek(key, { bypassL1? })` | `Promise<V \| undefined>` | Does not update LRU position. |
266
+ | `clear()` | `Promise<void>` | Clears the primary cache and this instance's L1. |
290
267
 
291
268
  ### Multi
292
269
 
@@ -325,35 +302,31 @@ Count events without workers overwriting each other, or load a missing value onc
325
302
 
326
303
  ### Local L1
327
304
 
328
- These controls affect the extra cache inside this process. They help you see whether local reads are saving trips to the primary.
329
-
330
- | Method / event | Returns / payload | Notes |
331
- | ------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------- |
332
- | `localStats()` | `L1Stats \| undefined` | `undefined` when local L1 is disabled. |
333
- | `clearLocal()` | `void` | Local-only flush. |
334
- | `invalidateLocal(key)` | `void` | Local-only single-key invalidation. |
335
- | `withoutLocal()` | `LRUCacheClustered<K, V>` | Bypass view for `get`, `has`, `peek`, `mGet`, and `fetch`; writes pass through normally. |
336
- | `on('l1:hit' \| 'l1:miss' \| 'l1:set', listener)` | `{ namespace, key }` | Key is the original cache key, not an internal encoded key. |
337
- | `on('l1:invalidate', listener)` | `{ namespace, key }` | `key` may be `'*'` for namespace-wide invalidation. |
338
- | `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` also fires when an expired or version-stale local entry is rejected. |
339
- | `off(event, listener)` / `once(event, listener)` | `this` | Standard event helpers. |
305
+ | Method / event | Returns / payload | Notes |
306
+ | ------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
307
+ | `localStats()` | `L1Stats \| undefined` | `undefined` when local L1 is disabled. |
308
+ | `clearLocal()` | `void` | Local-only flush. |
309
+ | `invalidateLocal(key)` | `void` | Local-only single-key invalidation. |
310
+ | `withoutLocal()` | `LRUCacheClustered<K, V>` | Bypass view for `get`, `has`, `peek`, `mGet`, and `fetch` (including local in-flight dedup); chaining `on`/`off`/`once` preserves the view. |
311
+ | `on('l1:hit' \| 'l1:miss' \| 'l1:set', listener)` | `{ namespace, key }` | Key is the original cache key, not an internal encoded key. |
312
+ | `on('l1:invalidate', listener)` | `{ namespace, key }` | `key` may be `'*'` for namespace-wide invalidation. |
313
+ | `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` also fires when an expired or version-stale local entry is rejected. |
314
+ | `off(event, listener)` / `once(event, listener)` | `this` | Standard event helpers. |
340
315
 
341
316
  ### Lifecycle, metrics, tunables
342
317
 
343
- Check the cache, inspect its activity, change its limits, or remove its namespace.
344
-
345
- | Method | Returns | Notes |
346
- | ---------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
347
- | `getRemainingTTL(key)` | `Promise<number>` | ms until expiry. `Infinity` for keys with no TTL; `0` for missing keys. |
348
- | `purgeStale()` | `Promise<boolean>` | Removes expired entries. |
349
- | `healthCheck()` | `Promise<void>` | Verifies that the primary can resolve the namespace and answer requests. |
350
- | `stats()` | `Promise<Stats>` | `{ hits, misses, sets, deletes, evictions, size, namespace }`. |
351
- | `destroy()` | `Promise<boolean>` | Removes the namespace cache, stats, and primary-side coordination state. Later use of the same instance recreates it with the original options. |
352
- | `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
353
- | `ready` | `Promise<void>` | Waits for worker initialization but swallows failures. Use `getInstance()` when initialization errors should reject. |
354
- | `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves primary entries and remaining TTL metadata, then clears this instance's L1. |
355
- | `ttl(value?)` | `Promise<number>` | Getter and setter. Setter clears this instance's L1. |
356
- | `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
318
+ | Method | Returns | Notes |
319
+ | ---------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
320
+ | `getRemainingTTL(key)` | `Promise<number>` | ms until expiry. `Infinity` for keys with no TTL; `0` for missing keys. |
321
+ | `purgeStale()` | `Promise<boolean>` | Removes expired entries. |
322
+ | `healthCheck()` | `Promise<void>` | Verifies that the primary can resolve the namespace and answer requests. |
323
+ | `stats()` | `Promise<Stats>` | `{ hits, misses, sets, deletes, evictions, size, namespace }`. |
324
+ | `destroy()` | `Promise<boolean>` | Removes the namespace cache, stats, and primary-side coordination state. Later use of the same instance recreates it with the original options. |
325
+ | `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
326
+ | `ready` | `Promise<void>` | Waits for worker initialization but swallows failures. Use `getInstance()` when initialization errors should reject. |
327
+ | `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves primary entries, remaining TTLs, and non-expiring entries, then clears this instance's L1. |
328
+ | `ttl(value?)` | `Promise<number>` | Getter and setter. Validates non-negative integers (rejecting `0` on TTL-only caches and timer-overflow values with `ttlAutopurge`) and clears L1. |
329
+ | `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
357
330
 
358
331
  ## Compression and codecs
359
332
 
@@ -386,9 +359,7 @@ await cache.get('user:42'); // decoded back to { id: 42, name: 'ada' }
386
359
 
387
360
  ## `memoize` helper
388
361
 
389
- Give a function a memory. Calling it again with the same cache key can reuse the previous result instead of repeating a database query or API request.
390
-
391
- `memoize(cache, fn, keyFn, opts)` calls `cache.fetch()` under the hood. `keyFn` must include every input that can change the result, including tenant or permission context when relevant.
362
+ `memoize(cache, fn, keyFn, opts)` accepts either `LRUCacheClustered` or a `WrappedCache` from `wrap()` and calls `cache.fetch()` under the hood. `keyFn` must include every input that can change the result, including tenant or permission context when relevant.
392
363
 
393
364
  ```ts
394
365
  import { LRUCacheClustered, memoize } from '@0xdoublesharp/lru-cache-clustered';
@@ -435,8 +406,6 @@ A missing key is normal. A failed operation is different: handle its rejected pr
435
406
 
436
407
  ## Debugging
437
408
 
438
- Turn on logs to see whether workers are reaching the primary and which requests they send.
439
-
440
409
  ```sh
441
410
  DEBUG=lru-cache-clustered-* node app.js
442
411
  ```
@@ -449,18 +418,14 @@ Available namespaces:
449
418
 
450
419
  ## Migration
451
420
 
452
- Existing applications can move to the scoped package name while keeping the compatibility alias during the transition.
453
-
454
421
  `LRUCacheClustered` is the canonical class; `LRUCacheForClustersAsPromised` remains an alias. The [migration guide](./docs/migration.md) maps the older methods, options, and package name. The [changelog](./CHANGELOG.md) records release-specific changes.
455
422
 
456
423
  ## Development
457
424
 
458
- Clone the project, install its dependencies, and run the checks before changing code. The examples are small servers you can use to explore the behavior yourself.
459
-
460
425
  For development, use a current Node.js 22 LTS patch release, at least 22.13, or Node.js 24 LTS. Use the pnpm version recorded in `package.json`; the runtime minimum for applications remains Node.js 22.
461
426
 
462
427
  ```sh
463
- git clone https://github.com/doublesharp/lru-cache-clustered.git
428
+ git clone https://github.com/0xdoublesharp/lru-cache-clustered.git
464
429
  cd lru-cache-clustered
465
430
  corepack enable
466
431
  pnpm install --frozen-lockfile
@@ -473,6 +438,7 @@ pnpm check
473
438
  | `pnpm test` | Unit, fuzz, and real cluster-worker tests. |
474
439
  | `pnpm test:coverage` | Text and LCOV reports in `coverage/`; requires 100% source statements, branches, functions, and lines. |
475
440
  | `pnpm build` | ESM and CommonJS bundles with TypeScript declarations in `dist/`. |
441
+ | `pnpm formal` | Run TLA+ (TLC) model checks and Lean 4 proofs under [`formal/`](./formal/README.md). |
476
442
  | `pnpm bench` | Compare worker reads with and without local L1. |
477
443
  | `pnpm example:users` | Start the shared user-cache example. |
478
444
 
@@ -480,8 +446,10 @@ pnpm check
480
446
 
481
447
  When changing cache behavior, add a regression test that retains the same cache instances and checks the resulting values. For L1 changes, verify warm hits, invalidation, and expiration. Cluster tests use child processes under both JSON and advanced serialization.
482
448
 
483
- Dependency resolution waits seven days after publication through `minimumReleaseAge` in `pnpm-workspace.yaml`. Use frozen lockfile installs for reproducible checks. Release preparation with `pnpm prepare:publish` creates scoped and legacy package directories under `dist-publish/`; the [publishing workflow](./.github/workflows/npm-publish.yml) handles publication.
449
+ Dependency resolution waits seven days after publication through `minimumReleaseAge` in `pnpm-workspace.yaml`. Use frozen lockfile installs for reproducible checks. The [dependency update notes](./docs/dependency-updates.md) describe security overrides and the import-plugin compatibility patch.
450
+
451
+ Release preparation with `pnpm prepare:publish` creates scoped and legacy package directories under `dist-publish/`. Pushing a `vX.Y.Z` tag matching the version in `package.json` triggers the [publishing workflow](./.github/workflows/npm-publish.yml), which runs the package checks and publishes both names to npm with provenance through GitHub OIDC.
484
452
 
485
453
  ## License
486
454
 
487
- You can use, modify, and distribute this package under the MIT license. See [LICENSE](./LICENSE) for the terms.
455
+ [MIT](./LICENSE).
@@ -1 +1 @@
1
- {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../src/codec.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../src/codec.ts"],"names":[],"mappings":"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"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var we=Object.create;var K=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Pe=(t,e)=>{for(var n in e)K(t,n,{get:e[n],enumerable:!0})},J=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Le(e))!Re.call(t,i)&&i!==n&&K(t,i,{get:()=>e[i],enumerable:!(s=Se(e,i))||s.enumerable});return t};var E=(t,e,n)=>(n=t!=null?we(xe(t)):{},J(e||!t||!t.__esModule?K(n,"default",{value:t,enumerable:!0}):n,t)),Oe=t=>J(K({},"__esModule",{value:!0}),t);var tt={};Pe(tt,{LRUCacheClustered:()=>_,LRUCacheForClustersAsPromised:()=>_,default:()=>et,memoize:()=>ke,wrap:()=>ye});module.exports=Oe(tt);var w=E(require("cluster"),1),ge=require("crypto"),ve=require("events");var P=E(require("cluster"),1),j=E(require("debug"),1),ae=require("lru-cache");var ne=E(require("debug"),1);var b="lcfcap",x="lru-cache-clustered";function Q(t){return ee(t,0,new Set)}function ee(t,e,n){if(t instanceof Error){if(n.has(t))return{name:t.name,message:"[circular cause]"};n.add(t);let s={name:t.name,message:t.message};t.stack&&(s.stack=t.stack);let i=t.code;(typeof i=="string"||typeof i=="number")&&(s.code=i);let r=t.cause;return r!==void 0&&(e+1>=8?s.cause={name:"Error",message:"[cause chain truncated]"}:s.cause=ee(r,e+1,n)),s}return{name:"Error",message:typeof t=="string"?t:String(t)}}function W(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),t.code!==void 0&&(e.code=t.code),t.cause!==void 0&&(e.cause=W(t.cause)),e}function te(t){if(typeof t!="object"||t===null||t.source!==b||typeof t.namespace!="string"||typeof t.version!="number")return!1;let e=t.push;return e==="l1:invalidate"||e==="l1:invalidate-namespace"}var Ce=Symbol.for("lru-cache-clustered.invalidations"),T=globalThis[Ce]??=new Map,Ee=(0,ne.default)(`${x}-invalidations`);function se(t,e){let n=T.get(t);return n||T.set(t,n=new Set),n.add(e),()=>{n.delete(e),n.size===0&&T.get(t)===n&&T.delete(t)}}function N(t){for(let e of T.get(t.namespace)??[])try{e(t)}catch(n){Ee("local invalidation subscriber failed: %s",n)}}var I=(0,j.default)(`${x}-primary`),Te=(0,j.default)(`${x}-messages`),ze=3e4,Ie=Symbol.for("lru-cache-clustered.primary"),m=globalThis[Ie]??={caches:new Map,stats:new Map,fetchLocks:new Map,versions:new Map,clusterListenerInstalled:!1,nextFetchToken:0,nextMutationVersion:0},v=m.caches,U=m.stats,Ae=m.versions,k=m.fetchLocks;function A(t){return m.versions.get(t)??0}function y(t){let e=(m.nextMutationVersion??0)+1;return m.nextMutationVersion=e,m.versions.set(t,e),e}function ue(t){return{namespace:t,hits:0,misses:0,sets:0,deletes:0,evictions:0,size:0}}function g(t){let e=U.get(t);return e||(e=ue(t),U.set(t,e)),e}function le(t){let e=t;return{max:e.max,maxSize:e.maxSize,maxEntrySize:e.maxEntrySize,ttl:e.ttl,allowStale:e.allowStale,updateAgeOnGet:e.updateAgeOnGet,updateAgeOnHas:e.updateAgeOnHas,noDeleteOnStaleGet:e.noDeleteOnStaleGet,ttlAutopurge:e.ttlAutopurge}}function d(t,e){let n=v.get(t);return n||V(t,e.cacheOptions)}function Ve(t,e,n){if(!n)return;let s=le(e),i=[];for(let[r,o]of Object.entries(n))o!==void 0&&s[r]!==o&&i.push(`${r}=${String(s[r])} (existing) != ${String(o)} (incoming)`);if(i.length>0)throw new Error(`Conflicting options for namespace '${t}': ${i.join(", ")}`)}function h(t,e){if(e==null)throw new TypeError(`${t} must not be null or undefined`);return e}function z(t){let e={};return t.ttl!==void 0&&(e.ttl=t.ttl),t.size!==void 0&&(e.size=t.size),t.noUpdateTTL&&(e.noUpdateTTL=!0),Object.keys(e).length>0?e:void 0}function Ke(t,e){let n=t.info(e);return typeof n?.size=="number"?n.size:void 0}function Ne(t){let e=k.get(t);return e||(e=new Map,k.set(t,e)),e}function R(t,e){let n=k.get(t)?.delete(e)??!1;return O(t),n}function O(t){k.get(t)?.size===0&&k.delete(t)}function ie(t){for(let[e,n]of k){for(let[s,i]of n){for(let[r,o]of i.followers)o===t&&i.followers.delete(r);i.ownerWorkerId===t&&(i.token=void 0),!i.token&&i.followers.size===0&&n.delete(s)}O(e)}}function ce(t,e){let n={...t,dispose:(i,r,o)=>{o==="evict"&&(e.evictions+=1,R(e.namespace,r),m.activeEvictions?.namespace===e.namespace&&m.activeEvictions.keys.push(r))}},s=n.max===void 0&&n.maxSize===void 0&&n.ttl===void 0?{...n,max:1e3}:n;return new ae.LRUCache(s)}function V(t,e){let n=v.get(t);if(n)Ve(t,n,e);else{let s=ue(t);U.set(t,s),n=ce(e??{},s),v.set(t,n),I(`Created LRUCache for namespace '${t}'`)}return n}function Ue(t,e,n={}){switch(e.op){case"init":{let s=!v.has(t),i=V(t,e.options);return{namespace:t,isNew:s,max:i.max,version:A(t)}}case"healthCheck":V(t,e.cacheOptions);return;case"destroy":{let s=v.delete(t),i=U.delete(t),r=k.delete(t),o=s||i||r;return o&&y(t),o}case"get":{let s=h("cache key",e.key),i=e.existingOnly?v.get(t):d(t,e);if(!i)return;let r=i.get(s),o=g(t);return r!==void 0?o.hits+=1:o.misses+=1,r}case"set":{let s=d(t,e),i=h("cache key",e.key);return s.set(i,h("cache value",e.value),z({ttl:e.ttl,size:e.size})),R(t,i),g(t).sets+=1,y(t),!0}case"setIfAbsent":{let s=d(t,e),i=h("cache key",e.key);return s.peek(i,{allowStale:!1})!==void 0?!1:(s.set(i,h("cache value",e.value),z({ttl:e.ttl,size:e.size})),R(t,i),g(t).sets+=1,y(t),!0)}case"delete":{let s=d(t,e),i=h("cache key",e.key),r=s.delete(i),o=R(t,i);return r&&(g(t).deletes+=1),(r||o)&&y(t),r}case"has":return d(t,e).has(h("cache key",e.key));case"peek":return d(t,e).peek(h("cache key",e.key));case"getRemainingTTL":return d(t,e).getRemainingTTL(h("cache key",e.key));case"clear":d(t,e).clear(),k.delete(t),y(t);return;case"mGet":{let s=d(t,e),i=g(t);return e.keys.map(r=>{let o=s.get(h("cache key",r));return o!==void 0?i.hits+=1:i.misses+=1,[r,o]})}case"mSet":{let s=d(t,e),i=g(t),r=e.entries.map(([a,u,l])=>({key:h("cache key",a),value:h("cache value",u),entryOpts:l})),o=!1;try{for(let{key:a,value:u,entryOpts:l}of r)s.set(a,u,z({ttl:l?.ttl??e.ttl,size:l?.size??e.size})),R(t,a),o=!0,i.sets+=1}finally{(o||r.length===0)&&y(t)}return}case"mDelete":{let s=d(t,e),i=g(t),r=e.keys.map(o=>h("cache key",o));for(let o of r)s.delete(o)&&(i.deletes+=1),R(t,o);y(t);return}case"keys":return[...d(t,e).keys()];case"values":return[...d(t,e).values()];case"entries":return[...d(t,e).entries()];case"dump":return d(t,e).dump();case"load":{let s=d(t,e),i=e.entries.map(([r,o])=>{let a=h("cache key",r);return h("cache value",o.value),[a,o]});k.delete(t);try{s.load(i)}finally{y(t)}return}case"size":return d(t,e).size;case"stats":{let s=d(t,e),i=g(t);return i.size=s.size,{...i}}case"purgeStale":{let s=d(t,e).purgeStale();return s&&y(t),s}case"incr":case"decr":{let s=d(t,e),i=h("cache key",e.key),r=s.peek(i,{allowStale:!1}),o=r!==void 0,a=typeof r=="number"?r:0,u=(e.amount??1)*(e.op==="decr"?-1:1),l=a+u,f=e.size??(o?Ke(s,i):void 0),c=z(o?{size:f,noUpdateTTL:!0}:{ttl:e.ttl,size:f});return s.set(i,l,c),R(t,i),g(t).sets+=1,y(t),l}case"fetchClaim":{let s=h("cache key",e.key),i=k.get(t)?.get(s);if(e.generation!==void 0&&i?.generation!==e.generation){let u=v.get(t)?.get(s);if(u!==void 0)return{kind:"value",value:u};throw new Error("Fetch was superseded by a cache mutation and no current value remains")}let r=d(t,e),o=Date.now();if(!e.forceRefresh){let u=r.get(s),l=g(t);if(u!==void 0)return e.requestId&&i?.followers.delete(e.requestId),i&&!i.token&&i.followers.size===0&&(k.get(t)?.delete(s),O(t)),l.hits+=1,{kind:"value",value:u};if(l.misses+=1,i?.token&&o-i.claimedAt<ze)return e.requestId&&i.followers.set(e.requestId,n.workerId),e.requestId?{kind:"follower",generation:i.generation}:{kind:"follower"}}let a=`fetch-${++m.nextFetchToken}`;return Ne(t).set(s,{token:a,generation:i?.generation??a,followers:i?.followers??new Map,ownerWorkerId:n.workerId,claimedAt:o}),{kind:"leader",token:a}}case"fetchStore":{let s=h("cache key",e.key),i=k.get(t),r=i?.get(s);return!r||r.token!==e.token?!1:(d(t,e).set(s,h("cache value",e.value),z({ttl:e.ttl,size:e.size})),i?.delete(s),O(t),g(t).sets+=1,y(t),!0)}case"fetchAbort":{let s=h("cache key",e.key),i=k.get(t),r=i?.get(s);return!r||r.token!==e.token?!1:(r.token=void 0,r.followers.size===0&&i?.delete(s),O(t),!0)}case"fetchRelease":{let s=h("cache key",e.key),i=k.get(t),r=i?.get(s);if(!r||e.generation!==void 0&&r.generation!==e.generation)return!1;let o=r.followers.delete(e.requestId);return!r.token&&r.followers.size===0&&i?.delete(s),O(t),o}case"max":{let s=d(t,e);if(typeof e.value=="number"&&e.value!==s.max){let i=g(t),r={...le(s),max:e.value},o=ce(r,i);return o.load(s.dump()),v.set(t,o),y(t),o.max}return s.max}case"ttl":{let s=d(t,e),i=s.ttl;return typeof e.value=="number"&&e.value!==i&&(s.ttl=e.value,y(t)),s.ttl}case"allowStale":{let s=d(t,e);return typeof e.value=="boolean"&&(s.allowStale=e.value),s.allowStale}default:{let s=e.op;throw new Error(`unhandled op: ${s}`)}}}var q=new Set(["destroy","clear","purgeStale","mSet","mDelete","load","max","ttl"]);function Me(t,e,n){if(q.has(e.op))return{source:b,push:"l1:invalidate-namespace",namespace:t,version:n};let s=e.key;if(s!=null)return{source:b,push:"l1:invalidate",namespace:t,key:s,version:n}}function De(t){for(let e of Object.values(P.default.workers??{}))if(!(!e||!e.isConnected()))try{e.send(t,n=>{n&&I(`l1 broadcast to worker ${e.id} failed: %s`,n)})}catch(n){I(`l1 broadcast to worker ${e.id} failed: %s`,n)}}var Fe=new Set(["set","setIfAbsent","mSet","load","incr","decr","fetchStore","max"]);function re(t){N(t),De(t)}function $(t,e,n={}){let s=A(t),i=Fe.has(e.op)?{namespace:t,keys:[]}:void 0,r=m.activeEvictions;m.activeEvictions=i;let o,a;try{o=Ue(t,e,n)}finally{if(m.activeEvictions=r,a=A(t),a!==s){let l=Me(t,e,a);if(l&&re(l),l?.push!=="l1:invalidate-namespace")for(let f of i?.keys??[])re({source:b,push:"l1:invalidate",namespace:t,key:f,version:a})}e.op==="destroy"&&Ae.delete(t)}let u={value:o,version:a};if(i?.keys.length&&(u.evictedKeys=i.keys),e.includeTTL){let l=e.op==="mGet"?e.keys:"key"in e?[e.key]:[],f=v.get(t);u.ttls=l.map(c=>{let p=f?.getRemainingTTL(h("cache key",c))??0;return Number.isFinite(p)?p:null})}return u}function _e(t,e={}){if(typeof t!="object"||t===null)return G(t,"invalid request: not an object");if(!de(t))return G(t,"invalid request: missing required fields");try{let n=$(t.namespace,t,e);return{id:t.id,source:b,ok:!0,...n}}catch(n){return G(t,n)}}function G(t,e){return{id:typeof t=="object"&&t!==null&&typeof t.id=="string"?t.id:"",source:b,ok:!1,error:Q(e)}}function H(){if(!m.clusterListenerInstalled){m.clusterListenerInstalled=!0,P.default.on("disconnect",t=>{ie(t.id)}),P.default.on("exit",t=>{ie(t.id)}),P.default.on("fork",t=>{oe(t)});for(let t of Object.values(P.default.workers??{}))t&&oe(t)}}function oe(t){t.on("message",e=>{if(!de(e))return;Te(`primary <- worker ${t.id}`,e);let n=_e(e,{workerId:t.id});if(t.isConnected())try{t.send(n,s=>{s&&I(`worker ${t.id} send failed (likely disconnected): %s`,s)})}catch(s){I(`worker ${t.id} send failed (likely disconnected): %s`,s)}})}function de(t){return typeof t=="object"&&t!==null&&t.source===b&&typeof t.id=="string"&&typeof t.namespace=="string"&&typeof t.op=="string"}var C=require("timers"),he=E(require("debug"),1);var fe=(0,he.default)(`${x}-messages`),We=Symbol.for("lru-cache-clustered.worker"),Ge=globalThis[We]??={nextRequestId:0};function je(t){let e=new Map,n=new Map;t.on("message",i=>{if(qe(i)){let r=e.get(i.id);if(!r)return;e.delete(i.id),r(i);return}if(te(i)){let r=n.get(i.namespace);if(!r)return;for(let o of r)try{o(i)}catch(a){fe("invalidation handler threw: %o",a)}return}});function s(i,r){let o=String(++Ge.nextRequestId),a={id:o,namespace:i.namespace,source:b,...r};return new Promise((u,l)=>{let f=(0,C.setTimeout)(()=>{e.delete(o),i.failsafe==="reject"?l(new Error("IPC timeout")):u({value:void 0,version:0})},i.timeout);e.set(o,c=>{(0,C.clearTimeout)(f),c.ok?u({value:c.value,version:c.version??0,ttls:c.ttls,evictedKeys:c.evictedKeys}):l(W(c.error))}),fe("worker -> primary",a);try{t.send(a,c=>{!c||!e.delete(o)||((0,C.clearTimeout)(f),l(c))})}catch(c){(0,C.clearTimeout)(f),e.delete(o),l(c instanceof Error?c:new Error(String(c)))}})}return{async sendToPrimary(i,r){return(await s(i,r)).value},sendToPrimaryWithMeta:(i,r)=>s(i,r),subscribeInvalidations(i,r){let o=n.get(i);return o||(o=new Set,n.set(i,o)),o.add(r),()=>{let a=n.get(i);a&&(a.delete(r),a.size===0&&n.delete(i))}}}}function qe(t){if(typeof t!="object"||t===null||t.source!==b||typeof t.id!="string"||typeof t.ok!="boolean")return!1;if(t.ok===!1){let e=t.error;for(let n=0;;n++){if(n>8||typeof e!="object"||e===null||typeof e.name!="string"||typeof e.message!="string")return!1;if(e=e.cause,e===void 0)break}}return!0}var B;function X(){if(!B){if(typeof process.send!="function")throw new Error("lru-cache-clustered: worker IPC client requested in a process without `process.send` (not a cluster worker).");let t=process.send.bind(process);B=je({send:(e,n)=>t(e,n),on:(e,n)=>process.on(e,n)})}return B}var be=require("lru-cache"),me=new WeakMap,$e=0;function pe(t){let e=me.get(t);return e===void 0&&(e=++$e,me.set(t,e)),e}function D(t){switch(typeof t){case"string":return`s:${t}`;case"number":return`n:${t}`;case"boolean":return`b:${t}`;case"bigint":return`i:${t.toString()}`;case"symbol":throw new Error("L1 does not support symbol keys");case"function":return`f:${pe(t)}`;default:return`o:${pe(t)}`}}var He=()=>({enabled:!0,hits:0,misses:0,sets:0,invalidations:0,evictions:0,staleHits:0,size:0,ipcAvoided:0}),M=class{#t;#a;#r=0;#e=new Map;#s=He();#i;constructor(e){this.#i=e.emit??(()=>{}),this.#a=e.ttl;let n={max:e.max??1e3,ttl:e.ttl,updateAgeOnGet:e.updateAgeOnGet??!0,allowStale:e.allowStale??!1,maxSize:e.maxSize,...e.maxSize!==void 0?{sizeCalculation:()=>1}:{},dispose:(s,i,r)=>{r==="evict"&&(this.#s.evictions+=1,this.#i("evict",{key:s.key??i,reason:"lru"}))}};this.#t=new be.LRUCache(n)}get(e,n=e,s="get"){let i={},r=s==="get"?this.#t.get(e,{status:i}):this.#t.peek(e,{allowStale:s==="has"?!1:this.#t.allowStale});if(s==="peek"&&r&&this.#t.getRemainingTTL(e)<0&&(i.returnedStale=!0),!r){this.#s.misses+=1,this.#i("miss",{key:n});return}if(r.version<this.#r||r.expiresAt!==void 0&&globalThis.performance.now()>=r.expiresAt){this.#t.delete(e),this.#s.misses+=1,this.#s.staleHits+=1,this.#i("stale-hit",{key:r.key}),this.#i("miss",{key:n});return}return i.returnedStale&&(this.#s.staleHits+=1,this.#i("stale-hit",{key:r.key})),this.#s.hits+=1,this.#s.ipcAvoided+=1,this.#i("hit",{key:r.key}),r.value}set(e,n,s,i,r=e,o){if(s<this.#r||o&&(o.cancelled||s<o.version))return;let a=this.#u(i);if(a===!1)return;let u=i!==void 0&&Number.isFinite(i)?globalThis.performance.now()+i:void 0;this.#t.set(e,{value:n,version:s,expiresAt:u,key:r},a),this.#s.sets+=1,this.#i("set",{key:r,version:s})}trackRead(e){let n=this.#e.get(e);n||(n=new Set,this.#e.set(e,n));let s={version:this.#r,cancelled:!1,release:()=>{n.delete(s),n.size===0&&this.#e.get(e)===n&&this.#e.delete(e)}};return n.add(s),s}delete(e,n=e,s=!0,i){for(let o of this.#e.get(e)??[])i===void 0?o.cancelled=!0:o.version=Math.max(o.version,i);let r=this.#t.peek(e,{allowStale:!0});r&&(i===void 0||r.version<i)&&this.#t.delete(e)&&(this.#s.invalidations+=1,s&&this.#i("invalidate",{key:n,reason:"self"}))}clear(e=!0,n){if(n===void 0)for(let i of this.#e.values())for(let r of i)r.cancelled=!0;else this.advanceLatestSeen(n);let s=!1;if(n===void 0)s=this.#t.size>0,this.#t.clear();else for(let[i,r]of this.#t.entries())r.version<n&&(this.#t.delete(i),s=!0);s&&(this.#s.invalidations+=1),e&&this.#i("invalidate",{key:"*",reason:"clear"})}advanceLatestSeen(e){e>this.#r&&(this.#r=e)}latestSeen(){return this.#r}stats(){return{...this.#s,size:this.#t.size}}destroy(){this.clear(!1)}#u(e){if(e===void 0||!Number.isFinite(e))return;let n=this.#a===void 0?e:Math.min(e,this.#a);return n>0?{ttl:n}:!1}};function ke(t,e,n,s){return async(...i)=>{let r=n(...i);return t.fetch(r,()=>e(...i),s)}}function ye(t,e){let n=o=>e.encode(o),s=o=>e.decode(o);return{cache:t,namespace:t.namespace,ready:t.ready,async get(o,a){let u=await t.get(o,a);return u===void 0?void 0:await s(u)},async set(o,a,u){return t.set(o,await n(a),u)},async setIfAbsent(o,a,u){return t.setIfAbsent(o,await n(a),u)},has:(o,a)=>t.has(o,a),async peek(o,a){let u=await t.peek(o,a);return u===void 0?void 0:await s(u)},delete:o=>t.delete(o),getRemainingTTL:o=>t.getRemainingTTL(o),async mGet(o,a){let u=await t.mGet(o,a),l=new Map;for(let[f,c]of u)l.set(f,c===void 0?void 0:await s(c));return l},async mSet(o,a){let u=[];for(let l of o){let[f,c,p]=l;p===void 0?u.push([f,await n(c)]):u.push([f,await n(c),p])}return t.mSet(u,a)},mDelete:o=>t.mDelete(o),keys:()=>t.keys(),async values(){let o=await t.values(),a=[];for(let u of o)a.push(await s(u));return a},async entries(){let o=await t.entries(),a=[];for(let[u,l]of o)a.push([u,await s(l)]);return a},size:()=>t.size(),async*[Symbol.asyncIterator](){for(let[o,a]of await this.entries())yield[o,a]},clear:()=>t.clear(),destroy:()=>t.destroy(),healthCheck:()=>t.healthCheck(),purgeStale:()=>t.purgeStale(),stats:()=>t.stats(),async fetch(o,a,u){let l=await t.fetch(o,async f=>await n(await a(f)),u);return await s(l)}}}w.default.isPrimary&&H();var Be=5,Xe=5e3,Ye=1e3;function Ze(t,e){switch(t.op){case"set":case"mSet":case"mDelete":case"clear":case"load":case"incr":case"decr":return!0;case"delete":case"setIfAbsent":case"purgeStale":case"fetchStore":case"destroy":return e===!0;case"max":case"ttl":return typeof t.value=="number";default:return!1}}function Je(t,e,n,s){if(!Ze(e,s))return;if(q.has(e.op))return{source:b,push:"l1:invalidate-namespace",namespace:t,version:n};let i=e.key;if(i!=null)return{source:b,push:"l1:invalidate",namespace:t,key:i,version:n}}function Qe(t,e){if(t===void 0||t===!1)return;let n=t;if(n.enabled===!1)return;if(!n.experimental)throw new Error("localL1 is experimental. Pass `localL1: { experimental: true }` to opt in.");let s=e.ttl||1/0,i=n.ttl??Math.min(s*.1,Xe),r=Math.max(100,Math.floor(Math.min(i,s))),o=n.methods===void 0?{get:!0,has:!0,fetch:!0}:{get:n.methods.get===!0,has:n.methods.has===!0,fetch:n.methods.fetch===!0};return{max:n.max??Ye,maxSize:n.maxSize,ttl:r,updateAgeOnGet:n.updateAgeOnGet??!0,allowStale:n.allowStale??!1,invalidation:n.invalidation??"broadcast",methods:o}}function F(t){if(t!=null)try{return D(t)}catch{return}}var _=class t{namespace;timeout;failsafe;ready;#t;#a=new Map;#r=new ve.EventEmitter;#e;#s;#i;#u;#d=!1;constructor(e={}){this.namespace=e.namespace??"default",this.timeout=e.timeout??100,this.failsafe=e.failsafe==="reject"?"reject":"resolve";let{namespace:n,timeout:s,failsafe:i,noInit:r,localL1:o,...a}=e;this.#t=a;let u=Qe(e.localL1,a);this.#s=u?.methods??{get:!1,has:!1,fetch:!1},this.#i=u?.invalidation??"broadcast",u&&(this.#e=new M({max:u.max,maxSize:u.maxSize,ttl:u.ttl,updateAgeOnGet:u.updateAgeOnGet,allowStale:u.allowStale,emit:(l,f)=>{this.#r.emit(`l1:${l}`,{namespace:this.namespace,...f})}})),w.default.isPrimary?(V(this.namespace,this.#t),this.#e&&(this.#e.advanceLatestSeen(A(this.namespace)),this.#m()),this.ready=Promise.resolve(void 0)):e.noInit?this.ready=Promise.resolve(void 0):this.ready=this.#n({op:"init",options:this.#t},"reject").then(l=>{this.#e&&(this.#e.advanceLatestSeen(l.value.version),this.#m())},()=>{})}static async getInstance(e={}){let n=new t({...e,noInit:!0});if(w.default.isWorker){let s=await n.#n({op:"init",options:n.#t},"reject");n.#e&&(n.#e.advanceLatestSeen(s.value.version),n.#m())}return n}static bootstrap(){w.default.isPrimary&&H()}static getAllCaches(){if(w.default.isWorker)throw new Error("LRUCacheClustered.getAllCaches() must not be called from a worker");return v}getCache(){if(w.default.isWorker)throw new Error("LRUCacheClustered.getCache() must not be called from a worker");return v.get(this.namespace)}async get(e,n){let s=this.#e&&this.#s.get&&!n?.bypassL1;if(s){let r=this.#h(e);if(r!==void 0)return r}let i=s?this.#f(e):void 0;try{let r=await this.#n({op:"get",key:e,includeTTL:!!s},this.failsafe);return s&&r.value!==void 0&&this.#l(e,r.value,r,0,i),r.value}finally{i?.release()}}async set(e,n,s){this.#c(e);let i=this.#e&&s?.updateL1?this.#f(e):void 0;try{let r=await this.#n({op:"set",key:e,value:n,ttl:s?.ttl,size:s?.size,includeTTL:!!this.#e&&s?.updateL1},this.failsafe);return this.#e&&s?.updateL1&&r.value===!0&&this.#l(e,n,r,0,i),r.value}finally{i?.release()}}async delete(e){return this.#c(e),(await this.#n({op:"delete",key:e},this.failsafe)).value}async has(e,n){return this.#e&&this.#s.has&&!n?.bypassL1&&this.#h(e,"has")!==void 0?!0:(await this.#n({op:"has",key:e},this.failsafe)).value}async peek(e,n){let s=this.#e&&this.#s.get&&!n?.bypassL1;if(s){let r=this.#h(e,"peek");if(r!==void 0)return r}let i=s?this.#f(e):void 0;try{let r=await this.#n({op:"peek",key:e,includeTTL:!!s},this.failsafe);return s&&r.value!==void 0&&this.#l(e,r.value,r,0,i),r.value}finally{i?.release()}}async clear(){return this.#e?.clear(),(await this.#n({op:"clear"},this.failsafe)).value}async purgeStale(){return this.#e?.clear(),(await this.#n({op:"purgeStale"},this.failsafe)).value}async mGet(e,n){let s=new Map,i=this.#e&&this.#s.get&&!n?.bypassL1,r=i?[]:e;if(i)for(let a of e){let u=this.#h(a);u!==void 0?s.set(a,u):r.push(a)}if(r.length===0)return s;let o=i?new Map([...new Set(r)].map(a=>[a,this.#f(a)])):void 0;try{let a=await this.#n({op:"mGet",keys:r,includeTTL:!!i},this.failsafe);for(let[l,[f,c]]of(a.value??[]).entries()){let p=c===null?void 0:c;s.set(f,p),i&&p!==void 0&&this.#l(f,p,a,l,o?.get(f))}let u=new Map;for(let l of e)s.has(l)&&u.set(l,s.get(l));return u}finally{if(o)for(let a of o.values())a?.release()}}async mSet(e,n){this.#e?.clear();let s=[...e];return(await this.#n({op:"mSet",entries:s,ttl:n?.ttl,size:n?.size},this.failsafe)).value}async mDelete(e){return this.#e?.clear(),(await this.#n({op:"mDelete",keys:e},this.failsafe)).value}keys(){return this.#o({op:"keys"})}values(){return this.#o({op:"values"})}entries(){return this.#o({op:"entries"})}dump(){return this.#o({op:"dump"})}size(){return this.#o({op:"size"})}async incr(e,n,s){return this.#c(e),(await this.#n({op:"incr",key:e,amount:n,ttl:s?.ttl,size:s?.size},this.failsafe)).value}async decr(e,n,s){return this.#c(e),(await this.#n({op:"decr",key:e,amount:n,ttl:s?.ttl,size:s?.size},this.failsafe)).value}async allowStale(e){let n=await this.#o({op:"allowStale",value:e});return this.#t.allowStale=n,n}async max(e){let n=await this.#o({op:"max",value:e});return this.#t.max=n,e!==void 0&&this.#e?.clear(),n}async ttl(e){let n=await this.#o({op:"ttl",value:e});return this.#t.ttl=n,e!==void 0&&this.#e?.clear(),n}async getRemainingTTL(e){let n=await this.#o({op:"getRemainingTTL",key:e});return n===null?1/0:n}async setIfAbsent(e,n,s){return this.#c(e),(await this.#n({op:"setIfAbsent",key:e,value:n,ttl:s?.ttl,size:s?.size},this.failsafe)).value}async load(e){return this.#e?.clear(),(await this.#n({op:"load",entries:e},this.failsafe)).value}async destroy(){return this.#a.clear(),this.#u?.(),this.#u=void 0,this.#e?.destroy(),this.#o({op:"destroy"})}healthCheck(){return this.#p({op:"healthCheck"})}stats(){return this.#o({op:"stats"})}localStats(){return this.#e?.stats()}on(e,n){return this.#r.on(e,n),this}off(e,n){return this.#r.off(e,n),this}once(e,n){return this.#r.once(e,n),this}clearLocal(){this.#e?.clear()}invalidateLocal(e){this.#c(e)}withoutLocal(){let e;return e=new Proxy(this,{get(n,s){if(s==="withoutLocal")return()=>e;if(s==="get")return(r,o)=>n.get(r,{...o,bypassL1:!0});if(s==="has")return(r,o)=>n.has(r,{...o,bypassL1:!0});if(s==="peek")return(r,o)=>n.peek(r,{...o,bypassL1:!0});if(s==="mGet")return(r,o)=>n.mGet(r,{...o,bypassL1:!0});if(s==="fetch")return(r,o,a)=>n.fetch(r,o,{...a,bypassL1:!0});let i=Reflect.get(n,s,n);return typeof i=="function"?i.bind(n):i}}),e}async*[Symbol.asyncIterator](){let e=await this.entries();for(let n of e)yield n}async fetch(e,n,s){let i=this.#e&&this.#s.fetch&&!s?.bypassL1;if(!s?.forceRefresh){if(i){let p=this.#h(e);if(p!==void 0)return p}let c=this.#a.get(e);if(c)return c.promise}let r=i?this.#f(e):void 0,o,a=(0,ge.randomUUID)(),u,l=!1;o={promise:(async()=>{let c=s?.forceRefresh===!0;for(;;){l=!0;let p=await this.#n({op:"fetchClaim",key:e,forceRefresh:c,requestId:a,generation:u,includeTTL:!!i},"reject");l=!1;let S=p.value;if(S.kind==="value")return u=void 0,i&&this.#l(e,S.value,p,0,r),S.value;if(S.kind==="leader")try{let L=await n(e),Y=await this.#n({op:"fetchStore",includeTTL:!!i,key:e,token:S.token,value:L,ttl:s?.ttl,size:s?.size},"reject");if(!Y.value){let Z=await this.#p({op:"get",key:e,existingOnly:!0});if(Z===void 0)throw new Error("Fetch was superseded by a cache mutation and no current value remains");return Z}return u=void 0,i&&this.#l(e,L,Y,0,r),L}catch(L){try{await this.#p({op:"fetchAbort",key:e,token:S.token})}catch{}throw L}u=S.generation,c=!1,await new Promise(L=>setTimeout(L,Be))}})()},this.#a.set(e,o);try{return await o.promise}finally{if(this.#a.get(e)===o&&this.#a.delete(e),r?.release(),u!==void 0||l)try{await this.#p({op:"fetchRelease",key:e,generation:u,requestId:a})}catch{}}}#m(){if(!this.#e||this.#i!=="broadcast"||this.#u)return;let e=i=>this.#k(i),n=se(this.namespace,e),s=w.default.isPrimary?void 0:X().subscribeInvalidations(this.namespace,e);this.#u=()=>{n(),s?.()}}#k(e){try{this.#d||this.#r.emit("l1:invalidate",{namespace:this.namespace,key:e.push==="l1:invalidate"?e.key:"*",reason:"broadcast"})}finally{if(e.push==="l1:invalidate")try{this.#e.delete(D(e.key),e.key,!1,e.version)}catch{}else this.#e.clear(!1,e.version)}}#l(e,n,s,i=0,r){let o=F(e),a=s.ttls?.[i];if(o===void 0||a===void 0)return;let u=a===null?void 0:a-(globalThis.performance.now()-s.ttlStart);this.#e.set(o,n,s.version,u,e,r)}#f(e){let n=F(e);return n===void 0?void 0:this.#e.trackRead(n)}#h(e,n="get"){let s=F(e);return s===void 0?void 0:this.#e.get(s,e,n)}#c(e){if(!this.#e)return;let n=F(e);n!==void 0&&this.#e.delete(n,e)}#y(e,n,s){let i=Je(this.namespace,e,s,n);if(i){this.#d=!0;try{N(i)}finally{this.#d=!1}}}#b(e){if(this.#e)for(let n of e.evictedKeys??[])try{this.#e.delete(D(n),n,!1,e.version)}catch{}}#o(e){return this.#n(e,this.failsafe).then(n=>n.value)}#p(e){return this.#n(e,"reject").then(n=>n.value)}async#n(e,n){e.op!=="destroy"&&e.op!=="init"&&this.#m();let s=e.includeTTL?globalThis.performance.now():void 0,i={...e,cacheOptions:this.#t};if(w.default.isPrimary){this.#d=!0;try{let o=$(this.namespace,i);return this.#b(o),{...o,value:o.value,ttlStart:s}}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{this.#d=!1}}let r=await X().sendToPrimaryWithMeta({namespace:this.namespace,timeout:this.timeout,failsafe:n},i);return this.#b(r),this.#y(i,r.value,r.version),{...r,ttlStart:s}}};var et=_;0&&(module.exports={LRUCacheClustered,LRUCacheForClustersAsPromised,memoize,wrap});
1
+ "use strict";var Ie=Object.create;var D=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Me=(t,e)=>{for(var n in e)D(t,n,{get:e[n],enumerable:!0})},ae=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ne(e))!Ae.call(t,o)&&o!==n&&D(t,o,{get:()=>e[o],enumerable:!(r=Ve(e,o))||r.enumerable});return t};var ue=(t,e,n)=>(n=t!=null?Ie(Ke(t)):{},ae(e||!t||!t.__esModule?D(n,"default",{value:t,enumerable:!0}):n,t)),Ue=t=>ae(D({},"__esModule",{value:!0}),t);var st={};Me(st,{LRUCacheClustered:()=>_,LRUCacheForClustersAsPromised:()=>_,default:()=>nt,memoize:()=>Ee,wrap:()=>ze});module.exports=Ue(st);var Te=require("events");var m=ue(require("cluster"),1),ve=require("lru-cache");var le=ue(require("debug"),1),S="lcfcap",P=t=>(0,le.default)(`lru-cache-clustered-${t}`),E=()=>globalThis.performance.now(),De=8;function $(t,e=0,n=new Set){if(t instanceof Error){let{name:r,message:o,stack:s,code:i,cause:a}=t;if(n.has(t))return{name:r,message:"[circular cause]"};n.add(t);let u={name:r,message:o};return s&&(u.stack=s),(typeof i=="string"||typeof i=="number")&&(u.code=i),a!==void 0&&(u.cause=e+1>=De?{name:"Error",message:"[cause chain truncated]"}:$(a,e+1,n)),u}return{name:"Error",message:typeof t=="string"?t:String(t)}}function B(t){let{name:e,message:n,stack:r,code:o,cause:s}=t,i=new Error(n);return i.name=e,r&&(i.stack=r),o!==void 0&&(i.code=o),s!==void 0&&(i.cause=B(s)),i}function I(t){return!!t&&typeof t=="object"&&t.source===S}function ce(t){return I(t)&&typeof t.namespace=="string"&&Number.isFinite(t.version)&&(t.push==="l1:invalidate"||t.push==="l1:invalidate-namespace")}var We=Symbol.for("lru-cache-clustered.invalidations"),de=globalThis[We]??=new Map,Fe=P("invalidations");function V(t,e,n){let r=t.get(e);return r||t.set(e,r=new Set),r.add(n),()=>{r.delete(n),r.size===0&&t.get(e)===r&&t.delete(e)}}function Y(t,e,n=Fe){for(let r of t.get(e.namespace)??[])try{r(e)}catch(o){n("%s",o)}}var fe=(t,e)=>V(de,t,e),W=t=>Y(de,t);var ke=P("primary"),je=P("messages"),J=3e4,Q="Fetch was superseded: no current value",qe=Symbol.for("lru-cache-clustered.primary"),b=globalThis[qe]??={caches:new Map,stats:new Map,fetchLocks:new Map,versions:new Map,clusterListenerInstalled:!1,nextFetchToken:0,nextMutationVersion:0},g=b.caches,j=b.stats,q=b.versions,L=b.fetchLocks,he=new WeakSet;function M(t){return q.get(t)??0}function k(t){let e=(b.nextMutationVersion??0)+1;return b.nextMutationVersion=e,q.set(t,e),e}function y(t){let e=j.get(t);return e||(e={namespace:t,hits:0,misses:0,sets:0,deletes:0,evictions:0,size:0},j.set(t,e)),e}function He(t,e,n){if(!n)return;let r=e;for(let[o,s]of Object.entries(n))if(s!==void 0&&r[o]!==(o==="maxEntrySize"&&!s?r.maxSize:s))throw new Error(`Conflicting options (${t}): ${o}`)}function ee(t,e){if(e==null)throw new TypeError(`cache ${t} must not be null or undefined`);return e}var p=t=>ee("key",t),N=t=>ee("value",t);function C(t,e){if(t!==void 0&&(!Number.isInteger(t)||t<0||e&&t>2147483646))throw new TypeError("invalid ttl")}var me=(t,e)=>!!t.maxEntrySize&&Number.isInteger(e)&&e>t.maxEntrySize;function X(t,e,n){T(t,e),n&&(y(t).sets+=1),k(t)}var pe={allowStale:!0},be={allowStale:!1};function K(t,e,n,r,o=!1){let{ttl:s,size:i}=r;o||C(s,t.ttlAutopurge);let a=o?{size:i,noUpdateTTL:!0}:{ttl:s,size:i};if(t.maxEntrySize&&Number.isInteger(i)&&i>0&&t.peek(e,pe)===n&&t.info(e)?.size!==i){let u={};o&&(t.has(e,{updateAgeOnHas:!1,status:u}),a={ttl:u.ttl??0,start:u.start,size:i}),t.delete(e)}return t.set(e,n,a),t.peek(e,pe)!==void 0}function F(t){t.token=t.requestId=void 0}function T(t,e){let n=L.get(t),r=n?.delete(e)??!1;return n?.size===0&&L.delete(t),r}function z(t,e,n){n&&!n.token&&!n.followers.size&&!n.resolved?.size&&T(t,e)}function Ge(t){for(let[e,n]of L)for(let[r,o]of n){for(let[s,i]of o.followers)i===t&&o.followers.delete(s);for(let[s,[,i]]of o.resolved??[])i===t&&o.resolved.delete(s);o.ownerWorkerId===t&&F(o),z(e,r,o)}}function we(t,e){if(t.maxSize&&t.maxEntrySize&&t.maxEntrySize>t.maxSize)throw new TypeError("invalid maxEntrySize");t.ttlAutopurge&&C(t.ttl,!0);let n={...t,dispose:(r,o,s)=>{s==="evict"&&(e.evictions+=1,T(e.namespace,o),b.activeEvictions?.namespace===e.namespace&&b.activeEvictions.keys.push(o))}};return n.max===void 0&&n.maxSize===void 0&&n.ttl===void 0&&(n.max=1e3),new ve.LRUCache(n)}function A(t,e){let n=g.get(t);return n?He(t,n,e):(j.delete(t),n=we(e??{},y(t)),g.set(t,n),ke("%s",t)),n}function _e(t,e,n={}){let r=()=>g.get(t)??A(t,e.cacheOptions),o=s=>L.get(t)?.get(s);switch(e.op){case"init":return{namespace:t,isNew:!g.has(t),max:A(t,e.options).max,version:M(t)};case"healthCheck":A(t,e.cacheOptions);return;case"destroy":{g.get(t)?.clear();let s=!!(+g.delete(t)|+j.delete(t)|+L.delete(t));return s&&k(t),s}case"get":{let s=p(e.key),i=e.existingOnly?g.get(t):r();if(!i)return;let a=i.get(s);return y(t)[a!==void 0?"hits":"misses"]+=1,a}case"set":{let s=p(e.key),i=K(r(),s,N(e.value),e);return X(t,s,i),i}case"setIfAbsent":{let s=r(),i=p(e.key);if(s.peek(i,be)!==void 0)return!1;let a=N(e.value);return C(e.ttl,s.ttlAutopurge),me(s,e.size)?!1:(K(s,i,a,e),X(t,i,!0),!0)}case"delete":{let s=p(e.key),i=r().delete(s),a=T(t,s);return i&&(y(t).deletes+=1),(i||a)&&k(t),i}case"has":case"peek":case"getRemainingTTL":return r()[e.op](p(e.key));case"clear":r().clear(),L.delete(t),k(t);return;case"mGet":{let s=r(),i=y(t);return e.keys.map(p).map(a=>{let u=s.get(a);return i[u!==void 0?"hits":"misses"]+=1,[a,u]})}case"mSet":{let s=r(),i=y(t),a=e.entries.map(([l,c,d])=>{let f=d?.ttl===void 0?e.ttl:d.ttl;return C(f,s.ttlAutopurge),[p(l),N(c),f,d?.size===void 0?e.size:d.size]}),u=!1;try{for(let[l,c,d,f]of a)K(s,l,c,{ttl:d,size:f})&&(i.sets+=1),T(t,l),u=!0}finally{(u||a.length===0)&&k(t)}return}case"mDelete":{let s=r(),i=y(t),a=e.keys.map(p);for(let u of a)s.delete(u)&&(i.deletes+=1),T(t,u);k(t);return}case"keys":case"values":case"entries":return[...r()[e.op]()];case"dump":return r().dump();case"load":{let s=r(),i=e.entries.map(([a,u])=>{let l=p(a),c=ee("entry",u);N(c.value),C(c.ttl,s.ttlAutopurge);let d={...c};return s.ttl&&d.ttl===void 0&&(d.ttl=0),[l,d]});L.delete(t);try{s.load(i)}finally{k(t)}return}case"size":return r().size;case"stats":{let s=y(t);return s.size=r().size,{...s}}case"purgeStale":{let s=r().purgeStale();return s&&k(t),s}case"incr":case"decr":{let s=r(),i=p(e.key),a=e.amount===void 0?1:e.amount,u=s.peek(i,be),l=u!==void 0,c=(typeof u=="number"?u:0)+a*(e.op==="decr"?-1:1);if(!Number.isFinite(a)||!Number.isFinite(c))throw new TypeError("invalid amount");let d=e.size===void 0?l?s.info(i)?.size:void 0:e.size;if(me(s,d))throw new RangeError("invalid size");return K(s,i,c,{ttl:e.ttl,size:d},l),X(t,i,!0),c}case"fetchClaim":{let s=p(e.key),i=o(s),a=e.requestId,u=a?i?.resolved?.get(a):void 0;if(u)return i.resolved.delete(a),z(t,s,i),y(t).hits+=1,{kind:"value",value:u[0]};if(e.generation!==void 0&&i?.generation!==e.generation){let v=g.get(t)?.get(s);if(v!==void 0)return{kind:"value",value:v};throw new Error(Q)}let l=r(),c=Date.now();if(!e.forceRefresh){let v=l.get(s),h=y(t);if(v!==void 0)return a&&i?.followers.delete(a),z(t,s,i),h.hits+=1,{kind:"value",value:v};if(e.generation===void 0&&(h.misses+=1),i?.token&&c-i.claimedAt<J)return a?(i.followers.set(a,n.workerId),{kind:"follower",generation:i.generation}):{kind:"follower"}}let d=`fetch-${++b.nextFetchToken}`;a&&i?.followers.delete(a);let f=L.get(t);return f||L.set(t,f=new Map),f.set(s,{token:d,generation:i?.token||i?.followers.size?i.generation:d,followers:i?.followers??new Map,resolved:i?.resolved,ownerWorkerId:n.workerId,requestId:a,claimedAt:c}),{kind:"leader",token:d}}case"fetchStore":{let s=p(e.key),i=o(s);if(!i||i.token!==e.token)return!1;let a=N(e.value);if(K(r(),s,a,e))y(t).sets+=1;else if(i.followers.size){let l=i.resolved??=new Map;for(let[c,d]of i.followers)l.set(c,[a,d])}return i.followers.clear(),F(i),z(t,s,i),k(t),!0}case"fetchAbort":{let s=p(e.key),i=o(s);return!i||i.token!==e.token?!1:(F(i),z(t,s,i),!0)}case"fetchRelease":{let s=p(e.key),i=o(s);if(!i)return!1;let a=i.resolved?.delete(e.requestId)??!1;return(e.generation===void 0||i.generation===e.generation)&&(i.followers.delete(e.requestId)&&(a=!0),i.requestId!==void 0&&i.requestId===e.requestId&&(F(i),a=!0)),z(t,s,i),a}case"max":{let s=r();if(e.value!==void 0&&e.value!==s.max){let i={max:e.value};for(let l of"maxSize maxEntrySize ttl allowStale updateAgeOnGet updateAgeOnHas noDeleteOnStaleGet ttlAutopurge".split(" "))i[l]=s[l];let a=we(i,y(t)),u=s.dump();if(i.ttl)for(let[,l]of u)l.ttl===void 0&&(l.ttl=0);return a.load(u),g.set(t,a),s.clear(),k(t),a.max}return s.max}case"ttl":{let s=r();if(e.value!==void 0){if(C(e.value,s.ttlAutopurge),!e.value&&!s.max&&!s.maxSize)throw new TypeError("invalid ttl");e.value!==s.ttl&&(s.ttl=e.value,k(t))}return s.ttl}case"allowStale":{let s=r();return typeof e.value=="boolean"&&(s.allowStale=e.value),s.allowStale}default:{let s=e.op;throw new Error(`unhandled op: ${s}`)}}}var O=(t,e)=>t.includes(` ${e} `);function te(t,e,n){if(O(" destroy clear purgeStale mSet mDelete load max ttl ",e.op))return{source:S,push:"l1:invalidate-namespace",namespace:t,version:n};let r=e.key;if(r!=null)return{source:S,push:"l1:invalidate",namespace:t,key:r,version:n}}function Se(t,e){if(!t.isConnected())return;let n=r=>{r&&ke("%s",r)};try{t.send(e,n)}catch(r){n(r)}}function ge(t){W(t);for(let e of Object.values(m.default.workers??{}))e&&Se(e,t)}function ne(t,e,n={}){let r=M(t),o=O(" set setIfAbsent mSet load incr decr fetchStore max ",e.op)?{namespace:t,keys:[]}:void 0,s=b.activeEvictions;b.activeEvictions=o;let i,a;try{i=_e(t,e,n)}finally{if(b.activeEvictions=s,a=M(t),a!==r){let l=te(t,e,a);if(l&&ge(l),l?.push!=="l1:invalidate-namespace")for(let c of o?.keys??[])ge({source:S,push:"l1:invalidate",namespace:t,key:c,version:a})}e.op==="destroy"&&q.get(t)===a&&q.delete(t)}let u={value:i,version:a};if(o?.keys.length&&(u.evictedKeys=o.keys),e.includeTTL){let l=e.op==="mGet"?e.keys:"key"in e?[e.key]:[],c=g.get(t);u.ttls=l.map(d=>{let f=c?.info(p(d));return f?f.ttl??null:0}),i===!0&&(e.op==="set"||e.op==="fetchStore")&&(u.l1Value=e.value)}return u}function $e(t,e={}){if(!t||typeof t!="object")return Z(t,"not an object");if(!Le(t))return Z(t,"invalid request");try{return{id:t.id,source:S,ok:!0,...ne(t.namespace,t,e)}}catch(n){return Z(t,n)}}function Z(t,e){return{id:t&&typeof t=="object"&&typeof t.id=="string"?t.id:"",source:S,ok:!1,error:$(e)}}function se(){if(b.clusterListenerInstalled)return;b.clusterListenerInstalled=!0;let t=e=>Ge(e.id);m.default.on("disconnect",t),m.default.on("exit",t),m.default.on("fork",ye);for(let e of Object.values(m.default.workers??{}))e&&ye(e)}function ye(t){he.has(t)||(he.add(t),t.on("message",e=>{if(!Le(e))return;je("%d",t.id,e);let n=$e(e,{workerId:t.id});Se(t,n)}))}function Le(t){return I(t)&&typeof t.id=="string"&&typeof t.namespace=="string"&&typeof t.op=="string"}var xe=P("messages"),Be=Symbol.for("lru-cache-clustered.worker"),Ye=globalThis[Be]??={nextRequestId:0};function Xe(t){let e=new Map,n=new Map;t.on("message",o=>{if(Ze(o)){let s=e.get(o.id);if(!s)return;e.delete(o.id),s(o);return}ce(o)&&Y(n,o,xe)});function r(o,s){let i=String(++Ye.nextRequestId),a={id:i,namespace:o.namespace,source:S,...s};return new Promise((u,l)=>{let c=setTimeout(()=>{e.delete(i),o.failsafe==="reject"?l(new Error("IPC timeout")):u({value:void 0,version:0})},o.timeout);e.set(i,f=>{if(clearTimeout(c),f.ok){let{value:v,version:h=0,ttls:R,evictedKeys:w,l1Value:x}=f;u({value:v,version:h,ttls:R,evictedKeys:w,l1Value:x})}else l(B(f.error))}),xe("%O",a);let d=f=>{e.delete(i)&&(clearTimeout(c),l(f instanceof Error?f:new Error(String(f))))};try{t.send(a,f=>{f&&d(f)})}catch(f){d(f)}})}return{sendToPrimary:(o,s)=>r(o,s).then(i=>i.value),sendToPrimaryWithMeta:r,subscribeInvalidations:(o,s)=>V(n,o,s)}}function Ze(t){if(!I(t)||typeof t.id!="string"||typeof t.ok!="boolean")return!1;if(!t.ok){let e=t.error;for(let n=0;;n++){if(n>8||!e||typeof e!="object"||typeof e.name!="string"||typeof e.message!="string")return!1;if(e=e.cause,e===void 0)break}}return!0}var ie;function re(){if(!ie){if(typeof process.send!="function")throw new Error("not a cluster worker");ie=Xe(process)}return ie}var Pe=require("lru-cache");var Re=new WeakMap,Je=0;function Qe(t){let e=Re.get(t);return e||Re.set(t,e=++Je),e}function Oe(t){let e=typeof t;if(e==="symbol")throw new Error("symbol keys unsupported");return e==="object"||e==="function"?`${e[0]}:${Qe(t)}`:`${e==="bigint"?"i":e[0]}:${t}`}var H=class{#e;#r;#o=0;#t=new Map;#s={enabled:!0,hits:0,misses:0,sets:0,invalidations:0,evictions:0,staleHits:0};#i;constructor(e){let{max:n=1e3,ttl:r,updateAgeOnGet:o=!0,allowStale:s=!1,maxSize:i,emit:a}=e;this.#i=a??(()=>{}),this.#r=r,this.#e=new Pe.LRUCache({max:n,ttl:r,updateAgeOnGet:o,allowStale:s,maxSize:i,sizeCalculation:i!==void 0?()=>1:void 0,disposeAfter:(u,l,c)=>{c==="evict"&&(this.#s.evictions+=1,this.#i("evict",{key:u.key??l,reason:"lru"}))}})}get(e,n=e,r="get"){let o={},s=r==="get"?this.#e.get(e,{status:o}):this.#e.peek(e,{allowStale:r!=="has"&&this.#e.allowStale});r==="peek"&&s&&this.#e.getRemainingTTL(e)<0&&(o.returnedStale=!0);let i=this.#s;if(s){let a=s.version<this.#o||s.expiresAt!==void 0&&E()>=s.expiresAt;(a||o.returnedStale)&&(i.staleHits+=1,this.#i("stale-hit",{key:s.key}),a&&(this.#e.delete(e),s=void 0))}if(!s){i.misses+=1,this.#i("miss",{key:n});return}return i.hits+=1,this.#i("hit",{key:s.key}),s.value}set(e,n,r,o,s=e,i){let a=this.#e.peek(e,{allowStale:!0});if(r<this.#o||a&&r<a.version||i&&(i.cancelled||r<i.version))return;let u,l;if(Number.isFinite(o)){let c=this.#r===void 0?o:Math.min(o,this.#r);if(c<=0)return;u={ttl:c},l=E()+o}this.#e.set(e,{value:n,version:r,expiresAt:l,key:s},u),this.#s.sets+=1,this.#i("set",{key:s,version:r})}trackRead(e){let n={version:this.#o,cancelled:!1};return n.release=V(this.#t,e,n),n}delete(e,n=e,r=!0,o){for(let i of this.#t.get(e)??[])o===void 0?i.cancelled=!0:i.version=Math.max(i.version,o);let s=this.#e.peek(e,{allowStale:!0});s&&(o===void 0||s.version<o)&&this.#e.delete(e)&&(this.#s.invalidations+=1,r&&this.#i("invalidate",{key:n,reason:"self"}))}clear(e=!0,n){let r=!1;if(n===void 0){for(let o of this.#t.values())for(let s of o)s.cancelled=!0;r=this.#e.size>0,this.#e.clear()}else{this.advanceLatestSeen(n),this.#e.allowStale||this.#e.purgeStale();for(let[o,s]of this.#e.entries())s.version<n&&(this.#e.delete(o),r=!0)}r&&(this.#s.invalidations+=1),e&&this.#i("invalidate",{key:"*",reason:"clear"})}advanceLatestSeen(e){e>this.#o&&(this.#o=e)}latestSeen(){return this.#o}stats(){return{...this.#s,size:this.#e.size,ipcAvoided:this.#s.hits}}destroy(){this.clear(!1)}};function Ee(t,e,n,r){return async(...o)=>{let s=n(...o);return t.fetch(s,()=>e(...o),r)}}function ze(t,e){let n=u=>e.encode(u),r=u=>e.decode(u),o=async u=>u===void 0?void 0:r(u),s=t;return{...Object.fromEntries("has delete getRemainingTTL mDelete keys size clear destroy healthCheck purgeStale stats".split(" ").map(u=>[u,t[u].bind(t)])),cache:s,namespace:t.namespace,ready:t.ready,async get(u,l){return o(await t.get(u,l))},async set(u,l,c){return t.set(u,await n(l),c)},async setIfAbsent(u,l,c){return t.setIfAbsent(u,await n(l),c)},async peek(u,l){return o(await t.peek(u,l))},async mGet(u,l){let c=new Map;for(let[d,f]of await t.mGet(u,l))c.set(d,await o(f));return c},async mSet(u,l){let c=[];for(let[d,f,v]of u){let h=await n(f);c.push(v?[d,h,v]:[d,h])}return t.mSet(c,l)},async values(){return Promise.all((await t.values()??[]).map(async u=>r(u)))},async entries(){return Promise.all((await t.entries()??[]).map(async([u,l])=>[u,await r(l)]))},async*[Symbol.asyncIterator](){for(let u of await this.entries())yield u},async fetch(u,l,c){return r(await t.fetch(u,async d=>n(await l(d)),c))}}}m.default.isPrimary&&se();function et(t,e){let{op:n}=t;return n==="max"||n==="ttl"?typeof t.value=="number":O(" set mSet mDelete clear load incr decr ",n)||e===!0&&O(" delete setIfAbsent purgeStale fetchStore destroy ",n)}function tt(t,e){if(!t||t.enabled===!1)return;let{experimental:n,ttl:r,max:o=1e3,maxSize:s,updateAgeOnGet:i=!0,allowStale:a=!1,invalidation:u="broadcast",methods:l}=t;if(!n)throw new Error("localL1 requires experimental: true");if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new TypeError("invalid localL1.ttl");let c=e.ttl||1/0,d=Math.max(1,Math.floor(Math.min(r??Math.max(100,Math.min(c*.1,5e3)),c)));return{max:o,maxSize:s,ttl:d,updateAgeOnGet:i,allowStale:a,invalidation:u,methods:{get:!l||!!l.get,has:!l||!!l.has,fetch:!l||!!l.fetch}}}function Ce(t){if(m.default.isWorker)throw new Error(`${t}() is primary-only`)}var G=t=>t==null||typeof t=="symbol"?void 0:Oe(t),_=class t{namespace;timeout;failsafe;ready;#e;#r=new Map;#o=new Te.EventEmitter;#t;#s;#i;#m=!1;#l=0;constructor(e={}){let{namespace:n="default",timeout:r=100,failsafe:o,noInit:s,localL1:i,...a}=e;this.namespace=n,this.timeout=r,this.failsafe=o==="reject"?"reject":"resolve",this.#e=a;let u=tt(i,a);this.#s=u,u&&(this.#t=new H({...u,emit:(l,c)=>{this.#o.emit(`l1:${l}`,{namespace:this.namespace,...c})}})),m.default.isPrimary&&(A(this.namespace,this.#e),this.#t?.advanceLatestSeen(M(this.namespace)),this.#b()),this.ready=!m.default.isPrimary&&!s?this.#g().catch(()=>{}):Promise.resolve()}static async getInstance(e={}){let n=new t({...e,noInit:!0});return m.default.isWorker&&await n.#g(),n}static bootstrap(){m.default.isPrimary&&se()}static getAllCaches(){return Ce("getAllCaches"),g}getCache(){return Ce("getCache"),g.get(this.namespace)}get(e,n){return this.#y("get",e,n)}async set(e,n,r){this.#a(e);let o=!!this.#t&&!!r?.updateL1,s=o?this.#f(e):void 0;try{let i=await this.#u({op:"set",key:e,value:n,ttl:r?.ttl,size:r?.size,includeTTL:o},this.failsafe);return o&&i.value&&this.#c(e,i.l1Value,i,s),i.value}finally{s?.release()}}delete(e){return this.#a(e),this.#n({op:"delete",key:e})}async has(e,n){return this.#s?.methods.has&&!n?.bypassL1&&this.#h(e,"has")!==void 0?!0:this.#n({op:"has",key:e})}peek(e,n){return this.#y("peek",e,n)}clear(){return this.#d({op:"clear"})}purgeStale(){return this.#d({op:"purgeStale"})}async mGet(e,n){let r=new Map,o=!!this.#s?.methods.get&&!n?.bypassL1,s=o?[]:e;if(o)for(let a of e){let u=this.#h(a);u!==void 0?r.set(a,u):s.push(a)}if(s.length===0)return r;let i=o?new Map([...new Set(s)].map(a=>[a,this.#f(a)])):void 0;try{let a=await this.#u({op:"mGet",keys:s,includeTTL:o},this.failsafe);(a.value??[]).forEach(([l,c],d)=>{let f=c===null?void 0:c;r.set(l,f),o&&f!==void 0&&this.#c(l,f,a,i?.get(l),d)});let u=new Map;for(let l of e)r.has(l)&&u.set(l,r.get(l));return u}finally{if(i)for(let a of i.values())a?.release()}}mSet(e,n){return this.#d({op:"mSet",entries:[...e],ttl:n?.ttl,size:n?.size})}mDelete(e){return this.#d({op:"mDelete",keys:e})}keys(){return this.#n({op:"keys"})}values(){return this.#n({op:"values"})}entries(){return this.#n({op:"entries"})}dump(){return this.#n({op:"dump"})}size(){return this.#n({op:"size"})}incr(e,n,r){return this.#k("incr",e,n,r)}decr(e,n,r){return this.#k("decr",e,n,r)}allowStale(e){return this.#p("allowStale",e)}max(e){return this.#p("max",e)}ttl(e){return this.#p("ttl",e)}getRemainingTTL(e){return this.#n({op:"getRemainingTTL",key:e}).then(n=>n===null?1/0:n)}setIfAbsent(e,n,r){return this.#a(e),this.#n({op:"setIfAbsent",key:e,value:n,ttl:r?.ttl,size:r?.size})}load(e){return this.#d({op:"load",entries:e})}destroy(){return this.#l+=1,this.#r.clear(),this.#i?.(),this.#i=void 0,this.#t?.destroy(),this.#n({op:"destroy"})}healthCheck(){return this.#n({op:"healthCheck"},"reject")}stats(){return this.#n({op:"stats"})}localStats(){return this.#t?.stats()}on(e,n){return this.#o.on(e,n),this}off(e,n){return this.#o.off(e,n),this}once(e,n){return this.#o.once(e,n),this}clearLocal(){this.#t?.clear()}invalidateLocal(e){this.#a(e)}withoutLocal(){let e=new Proxy(this,{get(n,r){if(r==="withoutLocal")return()=>e;let o=Reflect.get(n,r,n);if(typeof o!="function")return o;let s=o;if(typeof r=="string"){if(O(" get has peek mGet fetch ",r))return(...i)=>{let a=r==="fetch"?2:1;return i[a]={...i[a],bypassL1:!0},s.apply(n,i)};if(O(" on off once ",r))return(...i)=>(s.apply(n,i),e)}return s.bind(n)}});return e}async*[Symbol.asyncIterator](){let e=await this.entries();for(let n of e??[])yield n}async fetch(e,n,r){let o=r?.bypassL1,s=!!this.#s?.methods.fetch&&!o;if(!r?.forceRefresh&&!o){if(s){let R=this.#h(e);if(R!==void 0)return R}let h=this.#r.get(e);if(h&&Date.now()-h.startedAt<J)return h.promise}let i=this.#l,a=h=>this.#u(h,"reject",this.#l===i),u=s?this.#f(e):void 0,l,c=globalThis.crypto.randomUUID(),d,f=!1;l={promise:(async()=>{let h=!!r?.forceRefresh;for(;;){f=!0;let R=await a({op:"fetchClaim",key:e,forceRefresh:h,requestId:c,generation:d,includeTTL:s});f=!1;let w=R.value;if(w.kind==="value")return d=void 0,s&&this.#c(e,w.value,R,u),w.value;if(w.kind==="leader")try{let x=await n(e),U=await a({op:"fetchStore",includeTTL:s,key:e,token:w.token,value:x,ttl:r?.ttl,size:r?.size});if(!U.value){let oe=(await a({op:"get",key:e,existingOnly:!0})).value;if(oe===void 0)throw new Error(Q);return oe}return d=void 0,this.#a(e,s?U.version:void 0),s&&this.#c(e,U.l1Value,U,u),x}catch(x){try{await a({op:"fetchAbort",key:e,token:w.token})}catch{}throw x}d=w.generation,h=!1,await new Promise(x=>setTimeout(x,5))}})(),startedAt:Date.now()},this.#r.set(e,l);try{return await l.promise}finally{if(this.#r.get(e)===l&&this.#r.delete(e),u?.release(),d!==void 0||f)try{await a({op:"fetchRelease",key:e,generation:d,requestId:c})}catch{}}}async#p(e,n){let r=await this.#n({op:e,value:n});return r!==void 0&&(this.#e[e]=r),n!==void 0&&e!=="allowStale"&&this.#v(),r}async#g(){let e=this.#l,n=await this.#u({op:"init",options:this.#e},"reject");this.#t?.advanceLatestSeen(n.value.version),this.#l===e&&this.#b()}async#y(e,n,r){let o=!!this.#s?.methods.get&&!r?.bypassL1;if(o){let i=this.#h(n,e);if(i!==void 0)return i}let s=o?this.#f(n):void 0;try{let i=await this.#u({op:e,key:n,includeTTL:o},this.failsafe);return o&&i.value!==void 0&&this.#c(n,i.value,i,s),i.value}finally{s?.release()}}#b(){if(this.#s?.invalidation!=="broadcast"||this.#i)return;let e=o=>{try{this.#m||this.#o.emit("l1:invalidate",{namespace:this.namespace,key:o.push==="l1:invalidate"?o.key:"*",reason:"broadcast"})}finally{o.push==="l1:invalidate"?this.#a(o.key,o.version):(this.#r.clear(),this.#t.clear(!1,o.version))}},n=fe(this.namespace,e),r=m.default.isPrimary?void 0:re().subscribeInvalidations(this.namespace,e);this.#i=()=>{n(),r?.()}}#c(e,n,r,o,s=0){let i=G(e),a=r.ttls?.[s];if(i===void 0||a===void 0)return;let u=a===null?void 0:a-(E()-r.ttlStart);this.#t.set(i,n,r.version,u,e,o)}#f(e){let n=G(e);return n===void 0?void 0:this.#t.trackRead(n)}#h(e,n="get"){let r=G(e);return r===void 0?void 0:this.#t.get(r,e,n)}#v(){this.#r.clear(),this.#t?.clear()}#a(e,n){if(this.#r.delete(e),!this.#t)return;let r=G(e);r!==void 0&&this.#t.delete(r,e,n===void 0,n)}#d(e){return this.#v(),this.#n(e)}#k(e,n,r,o){return this.#a(n),this.#n({op:e,key:n,amount:r,ttl:o?.ttl,size:o?.size})}#n(e,n=this.failsafe){return this.#u(e,n).then(r=>r.value)}async#u(e,n,r=!0){r&&e.op!=="destroy"&&e.op!=="init"&&this.#b();let o=e.includeTTL?E():void 0,s={...e,cacheOptions:this.#e},i=u=>{this.#m=!0;try{return u()}finally{this.#m=!1}},a;if(m.default.isPrimary)try{a=i(()=>ne(this.namespace,s))}catch(u){throw u instanceof Error?u:new Error(String(u))}else a=await re().sendToPrimaryWithMeta({namespace:this.namespace,timeout:this.timeout,failsafe:n},s);for(let u of a.evictedKeys??[])this.#a(u,a.version);if(!m.default.isPrimary&&a.version>0&&et(s,a.value)){let u=te(this.namespace,s,a.version);u&&i(()=>W(u))}return{...a,ttlStart:o}}};var nt=_;0&&(module.exports={LRUCacheClustered,LRUCacheForClustersAsPromised,memoize,wrap});
2
2
  //# sourceMappingURL=index.cjs.map