@warlock.js/cache 5.42.0 → 5.43.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 (105) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/cjs/index.cjs +1341 -271
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/cache-manager.d.mts +41 -0
  5. package/esm/cache-manager.d.mts.map +1 -1
  6. package/esm/cache-manager.mjs +47 -2
  7. package/esm/cache-manager.mjs.map +1 -1
  8. package/esm/drivers/base-cache-driver.d.mts +14 -0
  9. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  10. package/esm/drivers/base-cache-driver.mjs +26 -1
  11. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  12. package/esm/drivers/lru-memory-cache-driver.d.mts +17 -1
  13. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  14. package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
  15. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  16. package/esm/drivers/memory-cache-driver.d.mts +19 -1
  17. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  18. package/esm/drivers/memory-cache-driver.mjs +34 -0
  19. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  20. package/esm/drivers/mock-cache-driver.d.mts +4 -0
  21. package/esm/drivers/mock-cache-driver.d.mts.map +1 -1
  22. package/esm/drivers/mock-cache-driver.mjs +18 -0
  23. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  24. package/esm/drivers/null-cache-driver.d.mts +6 -0
  25. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  26. package/esm/drivers/null-cache-driver.mjs +8 -0
  27. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  28. package/esm/drivers/pg-cache-driver.d.mts +7 -0
  29. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  30. package/esm/drivers/pg-cache-driver.mjs +17 -0
  31. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  32. package/esm/drivers/redis-cache-driver.d.mts +17 -1
  33. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  34. package/esm/drivers/redis-cache-driver.mjs +29 -0
  35. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  36. package/esm/idempotent.d.mts +35 -0
  37. package/esm/idempotent.d.mts.map +1 -0
  38. package/esm/idempotent.mjs +74 -0
  39. package/esm/idempotent.mjs.map +1 -0
  40. package/esm/index.d.mts +12 -2
  41. package/esm/index.mjs +7 -3
  42. package/esm/scoped-cache.d.mts +5 -0
  43. package/esm/scoped-cache.d.mts.map +1 -1
  44. package/esm/scoped-cache.mjs +7 -0
  45. package/esm/scoped-cache.mjs.map +1 -1
  46. package/esm/structures/bloom-filter.d.mts +33 -0
  47. package/esm/structures/bloom-filter.d.mts.map +1 -0
  48. package/esm/structures/bloom-filter.mjs +56 -0
  49. package/esm/structures/bloom-filter.mjs.map +1 -0
  50. package/esm/structures/cuckoo-filter.d.mts +36 -0
  51. package/esm/structures/cuckoo-filter.d.mts.map +1 -0
  52. package/esm/structures/cuckoo-filter.mjs +70 -0
  53. package/esm/structures/cuckoo-filter.mjs.map +1 -0
  54. package/esm/structures/frequency-tracker.d.mts +33 -0
  55. package/esm/structures/frequency-tracker.d.mts.map +1 -0
  56. package/esm/structures/frequency-tracker.mjs +75 -0
  57. package/esm/structures/frequency-tracker.mjs.map +1 -0
  58. package/esm/structures/hash.mjs +69 -0
  59. package/esm/structures/hash.mjs.map +1 -0
  60. package/esm/structures/hyperloglog.d.mts +27 -0
  61. package/esm/structures/hyperloglog.d.mts.map +1 -0
  62. package/esm/structures/hyperloglog.mjs +67 -0
  63. package/esm/structures/hyperloglog.mjs.map +1 -0
  64. package/esm/structures/index.d.mts +10 -0
  65. package/esm/structures/index.mjs +11 -0
  66. package/esm/structures/memory-structures-backend.d.mts +56 -0
  67. package/esm/structures/memory-structures-backend.d.mts.map +1 -0
  68. package/esm/structures/memory-structures-backend.mjs +114 -0
  69. package/esm/structures/memory-structures-backend.mjs.map +1 -0
  70. package/esm/structures/redis-structures-backend.d.mts +42 -0
  71. package/esm/structures/redis-structures-backend.d.mts.map +1 -0
  72. package/esm/structures/redis-structures-backend.mjs +259 -0
  73. package/esm/structures/redis-structures-backend.mjs.map +1 -0
  74. package/esm/structures/sizing.mjs +26 -0
  75. package/esm/structures/sizing.mjs.map +1 -0
  76. package/esm/structures/structures.d.mts +22 -0
  77. package/esm/structures/structures.d.mts.map +1 -0
  78. package/esm/structures/structures.mjs +44 -0
  79. package/esm/structures/structures.mjs.map +1 -0
  80. package/esm/structures/types.d.mts +108 -0
  81. package/esm/structures/types.d.mts.map +1 -0
  82. package/esm/structures/types.mjs +8 -0
  83. package/esm/structures/types.mjs.map +1 -0
  84. package/esm/structures/unique-counter.d.mts +33 -0
  85. package/esm/structures/unique-counter.d.mts.map +1 -0
  86. package/esm/structures/unique-counter.mjs +43 -0
  87. package/esm/structures/unique-counter.mjs.map +1 -0
  88. package/esm/tagged-cache.d.mts +4 -0
  89. package/esm/tagged-cache.d.mts.map +1 -1
  90. package/esm/tagged-cache.mjs +6 -0
  91. package/esm/tagged-cache.mjs.map +1 -1
  92. package/esm/tagged-scoped-cache.d.mts +4 -0
  93. package/esm/tagged-scoped-cache.d.mts.map +1 -1
  94. package/esm/tagged-scoped-cache.mjs +6 -0
  95. package/esm/tagged-scoped-cache.mjs.map +1 -1
  96. package/esm/types.d.mts +24 -0
  97. package/esm/types.d.mts.map +1 -1
  98. package/esm/types.mjs.map +1 -1
  99. package/llms-full.txt +112 -1
  100. package/llms.txt +3 -0
  101. package/package.json +3 -3
  102. package/skills/index.md +3 -1
  103. package/skills/use-cache-extend/SKILL.md +22 -0
  104. package/skills/use-cache-idempotent/SKILL.md +27 -0
  105. package/skills/use-cache-structures/SKILL.md +48 -0
@@ -0,0 +1,35 @@
1
+ import { CacheTtl } from "./types.mjs";
2
+ //#region ../../packages/cache/src/idempotent.d.ts
3
+ /**
4
+ * Options of `idempotent()`.
5
+ */
6
+ export type IdempotentOptions = {
7
+ /**
8
+ * How long a successful result is kept and replayed. A number is seconds; a
9
+ * string is a duration such as `"24h"`. `0` means in-flight dedupe only:
10
+ * nothing is stored, and the next call after the run finishes runs again.
11
+ */
12
+ ttl: CacheTtl;
13
+ /**
14
+ * Cache driver name to store results in (and take the lock on). Defaults to
15
+ * the current driver.
16
+ */
17
+ driver?: string;
18
+ /**
19
+ * Make concurrent calls on DIFFERENT servers run `fn` once, using the cache
20
+ * lock. Without it, calls share a single run only inside one process; across
21
+ * processes the stored result still prevents re-runs after the first one
22
+ * finished. Needs a shared driver such as Redis or Postgres.
23
+ */
24
+ distributed?: boolean;
25
+ /**
26
+ * With `distributed`: how long the lock is held, which is also how long
27
+ * another server waits for the result before giving up. Must exceed the
28
+ * worst-case duration of `fn`. Default `"30s"`.
29
+ */
30
+ lockTtl?: CacheTtl;
31
+ };
32
+ /** In-flight runs, per driver instance and storage key. */
33
+ export type IdempotentFlights = WeakMap<object, Map<string, Promise<unknown>>>;
34
+ //#endregion
35
+ //# sourceMappingURL=idempotent.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotent.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/idempotent.ts"],"mappings":";;;;;YAQY;;;;;;EAMV,KAAK;;;;;EAKL;;;;;;;EAOA;;;;;;EAMA,UAAU;;;YAUA,oBAAoB,gBAAgB,YAAY"}
@@ -0,0 +1,74 @@
1
+ import { CacheConcurrencyError } from "./types.mjs";
2
+ import { parseCacheKey, parseTtl } from "./utils.mjs";
3
+ import { log, maskEmailsInText } from "@warlock.js/logger";
4
+
5
+ //#region ../../packages/cache/src/idempotent.ts
6
+ const MIN_POLL_MS = 25;
7
+ const MAX_POLL_MS = 250;
8
+ const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
9
+ async function readStored(driver, storeKey) {
10
+ const value = await driver.get(storeKey);
11
+ if (value && typeof value === "object" && value.idempotent === true) return value;
12
+ return null;
13
+ }
14
+ async function store(driver, storeKey, result, seconds) {
15
+ try {
16
+ await driver.set(storeKey, {
17
+ idempotent: true,
18
+ result
19
+ }, seconds);
20
+ } catch (error) {
21
+ log.error("cache", "idempotent", maskEmailsInText(`Could not store the result of ${storeKey}: ${String(error)}`));
22
+ }
23
+ }
24
+ /**
25
+ * Implementation behind `cache.idempotent()`.
26
+ */
27
+ function runIdempotent(driver, flights, key, fn, options) {
28
+ const seconds = parseTtl(options.ttl);
29
+ const keyString = typeof key === "string" ? key : parseCacheKey(key);
30
+ const storeKey = `idempotent.${keyString}`;
31
+ const driverFlights = flights.get(driver) ?? /* @__PURE__ */ new Map();
32
+ flights.set(driver, driverFlights);
33
+ const existing = driverFlights.get(storeKey);
34
+ if (existing) return existing;
35
+ const run = async () => {
36
+ if (seconds === 0) return fn();
37
+ const stored = await readStored(driver, storeKey);
38
+ if (stored) return stored.result;
39
+ if (options.distributed) return runDistributed(driver, keyString, storeKey, fn, seconds, options);
40
+ const result = await fn();
41
+ await store(driver, storeKey, result, seconds);
42
+ return result;
43
+ };
44
+ const promise = run().finally(() => {
45
+ if (driverFlights.get(storeKey) === promise) driverFlights.delete(storeKey);
46
+ });
47
+ driverFlights.set(storeKey, promise);
48
+ return promise;
49
+ }
50
+ async function runDistributed(driver, keyString, storeKey, fn, seconds, options) {
51
+ const lockKey = `idempotent.lock.${keyString}`;
52
+ const lockSeconds = parseTtl(options.lockTtl ?? "30s");
53
+ const deadline = Date.now() + lockSeconds * 1e3;
54
+ let pause = MIN_POLL_MS;
55
+ while (true) {
56
+ const outcome = await driver.lock(lockKey, lockSeconds, async () => {
57
+ const stored = await readStored(driver, storeKey);
58
+ if (stored) return stored.result;
59
+ const result = await fn();
60
+ await store(driver, storeKey, result, seconds);
61
+ return result;
62
+ });
63
+ if (outcome.acquired) return outcome.value;
64
+ await sleep(pause);
65
+ pause = Math.min(pause * 2, MAX_POLL_MS);
66
+ const stored = await readStored(driver, storeKey);
67
+ if (stored) return stored.result;
68
+ if (Date.now() >= deadline) throw new CacheConcurrencyError(`idempotent("${keyString}") timed out after ${lockSeconds}s waiting for another run to finish.`);
69
+ }
70
+ }
71
+
72
+ //#endregion
73
+ export { runIdempotent };
74
+ //# sourceMappingURL=idempotent.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotent.mjs","names":[],"sources":["../../../../../../../packages/cache/src/idempotent.ts"],"sourcesContent":["import { log, maskEmailsInText } from \"@warlock.js/logger\";\nimport type { CacheDriver, CacheKey, CacheTtl } from \"./types\";\nimport { CacheConcurrencyError } from \"./types\";\nimport { parseCacheKey, parseTtl } from \"./utils\";\n\n/**\n * Options of `idempotent()`.\n */\nexport type IdempotentOptions = {\n /**\n * How long a successful result is kept and replayed. A number is seconds; a\n * string is a duration such as `\"24h\"`. `0` means in-flight dedupe only:\n * nothing is stored, and the next call after the run finishes runs again.\n */\n ttl: CacheTtl;\n /**\n * Cache driver name to store results in (and take the lock on). Defaults to\n * the current driver.\n */\n driver?: string;\n /**\n * Make concurrent calls on DIFFERENT servers run `fn` once, using the cache\n * lock. Without it, calls share a single run only inside one process; across\n * processes the stored result still prevents re-runs after the first one\n * finished. Needs a shared driver such as Redis or Postgres.\n */\n distributed?: boolean;\n /**\n * With `distributed`: how long the lock is held, which is also how long\n * another server waits for the result before giving up. Must exceed the\n * worst-case duration of `fn`. Default `\"30s\"`.\n */\n lockTtl?: CacheTtl;\n};\n\n/**\n * What is kept in the cache. The wrapper tells a stored `undefined`, `null` or\n * `false` result apart from \"nothing stored\".\n */\ntype StoredResult = { idempotent: true; result: unknown };\n\n/** In-flight runs, per driver instance and storage key. */\nexport type IdempotentFlights = WeakMap<object, Map<string, Promise<unknown>>>;\n\nconst MIN_POLL_MS = 25;\nconst MAX_POLL_MS = 250;\n\nconst sleep = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));\n\nasync function readStored(\n driver: CacheDriver<any, any>,\n storeKey: string,\n): Promise<StoredResult | null> {\n const value = await driver.get(storeKey);\n\n if (value && typeof value === \"object\" && (value as StoredResult).idempotent === true) {\n return value as StoredResult;\n }\n\n return null;\n}\n\nasync function store(\n driver: CacheDriver<any, any>,\n storeKey: string,\n result: unknown,\n seconds: number,\n) {\n try {\n await driver.set(storeKey, { idempotent: true, result } satisfies StoredResult, seconds);\n } catch (error) {\n // The work already happened: hand the result back instead of failing the\n // caller into a retry that would repeat it.\n log.error(\n \"cache\",\n \"idempotent\",\n maskEmailsInText(`Could not store the result of ${storeKey}: ${String(error)}`),\n );\n }\n}\n\n/**\n * Implementation behind `cache.idempotent()`.\n */\nexport function runIdempotent<T>(\n driver: CacheDriver<any, any>,\n flights: IdempotentFlights,\n key: CacheKey,\n fn: () => Promise<T>,\n options: IdempotentOptions,\n): Promise<T> {\n const seconds = parseTtl(options.ttl);\n const keyString = typeof key === \"string\" ? key : parseCacheKey(key);\n const storeKey = `idempotent.${keyString}`;\n\n const driverFlights = flights.get(driver) ?? new Map<string, Promise<unknown>>();\n\n flights.set(driver, driverFlights);\n\n const existing = driverFlights.get(storeKey);\n\n if (existing) {\n return existing as Promise<T>;\n }\n\n const run = async (): Promise<T> => {\n if (seconds === 0) {\n return fn();\n }\n\n const stored = await readStored(driver, storeKey);\n\n if (stored) {\n return stored.result as T;\n }\n\n if (options.distributed) {\n return runDistributed(driver, keyString, storeKey, fn, seconds, options);\n }\n\n const result = await fn();\n\n await store(driver, storeKey, result, seconds);\n\n return result;\n };\n\n const promise = run().finally(() => {\n if (driverFlights.get(storeKey) === promise) {\n driverFlights.delete(storeKey);\n }\n });\n\n driverFlights.set(storeKey, promise);\n\n return promise;\n}\n\nasync function runDistributed<T>(\n driver: CacheDriver<any, any>,\n keyString: string,\n storeKey: string,\n fn: () => Promise<T>,\n seconds: number,\n options: IdempotentOptions,\n): Promise<T> {\n const lockKey = `idempotent.lock.${keyString}`;\n const lockSeconds = parseTtl(options.lockTtl ?? \"30s\");\n const deadline = Date.now() + lockSeconds * 1000;\n let pause = MIN_POLL_MS;\n\n while (true) {\n const outcome = await driver.lock(lockKey, lockSeconds, async () => {\n // Another server may have finished between our read and the lock.\n const stored = await readStored(driver, storeKey);\n\n if (stored) {\n return stored.result as T;\n }\n\n const result = await fn();\n\n await store(driver, storeKey, result, seconds);\n\n return result;\n });\n\n if (outcome.acquired) {\n return outcome.value;\n }\n\n // Held elsewhere: wait for its result. If that run fails it stores\n // nothing and releases the lock, and the next loop takes it over.\n await sleep(pause);\n pause = Math.min(pause * 2, MAX_POLL_MS);\n\n const stored = await readStored(driver, storeKey);\n\n if (stored) {\n return stored.result as T;\n }\n\n if (Date.now() >= deadline) {\n throw new CacheConcurrencyError(\n `idempotent(\"${keyString}\") timed out after ${lockSeconds}s waiting for another run to finish.`,\n );\n }\n }\n}\n"],"mappings":";;;;;AA4CA,MAAM,cAAc;AACpB,MAAM,cAAc;AAEpB,MAAM,SAAS,iBAAyB,IAAI,SAAS,YAAY,WAAW,SAAS,YAAY,CAAC;AAElG,eAAe,WACb,QACA,UAC8B;CAC9B,MAAM,QAAQ,MAAM,OAAO,IAAI,QAAQ;CAEvC,IAAI,SAAS,OAAO,UAAU,YAAa,MAAuB,eAAe,MAC/E,OAAO;CAGT,OAAO;AACT;AAEA,eAAe,MACb,QACA,UACA,QACA,SACA;CACA,IAAI;EACF,MAAM,OAAO,IAAI,UAAU;GAAE,YAAY;GAAM;EAAO,GAA0B,OAAO;CACzF,SAAS,OAAO;EAGd,IAAI,MACF,SACA,cACA,iBAAiB,iCAAiC,SAAS,IAAI,OAAO,KAAK,GAAG,CAChF;CACF;AACF;;;;AAKA,SAAgB,cACd,QACA,SACA,KACA,IACA,SACY;CACZ,MAAM,UAAU,SAAS,QAAQ,GAAG;CACpC,MAAM,YAAY,OAAO,QAAQ,WAAW,MAAM,cAAc,GAAG;CACnE,MAAM,WAAW,cAAc;CAE/B,MAAM,gBAAgB,QAAQ,IAAI,MAAM,qBAAK,IAAI,IAA8B;CAE/E,QAAQ,IAAI,QAAQ,aAAa;CAEjC,MAAM,WAAW,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d.mts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { BaseCacheDriver, NormalizedSetOptions } from "./drivers/base-cache-driver.mjs";
2
2
  import { FileCacheDriver } from "./drivers/file-cache-driver.mjs";
3
+ import { BloomOptions, CacheStructuresBackend, CuckooOptions, FrequencyEntry, FrequencyOptions, NativeStructures, StructureOptions, StructuresCapable, UniqueCounterOptions, isStructuresCapable } from "./structures/types.mjs";
4
+ import { MemoryStructuresBackend } from "./structures/memory-structures-backend.mjs";
3
5
  import { LRUMemoryCacheDriver } from "./drivers/lru-memory-cache-driver.mjs";
4
6
  import { MemoryCacheDriver } from "./drivers/memory-cache-driver.mjs";
5
7
  import { MemoryExtendedCacheDriver } from "./drivers/memory-extended-cache-driver.mjs";
@@ -9,8 +11,16 @@ import { PgCacheDriver } from "./drivers/pg-cache-driver.mjs";
9
11
  import { REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver } from "./drivers/redis-cache-driver.mjs";
10
12
  import "./drivers/index.mjs";
11
13
  import { CacheCall, CacheConcurrencyError, CacheConfigurationError, CacheConfigurations, CacheConflictPolicy, CacheConnectionError, CacheData, CacheDriver, CacheDriverNotInitializedError, CacheError, CacheEventData, CacheEventHandler, CacheEventType, CacheKey, CacheListAccessor, CacheMetricsSnapshot, CacheNamespaceOptions, CacheOperationType, CacheSetOptions, CacheSetResult, CacheSimilarHit, CacheSimilarOptions, CacheSwrOptions, CacheTtl, CacheUnsupportedError, DriverClass, FileCacheOptions, LRUMemoryCacheOptions, LockOptions, LockOutcome, MemoryCacheOptions, MemoryExtendedCacheOptions, MockCacheOptions, NullCacheDriverOptions, PgCacheOptions, PgClientLike, RedisOptions, RememberOptions, ScopedCacheContract, TaggedCacheDriver, TaggedScopedCacheContract } from "./types.mjs";
14
+ import { IdempotentOptions } from "./idempotent.mjs";
12
15
  import { CacheMetricsCollector } from "./metrics.mjs";
13
- import { CacheManager, cache } from "./cache-manager.mjs";
16
+ import { BloomFilter } from "./structures/bloom-filter.mjs";
17
+ import { CuckooFilter } from "./structures/cuckoo-filter.mjs";
18
+ import { FrequencyTracker } from "./structures/frequency-tracker.mjs";
19
+ import { RedisStructuresBackend } from "./structures/redis-structures-backend.mjs";
20
+ import { UniqueCounter, UniqueCounterGroup } from "./structures/unique-counter.mjs";
21
+ import { CacheStructures, UniqueCounterFactory } from "./structures/structures.mjs";
22
+ import "./structures/index.mjs";
23
+ import { CacheManager, cache, idempotent } from "./cache-manager.mjs";
14
24
  import { deriveAutoKey } from "./cached/auto-key.mjs";
15
25
  import { CachedOptions, NormalizedCachedConfig, normalizeCachedArgs } from "./cached/normalize-args.mjs";
16
26
  import { CachedFn, cached } from "./cached/cached.mjs";
@@ -21,4 +31,4 @@ import { ScopedCache } from "./scoped-cache.mjs";
21
31
  import { TaggedCache } from "./tagged-cache.mjs";
22
32
  import { TaggedScopedCache } from "./tagged-scoped-cache.mjs";
23
33
  import { CACHE_FOR, cosineSimilarity, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo } from "./utils.mjs";
24
- export { BaseCacheDriver, CACHE_FOR, CacheCall, CacheConcurrencyError, CacheConfigurationError, CacheConfigurations, CacheConflictPolicy, CacheConnectionError, CacheData, CacheDriver, CacheDriverNotInitializedError, CacheError, CacheEventData, CacheEventHandler, CacheEventType, CacheKey, CacheListAccessor, CacheManager, CacheMetricsCollector, CacheMetricsSnapshot, CacheNamespaceOptions, CacheOperationType, CacheSetOptions, CacheSetResult, CacheSimilarHit, CacheSimilarOptions, CacheSwrOptions, CacheTtl, CacheUnsupportedError, CachedFn, CachedOptions, DriverClass, FileCacheDriver, FileCacheOptions, LRUMemoryCacheDriver, LRUMemoryCacheOptions, LockOptions, LockOutcome, MemoryCacheDriver, MemoryCacheList, MemoryCacheOptions, MemoryExtendedCacheDriver, MemoryExtendedCacheOptions, MockCacheDriver, MockCacheOptions, NormalizedCachedConfig, NormalizedSetOptions, NullCacheDriver, NullCacheDriverOptions, PgCacheDriver, PgCacheOptions, PgClientLike, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisOptions, RememberOptions, ScopedCache, ScopedCacheContract, TaggedCache, TaggedCacheDriver, TaggedScopedCache, TaggedScopedCacheContract, cache, cached, cosineSimilarity, deriveAutoKey, expiresAtToTtl, injectTags, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
34
+ export { BaseCacheDriver, type BloomFilter, type BloomOptions, CACHE_FOR, CacheCall, CacheConcurrencyError, CacheConfigurationError, CacheConfigurations, CacheConflictPolicy, CacheConnectionError, CacheData, CacheDriver, CacheDriverNotInitializedError, CacheError, CacheEventData, CacheEventHandler, CacheEventType, CacheKey, CacheListAccessor, CacheManager, CacheMetricsCollector, CacheMetricsSnapshot, CacheNamespaceOptions, CacheOperationType, CacheSetOptions, CacheSetResult, CacheSimilarHit, CacheSimilarOptions, type CacheStructures, type CacheStructuresBackend, CacheSwrOptions, CacheTtl, CacheUnsupportedError, CachedFn, CachedOptions, type CuckooFilter, type CuckooOptions, DriverClass, FileCacheDriver, FileCacheOptions, type FrequencyEntry, type FrequencyOptions, type FrequencyTracker, type IdempotentOptions, LRUMemoryCacheDriver, LRUMemoryCacheOptions, LockOptions, LockOutcome, MemoryCacheDriver, MemoryCacheList, MemoryCacheOptions, MemoryExtendedCacheDriver, MemoryExtendedCacheOptions, MemoryStructuresBackend, MockCacheDriver, MockCacheOptions, type NativeStructures, NormalizedCachedConfig, NormalizedSetOptions, NullCacheDriver, NullCacheDriverOptions, PgCacheDriver, PgCacheOptions, PgClientLike, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisOptions, RedisStructuresBackend, RememberOptions, ScopedCache, ScopedCacheContract, type StructureOptions, type StructuresCapable, TaggedCache, TaggedCacheDriver, TaggedScopedCache, TaggedScopedCacheContract, type UniqueCounter, type UniqueCounterFactory, type UniqueCounterGroup, type UniqueCounterOptions, cache, cached, cosineSimilarity, deriveAutoKey, expiresAtToTtl, idempotent, injectTags, isStructuresCapable, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
package/esm/index.mjs CHANGED
@@ -1,9 +1,13 @@
1
- import { CacheMetricsCollector } from "./metrics.mjs";
2
1
  import { CacheConcurrencyError, CacheConfigurationError, CacheConnectionError, CacheDriverNotInitializedError, CacheError, CacheUnsupportedError } from "./types.mjs";
3
2
  import { CACHE_FOR, cosineSimilarity, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo } from "./utils.mjs";
3
+ import { CacheMetricsCollector } from "./metrics.mjs";
4
4
  import { TaggedScopedCache } from "./tagged-scoped-cache.mjs";
5
5
  import { ScopedCache } from "./scoped-cache.mjs";
6
- import { CacheManager, cache } from "./cache-manager.mjs";
6
+ import { MemoryStructuresBackend } from "./structures/memory-structures-backend.mjs";
7
+ import { RedisStructuresBackend } from "./structures/redis-structures-backend.mjs";
8
+ import { isStructuresCapable } from "./structures/types.mjs";
9
+ import "./structures/index.mjs";
10
+ import { CacheManager, cache, idempotent } from "./cache-manager.mjs";
7
11
  import { deriveAutoKey } from "./cached/auto-key.mjs";
8
12
  import { normalizeCachedArgs } from "./cached/normalize-args.mjs";
9
13
  import { cached } from "./cached/cached.mjs";
@@ -21,4 +25,4 @@ import { PgCacheDriver } from "./drivers/pg-cache-driver.mjs";
21
25
  import { REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver } from "./drivers/redis-cache-driver.mjs";
22
26
  import "./drivers/index.mjs";
23
27
 
24
- export { BaseCacheDriver, CACHE_FOR, CacheConcurrencyError, CacheConfigurationError, CacheConnectionError, CacheDriverNotInitializedError, CacheError, CacheManager, CacheMetricsCollector, CacheUnsupportedError, FileCacheDriver, LRUMemoryCacheDriver, MemoryCacheDriver, MemoryCacheList, MemoryExtendedCacheDriver, MockCacheDriver, NullCacheDriver, PgCacheDriver, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, ScopedCache, TaggedCache, TaggedScopedCache, cache, cached, cosineSimilarity, deriveAutoKey, expiresAtToTtl, injectTags, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
28
+ export { BaseCacheDriver, CACHE_FOR, CacheConcurrencyError, CacheConfigurationError, CacheConnectionError, CacheDriverNotInitializedError, CacheError, CacheManager, CacheMetricsCollector, CacheUnsupportedError, FileCacheDriver, LRUMemoryCacheDriver, MemoryCacheDriver, MemoryCacheList, MemoryExtendedCacheDriver, MemoryStructuresBackend, MockCacheDriver, NullCacheDriver, PgCacheDriver, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisStructuresBackend, ScopedCache, TaggedCache, TaggedScopedCache, cache, cached, cosineSimilarity, deriveAutoKey, expiresAtToTtl, idempotent, injectTags, isStructuresCapable, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
@@ -139,6 +139,11 @@ export declare class ScopedCache implements ScopedCacheContract {
139
139
  increment(key: CacheKey, value?: number, options?: {
140
140
  ttl?: CacheTtl;
141
141
  }): Promise<number>;
142
+ /**
143
+ * Reset the expiry of the scoped key to `ttl` from now. Resolves to `false`
144
+ * when the key is missing. See `CacheDriver.extend`.
145
+ */
146
+ extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;
142
147
  /**
143
148
  * Atomic counter decrement on the scoped key. See {@link increment} for
144
149
  * TTL semantics.
@@ -1 +1 @@
1
- {"version":3,"file":"scoped-cache.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/scoped-cache.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAsDa,uBAAuB;;;;;;WAMlB;;;;;;;;WASA,QAAQ;;;;;;;WAQR,UAAU;;;;;EAM1B,YACE,QAAQ,uBACR,gBACA,WAAU;;;;;;;;;;EAmBL,UAAU,gBAAgB,UAAS,wBAA6B;;;;;;EAchE,KAAK,iBAAiB;;;;;;EAStB,SAAS;;;;EAOT,IAAI,SAAS,KAAK,WAAW,QAAQ;;;;EAOrC,IAAI,KAAK,WAAW;;;;EAOpB,KAAK,MAAM,aAAa;;;;EAOxB,KAAK,SAAS,KAAK,WAAW,QAAQ;;;;;;EAStC,IAAI,KAAK,UAAU,YAAY,eAAe,WAAW,kBAAkB;;;;;;EAS3E,QAAQ,OAAO,qBAAqB,eAAe;;;;;EAcnD,MAAM,KAAK,UAAU,YAAY,eAAe;;;;;EAYhD,QAAQ,SAAS,KAAK,UAAU,OAAO,IAAI,QAAQ;;;;EAOnD,OAAO,KAAK,WAAW;;;;;EAQvB,SAAS,SACd,KAAK,UACL,cAAc,WAAW,iBACzB,gBAAgB,QAAQ,KACvB,QAAQ;;;;;;;EAcJ,IAAI,SACT,KAAK,UACL,SAAS,iBACT,gBAAgB,QAAQ,KACvB,QAAQ;;;;;EAaJ,UAAU,KAAK,UAAU,gBAAgB;IAAY,MAAM;MAAa;;;;;EAUxE,UAAU,KAAK,UAAU,iBAAiB;;;;;;;EAUpC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d,KAAK,UACL,cAAc,WAAW,iBACzB,gBAAgB,QAAQ,KACvB,QAAQ;;;;;;;EAcJ,IAAI,SACT,KAAK,UACL,SAAS,iBACT,gBAAgB,QAAQ,KACvB,QAAQ;;;;;EAaJ,UAAU,KAAK,UAAU,gBAAgB;IAAY,MAAM;MAAa;;;;;EAUxE,OAAO,KAAK,UAAU,KAAK,WAAW;;;;;EAQtC,UAAU,KAAK,UAAU,iBAAiB;;;;;;;EAUpC,OAAO,SAClB,KAAK,UACL,KAAK,SAAS,aAAa,WAAW,QAAQ,WAC9C;IAAY,MAAM;MACjB,QAAQ;;;;;EAUE,MAAM,UAAU,sBAAsB,qBACjD,KAAK,UACL,SAAS,QAAQ,IACjB;IAAY,MAAM;MACjB,QAAQ;;;;;UAUG;;;;;EAmBP,KAAK,SAAS,KAAK,WAAW,kBAAkB;;;;;EAQhD,KAAK,GACV,KAAK,UACL,cAAc,WAAW,KAAK,wBAC9B,UAAU,QAAQ,KACjB,QAAQ,YAAY;;;;;;;EAsBV,QAAQ,SACnB,kBACA,SAAS,sBACR,QAAQ,gBAAgB;;;;;;YAYjB,UAAU,KAAK;;;;;;;YAgBf,gBAAgB,QAAQ,WAAW,kBAAkB;;;;;YAsBrD,qBAAqB,OAAO,WAAW,kBAAkB,WAAW;;;;;;YAuBpE"}
@@ -167,6 +167,13 @@ var ScopedCache = class ScopedCache {
167
167
  return this.source.increment(this.scopedKey(key), value, { ttl: options?.ttl ?? this.defaults.ttl });
168
168
  }
169
169
  /**
170
+ * Reset the expiry of the scoped key to `ttl` from now. Resolves to `false`
171
+ * when the key is missing. See `CacheDriver.extend`.
172
+ */
173
+ extend(key, ttl) {
174
+ return this.source.extend(this.scopedKey(key), ttl);
175
+ }
176
+ /**
170
177
  * Atomic counter decrement on the scoped key. See {@link increment} for
171
178
  * TTL semantics.
172
179
  */
@@ -1 +1 @@
1
- {"version":3,"file":"scoped-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/scoped-cache.ts"],"sourcesContent":["import { TaggedScopedCache } from \"./tagged-scoped-cache\";\nimport type {\n CacheDriver,\n CacheKey,\n CacheListAccessor,\n CacheNamespaceOptions,\n CacheSetOptions,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheSwrOptions,\n CacheTtl,\n LockOptions,\n LockOutcome,\n RememberOptions,\n ScopedCacheContract,\n TaggedScopedCacheContract,\n} from \"./types\";\nimport {\n mergeTagSets,\n normalizeToOptions,\n normalizeToRememberOptions,\n parseCacheKey,\n parseTtl,\n} from \"./utils\";\n\n/**\n * Scoped view over a cache source. Returned by `cache.namespace(prefix, options?)`.\n *\n * **Role.** A `ScopedCache` is a stateless wrapper that prepends a fixed\n * prefix to every key and applies optional default `ttl` / `tags` to every\n * write. Stores nothing itself — every call forwards to the underlying\n * `source` (typically the `CacheManager`, but any `CacheDriver` works).\n *\n * **Responsibility.**\n * - Owns: prefix-prepending of keys, normalization of nested-scope prefixes,\n * merging scope defaults into write options (`ttl`, `tags`), filtering\n * `similar()` hits to its own scope, and exposing `.clear()` as a sugar\n * for `removeNamespace(prefix)`.\n * - Does NOT own: actual storage, connection lifecycle, event listeners,\n * driver selection, or tag-index bookkeeping (delegated to the source's\n * tagged-cache machinery).\n *\n * Per-call options always win over scope defaults; tags merge additively\n * across (scope defaults + per-call) layers. Nested scopes inherit and may\n * override the parent's defaults — see {@link ScopedCache.namespace}.\n *\n * @example\n * const chat = cache.namespace(`chats.${id}`, { ttl: \"30d\" });\n *\n * await chat.set(\"messages.10\", msg); // 30d default\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call override\n * await chat.namespace(\"typing\", { ttl: \"5s\" }).set(\"user.42\", true);\n * await chat.clear();\n */\nexport class ScopedCache implements ScopedCacheContract {\n /**\n * Fully-qualified prefix prepended to every key handled by this scope.\n * Normalized through {@link parseCacheKey} on construction so colon-form\n * input (`\"chats:10\"`) and trailing dots compose cleanly with nested scopes.\n */\n public readonly prefix: string;\n\n /**\n * Underlying cache source. Public-readonly so co-located helpers\n * (`TaggedScopedCache`) can delegate without ceremony — not part of the\n * stable consumer API.\n *\n * @internal\n */\n public readonly source: CacheDriver<any, any>;\n\n /**\n * Defaults applied to every write through this scope. Per-call options\n * override `ttl`; `tags` merge additively across layers.\n *\n * @internal\n */\n public readonly defaults: CacheNamespaceOptions;\n\n /**\n * Build a scope. Constructed via `cache.namespace(prefix, options)` —\n * users never call this directly.\n */\n public constructor(\n source: CacheDriver<any, any>,\n prefix: string,\n defaults: CacheNamespaceOptions = {},\n ) {\n this.source = source;\n this.prefix = parseCacheKey(prefix);\n this.defaults = {\n ttl: defaults.ttl,\n tags: defaults.tags && defaults.tags.length > 0 ? [...defaults.tags] : undefined,\n };\n }\n\n /**\n * Build a nested scope. The child's prefix is `parent.child`; child options\n * override the parent's `ttl` and union into `tags`.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * const typing = chat.namespace(\"typing\", { ttl: \"5s\" });\n * // typing.prefix === \"chats.10.typing\"\n */\n public namespace(prefix: string, options: CacheNamespaceOptions = {}): ScopedCacheContract {\n const childPrefix = `${this.prefix}.${parseCacheKey(prefix)}`;\n\n return new ScopedCache(this.source, childPrefix, {\n ttl: options.ttl ?? this.defaults.ttl,\n tags: mergeTagSets(this.defaults.tags, options.tags),\n });\n }\n\n /**\n * Return a one-shot tagged write handle. The handle's tags merge additively\n * with scope-level defaults — final tag list per write is the union of\n * (scope tags + handle tags + per-call tags), deduped.\n */\n public tags(tags: string[]): TaggedScopedCacheContract {\n return new TaggedScopedCache(this, tags);\n }\n\n /**\n * Wipe every entry under this scope's prefix. Sugar over\n * `source.removeNamespace(prefix)` — siblings outside the scope are\n * untouched.\n */\n public clear(): Promise<void> {\n return this.source.removeNamespace(this.prefix);\n }\n\n /**\n * Read the value at the scoped key. Forwards to the source after prefixing.\n */\n public get<T = any>(key: CacheKey): Promise<T | null> {\n return this.source.get<T>(this.scopedKey(key));\n }\n\n /**\n * Check presence of the scoped key without fetching the value.\n */\n public has(key: CacheKey): Promise<boolean> {\n return this.source.has(this.scopedKey(key));\n }\n\n /**\n * Batch-read scoped keys. Each input key is prefixed before forwarding.\n */\n public many(keys: CacheKey[]): Promise<any[]> {\n return this.source.many(keys.map((key) => this.scopedKey(key)));\n }\n\n /**\n * Read-and-remove. Returns the value or `null`; the entry is gone after.\n */\n public pull<T = any>(key: CacheKey): Promise<T | null> {\n return this.source.pull<T>(this.scopedKey(key));\n }\n\n /**\n * Write the scoped key. Per-call `ttl`/`tags` win over scope defaults;\n * `expiresAt` is preserved as-is (absolute deadlines are never overridden\n * by the scope's relative-ttl default).\n */\n public set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any> {\n return this.source.set(this.scopedKey(key), value, this.mergeSetOptions(ttlOrOptions));\n }\n\n /**\n * Batch-write under the scope. Caller's positional `ttl` wins; otherwise\n * the scope default is parsed to seconds (since `setMany` accepts only a\n * numeric ttl).\n */\n public setMany(items: Record<string, any>, ttl?: number): Promise<void> {\n const scoped: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(items)) {\n scoped[this.scopedKey(key)] = value;\n }\n\n return this.source.setMany(scoped, ttl ?? this.scopeTtlSeconds());\n }\n\n /**\n * Atomic create-or-skip on the scoped key. Throws when the underlying\n * source has no `setNX` (driver-specific — Redis-only today).\n */\n public setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean> {\n if (!this.source.setNX) {\n throw new Error(`setNX is not supported by the underlying cache source: ${this.source.name}`);\n }\n\n return this.source.setNX(this.scopedKey(key), value, ttl ?? this.scopeTtlSeconds());\n }\n\n /**\n * Permanent write (no expiration). Bypasses the scope's `ttl` default —\n * `forever` always means forever, regardless of scope policy.\n */\n public forever<T = any>(key: CacheKey, value: T): Promise<T> {\n return this.source.forever<T>(this.scopedKey(key), value);\n }\n\n /**\n * Remove a single scoped key.\n */\n public remove(key: CacheKey): Promise<void> {\n return this.source.remove(this.scopedKey(key));\n }\n\n /**\n * Read-or-compute. Cache-miss writes pick up the scope's default `ttl`\n * and `tags` unless the caller passed an options object that overrides.\n */\n public remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n return this.source.remember<T>(\n this.scopedKey(key),\n this.mergeRememberOptions(ttlOrOptions),\n callback,\n );\n }\n\n /**\n * Stale-while-revalidate on the scoped key. Scope-level `tags` merge\n * additively with `options.tags`; `freshTtl`/`staleTtl` always come from\n * the caller (no scope-default precedence — the SWR shape is too\n * specific to the call site to inherit).\n */\n public swr<T = any>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n const merged: CacheSwrOptions = {\n ...options,\n tags: mergeTagSets(this.defaults.tags, options.tags),\n };\n\n return this.source.swr<T>(this.scopedKey(key), merged, callback);\n }\n\n /**\n * Atomic counter increment on the scoped key. TTL is preserved by the\n * underlying driver — scope ttl is only applied on first write via `set`.\n */\n public increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number> {\n return this.source.increment(this.scopedKey(key), value, {\n ttl: options?.ttl ?? this.defaults.ttl,\n });\n }\n\n /**\n * Atomic counter decrement on the scoped key. See {@link increment} for\n * TTL semantics.\n */\n public decrement(key: CacheKey, value?: number): Promise<number> {\n return this.source.decrement(this.scopedKey(key), value);\n }\n\n /**\n * Atomic read-modify-write. An explicit `options.ttl` always wins. Otherwise\n * the scope's default `ttl` is applied only when the key does not exist yet;\n * for an existing key no ttl is passed so the source preserves the entry's\n * remaining TTL.\n */\n public async update<T = any>(\n key: CacheKey,\n fn: (current: T | null) => T | null | Promise<T | null>,\n options?: { ttl?: CacheTtl },\n ): Promise<T | null> {\n const scopedKey = this.scopedKey(key);\n\n return this.source.update<T>(scopedKey, fn, await this.writeOptions(scopedKey, options));\n }\n\n /**\n * Shallow-merge a partial object into the scoped entry. Same TTL semantics\n * as {@link update}.\n */\n public async merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T> {\n const scopedKey = this.scopedKey(key);\n\n return this.source.merge<T>(scopedKey, partial, await this.writeOptions(scopedKey, options));\n }\n\n /**\n * Resolve the ttl options for update/merge: explicit ttl, else the scope\n * default only for keys that don't exist yet, else nothing (keep remaining).\n */\n private async writeOptions(\n scopedKey: CacheKey,\n options?: { ttl?: CacheTtl },\n ): Promise<{ ttl?: CacheTtl }> {\n if (options?.ttl !== undefined) {\n return { ttl: options.ttl };\n }\n\n if (this.defaults.ttl === undefined) {\n return {};\n }\n\n return (await this.source.has(scopedKey)) ? {} : { ttl: this.defaults.ttl };\n }\n\n /**\n * Return a list accessor bound to the scoped key. The accessor itself\n * does its own read-mutate-write under the prefixed entry.\n */\n public list<T = any>(key: CacheKey): CacheListAccessor<T> {\n return this.source.list<T>(this.scopedKey(key));\n }\n\n /**\n * Acquire a distributed lock on the scoped key. Caller's TTL wins; when\n * the options form omits `ttl`, the scope default fills in.\n */\n public lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>> {\n if (typeof ttlOrOptions === \"object\" && ttlOrOptions !== null) {\n const merged: Omit<LockOptions, \"driver\"> = {\n ...ttlOrOptions,\n ttl: ttlOrOptions.ttl ?? this.defaults.ttl ?? ttlOrOptions.ttl,\n };\n\n // The third coalesce is intentional — when both caller and scope omit\n // the TTL, we still pass the original (undefined) through so the source\n // raises its own validation error rather than us swallowing it silently.\n return this.source.lock<T>(this.scopedKey(key), merged, fn);\n }\n\n return this.source.lock<T>(this.scopedKey(key), ttlOrOptions, fn);\n }\n\n /**\n * Similarity retrieval, scope-isolated. Hits whose keys fall outside this\n * scope are filtered out before the result is returned. `topK` applies to\n * the underlying retrieval — when the scope contains fewer than `topK`\n * matches but other scopes do, the caller will see fewer hits than `topK`.\n */\n public async similar<T = any>(\n vector: number[],\n options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n const hits = await this.source.similar<T>(vector, options);\n const parsedPrefix = this.source.parseKey(this.prefix);\n\n return hits.filter((hit) => hit.key === parsedPrefix || hit.key.startsWith(parsedPrefix + \".\"));\n }\n\n /**\n * Build the source-side key by prepending the scope prefix. Object keys\n * are normalized via {@link parseCacheKey} first so they compose with the\n * prefix as plain dot-strings.\n */\n protected scopedKey(key: CacheKey): string {\n const keyString = typeof key === \"string\" ? key : parseCacheKey(key);\n\n if (!keyString) {\n return this.prefix;\n }\n\n return `${this.prefix}.${keyString}`;\n }\n\n /**\n * Coerce the polymorphic 3rd `set` argument into a {@link CacheSetOptions}\n * with scope defaults filled in. Per-call values always win; tags merge\n * additively. `expiresAt` is preserved without injecting the scope's `ttl`\n * default (absolute deadlines override relative ones).\n */\n protected mergeSetOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions | undefined {\n const options = normalizeToOptions(input);\n const ttl = options.ttl ?? (options.expiresAt === undefined ? this.defaults.ttl : undefined);\n const tags = mergeTagSets(this.defaults.tags, options.tags);\n\n const merged: CacheSetOptions = { ...options };\n\n if (ttl !== undefined) {\n merged.ttl = ttl;\n }\n\n if (tags !== undefined) {\n merged.tags = tags;\n }\n\n return merged;\n }\n\n /**\n * Same merge as {@link mergeSetOptions} but for the `remember()` shape\n * ({@link RememberOptions} — no `expiresAt`).\n */\n protected mergeRememberOptions(input: CacheTtl | RememberOptions): CacheTtl | RememberOptions {\n const options = normalizeToRememberOptions(input);\n const ttl = options.ttl ?? this.defaults.ttl;\n const tags = mergeTagSets(this.defaults.tags, options.tags);\n\n const merged: RememberOptions = { ...options };\n\n if (ttl !== undefined) {\n merged.ttl = ttl;\n }\n\n if (tags !== undefined) {\n merged.tags = tags;\n }\n\n return merged;\n }\n\n /**\n * Convert the scope's default `ttl` (which may be a duration string) into\n * seconds, for the few methods (`setMany`, `setNX`) that accept only a\n * numeric ttl.\n */\n protected scopeTtlSeconds(): number | undefined {\n if (this.defaults.ttl === undefined) {\n return undefined;\n }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W,eAAe,GAAG,CAAC;CAChG;;;;;;CAOA,AAAU,UAAU,KAAuB;EACzC,MAAM,YAAY,OAAO,QAAQ,WAAW,MAAM,cAAc,GAAG;EAEnE,IAAI,CAAC,WACH,OAAO,KAAK;EAGd,OAAO,GAAG,KAAK,OAAO,GAAG;CAC3B;;;;;;;CAQA,AAAU,gBAAgB,OAAiE;EACzF,MAAM,UAAU,mBAAmB,KAAK;EACxC,MAAM,MAAM,QAAQ,QAAQ,QAAQ,cAAc,SAAY,KAAK,SAAS,MAAM;EAClF,MAAM,OAAO,aAAa,KAAK,SAAS,MAAM,QAAQ,IAAI;EAE1D,MAAM,SAA0B,EAAE,GAAG,QAAQ;EAE7C,IAAI,QAAQ,QACV,OAAO,MAAM;EAGf,IAAI,SAAS,QACX,OAAO,OAAO;EAGhB,OAAO;CACT;;;;;CAMA,AAAU,qBAAqB,OAA+D;EAC5F,MAAM,UAAU,2BAA2B,KAAK;EAChD,MAAM,MAAM,QAAQ,OAAO,KAAK,SAAS;EACzC,MAAM,OAAO,aAAa,KAAK,SAAS,MAAM,QAAQ,IAAI;EAE1D,MAAM,SAA0B,EAAE,GAAG,QAAQ;EAE7C,IAAI,QAAQ,QACV,OAAO,MAAM;EAGf,IAAI,SAAS,QACX,OAAO,OAAO;EAGhB,OAAO;CACT;;;;;;CAOA,AAAU,kBAAsC;EAC9C,IAAI,KAAK,SAAS,QAAQ,QACxB;EAGF,OAAO,SAAS,KAAK,SAAS,GAAG;CACnC;AACF"}
1
+ {"version":3,"file":"scoped-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/scoped-cache.ts"],"sourcesContent":["import { TaggedScopedCache } from \"./tagged-scoped-cache\";\nimport type {\n CacheDriver,\n CacheKey,\n CacheListAccessor,\n CacheNamespaceOptions,\n CacheSetOptions,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheSwrOptions,\n CacheTtl,\n LockOptions,\n LockOutcome,\n RememberOptions,\n ScopedCacheContract,\n TaggedScopedCacheContract,\n} from \"./types\";\nimport {\n mergeTagSets,\n normalizeToOptions,\n normalizeToRememberOptions,\n parseCacheKey,\n parseTtl,\n} from \"./utils\";\n\n/**\n * Scoped view over a cache source. Returned by `cache.namespace(prefix, options?)`.\n *\n * **Role.** A `ScopedCache` is a stateless wrapper that prepends a fixed\n * prefix to every key and applies optional default `ttl` / `tags` to every\n * write. Stores nothing itself — every call forwards to the underlying\n * `source` (typically the `CacheManager`, but any `CacheDriver` works).\n *\n * **Responsibility.**\n * - Owns: prefix-prepending of keys, normalization of nested-scope prefixes,\n * merging scope defaults into write options (`ttl`, `tags`), filtering\n * `similar()` hits to its own scope, and exposing `.clear()` as a sugar\n * for `removeNamespace(prefix)`.\n * - Does NOT own: actual storage, connection lifecycle, event listeners,\n * driver selection, or tag-index bookkeeping (delegated to the source's\n * tagged-cache machinery).\n *\n * Per-call options always win over scope defaults; tags merge additively\n * across (scope defaults + per-call) layers. Nested scopes inherit and may\n * override the parent's defaults — see {@link ScopedCache.namespace}.\n *\n * @example\n * const chat = cache.namespace(`chats.${id}`, { ttl: \"30d\" });\n *\n * await chat.set(\"messages.10\", msg); // 30d default\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call override\n * await chat.namespace(\"typing\", { ttl: \"5s\" }).set(\"user.42\", true);\n * await chat.clear();\n */\nexport class ScopedCache implements ScopedCacheContract {\n /**\n * Fully-qualified prefix prepended to every key handled by this scope.\n * Normalized through {@link parseCacheKey} on construction so colon-form\n * input (`\"chats:10\"`) and trailing dots compose cleanly with nested scopes.\n */\n public readonly prefix: string;\n\n /**\n * Underlying cache source. Public-readonly so co-located helpers\n * (`TaggedScopedCache`) can delegate without ceremony — not part of the\n * stable consumer API.\n *\n * @internal\n */\n public readonly source: CacheDriver<any, any>;\n\n /**\n * Defaults applied to every write through this scope. Per-call options\n * override `ttl`; `tags` merge additively across layers.\n *\n * @internal\n */\n public readonly defaults: CacheNamespaceOptions;\n\n /**\n * Build a scope. Constructed via `cache.namespace(prefix, options)` —\n * users never call this directly.\n */\n public constructor(\n source: CacheDriver<any, any>,\n prefix: string,\n defaults: CacheNamespaceOptions = {},\n ) {\n this.source = source;\n this.prefix = parseCacheKey(prefix);\n this.defaults = {\n ttl: defaults.ttl,\n tags: defaults.tags && defaults.tags.length > 0 ? [...defaults.tags] : undefined,\n };\n }\n\n /**\n * Build a nested scope. The child's prefix is `parent.child`; child options\n * override the parent's `ttl` and union into `tags`.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * const typing = chat.namespace(\"typing\", { ttl: \"5s\" });\n * // typing.prefix === \"chats.10.typing\"\n */\n public namespace(prefix: string, options: CacheNamespaceOptions = {}): ScopedCacheContract {\n const childPrefix = `${this.prefix}.${parseCacheKey(prefix)}`;\n\n return new ScopedCache(this.source, childPrefix, {\n ttl: options.ttl ?? this.defaults.ttl,\n tags: mergeTagSets(this.defaults.tags, options.tags),\n });\n }\n\n /**\n * Return a one-shot tagged write handle. The handle's tags merge additively\n * with scope-level defaults — final tag list per write is the union of\n * (scope tags + handle tags + per-call tags), deduped.\n */\n public tags(tags: string[]): TaggedScopedCacheContract {\n return new TaggedScopedCache(this, tags);\n }\n\n /**\n * Wipe every entry under this scope's prefix. Sugar over\n * `source.removeNamespace(prefix)` — siblings outside the scope are\n * untouched.\n */\n public clear(): Promise<void> {\n return this.source.removeNamespace(this.prefix);\n }\n\n /**\n * Read the value at the scoped key. Forwards to the source after prefixing.\n */\n public get<T = any>(key: CacheKey): Promise<T | null> {\n return this.source.get<T>(this.scopedKey(key));\n }\n\n /**\n * Check presence of the scoped key without fetching the value.\n */\n public has(key: CacheKey): Promise<boolean> {\n return this.source.has(this.scopedKey(key));\n }\n\n /**\n * Batch-read scoped keys. Each input key is prefixed before forwarding.\n */\n public many(keys: CacheKey[]): Promise<any[]> {\n return this.source.many(keys.map((key) => this.scopedKey(key)));\n }\n\n /**\n * Read-and-remove. Returns the value or `null`; the entry is gone after.\n */\n public pull<T = any>(key: CacheKey): Promise<T | null> {\n return this.source.pull<T>(this.scopedKey(key));\n }\n\n /**\n * Write the scoped key. Per-call `ttl`/`tags` win over scope defaults;\n * `expiresAt` is preserved as-is (absolute deadlines are never overridden\n * by the scope's relative-ttl default).\n */\n public set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any> {\n return this.source.set(this.scopedKey(key), value, this.mergeSetOptions(ttlOrOptions));\n }\n\n /**\n * Batch-write under the scope. Caller's positional `ttl` wins; otherwise\n * the scope default is parsed to seconds (since `setMany` accepts only a\n * numeric ttl).\n */\n public setMany(items: Record<string, any>, ttl?: number): Promise<void> {\n const scoped: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(items)) {\n scoped[this.scopedKey(key)] = value;\n }\n\n return this.source.setMany(scoped, ttl ?? this.scopeTtlSeconds());\n }\n\n /**\n * Atomic create-or-skip on the scoped key. Throws when the underlying\n * source has no `setNX` (driver-specific — Redis-only today).\n */\n public setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean> {\n if (!this.source.setNX) {\n throw new Error(`setNX is not supported by the underlying cache source: ${this.source.name}`);\n }\n\n return this.source.setNX(this.scopedKey(key), value, ttl ?? this.scopeTtlSeconds());\n }\n\n /**\n * Permanent write (no expiration). Bypasses the scope's `ttl` default —\n * `forever` always means forever, regardless of scope policy.\n */\n public forever<T = any>(key: CacheKey, value: T): Promise<T> {\n return this.source.forever<T>(this.scopedKey(key), value);\n }\n\n /**\n * Remove a single scoped key.\n */\n public remove(key: CacheKey): Promise<void> {\n return this.source.remove(this.scopedKey(key));\n }\n\n /**\n * Read-or-compute. Cache-miss writes pick up the scope's default `ttl`\n * and `tags` unless the caller passed an options object that overrides.\n */\n public remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n return this.source.remember<T>(\n this.scopedKey(key),\n this.mergeRememberOptions(ttlOrOptions),\n callback,\n );\n }\n\n /**\n * Stale-while-revalidate on the scoped key. Scope-level `tags` merge\n * additively with `options.tags`; `freshTtl`/`staleTtl` always come from\n * the caller (no scope-default precedence — the SWR shape is too\n * specific to the call site to inherit).\n */\n public swr<T = any>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n const merged: CacheSwrOptions = {\n ...options,\n tags: mergeTagSets(this.defaults.tags, options.tags),\n };\n\n return this.source.swr<T>(this.scopedKey(key), merged, callback);\n }\n\n /**\n * Atomic counter increment on the scoped key. TTL is preserved by the\n * underlying driver — scope ttl is only applied on first write via `set`.\n */\n public increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number> {\n return this.source.increment(this.scopedKey(key), value, {\n ttl: options?.ttl ?? this.defaults.ttl,\n });\n }\n\n /**\n * Reset the expiry of the scoped key to `ttl` from now. Resolves to `false`\n * when the key is missing. See `CacheDriver.extend`.\n */\n public extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n return this.source.extend(this.scopedKey(key), ttl);\n }\n\n /**\n * Atomic counter decrement on the scoped key. See {@link increment} for\n * TTL semantics.\n */\n public decrement(key: CacheKey, value?: number): Promise<number> {\n return this.source.decrement(this.scopedKey(key), value);\n }\n\n /**\n * Atomic read-modify-write. An explicit `options.ttl` always wins. Otherwise\n * the scope's default `ttl` is applied only when the key does not exist yet;\n * for an existing key no ttl is passed so the source preserves the entry's\n * remaining TTL.\n */\n public async update<T = any>(\n key: CacheKey,\n fn: (current: T | null) => T | null | Promise<T | null>,\n options?: { ttl?: CacheTtl },\n ): Promise<T | null> {\n const scopedKey = this.scopedKey(key);\n\n return this.source.update<T>(scopedKey, fn, await this.writeOptions(scopedKey, options));\n }\n\n /**\n * Shallow-merge a partial object into the scoped entry. Same TTL semantics\n * as {@link update}.\n */\n public async merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T> {\n const scopedKey = this.scopedKey(key);\n\n return this.source.merge<T>(scopedKey, partial, await this.writeOptions(scopedKey, options));\n }\n\n /**\n * Resolve the ttl options for update/merge: explicit ttl, else the scope\n * default only for keys that don't exist yet, else nothing (keep remaining).\n */\n private async writeOptions(\n scopedKey: CacheKey,\n options?: { ttl?: CacheTtl },\n ): Promise<{ ttl?: CacheTtl }> {\n if (options?.ttl !== undefined) {\n return { ttl: options.ttl };\n }\n\n if (this.defaults.ttl === undefined) {\n return {};\n }\n\n return (await this.source.has(scopedKey)) ? {} : { ttl: this.defaults.ttl };\n }\n\n /**\n * Return a list accessor bound to the scoped key. The accessor itself\n * does its own read-mutate-write under the prefixed entry.\n */\n public list<T = any>(key: CacheKey): CacheListAccessor<T> {\n return this.source.list<T>(this.scopedKey(key));\n }\n\n /**\n * Acquire a distributed lock on the scoped key. Caller's TTL wins; when\n * the options form omits `ttl`, the scope default fills in.\n */\n public lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>> {\n if (typeof ttlOrOptions === \"object\" && ttlOrOptions !== null) {\n const merged: Omit<LockOptions, \"driver\"> = {\n ...ttlOrOptions,\n ttl: ttlOrOptions.ttl ?? this.defaults.ttl ?? ttlOrOptions.ttl,\n };\n\n // The third coalesce is intentional — when both caller and scope omit\n // the TTL, we still pass the original (undefined) through so the source\n // raises its own validation error rather than us swallowing it silently.\n return this.source.lock<T>(this.scopedKey(key), merged, fn);\n }\n\n return this.source.lock<T>(this.scopedKey(key), ttlOrOptions, fn);\n }\n\n /**\n * Similarity retrieval, scope-isolated. Hits whose keys fall outside this\n * scope are filtered out before the result is returned. `topK` applies to\n * the underlying retrieval — when the scope contains fewer than `topK`\n * matches but other scopes do, the caller will see fewer hits than `topK`.\n */\n public async similar<T = any>(\n vector: number[],\n options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n const hits = await this.source.similar<T>(vector, options);\n const parsedPrefix = this.source.parseKey(this.prefix);\n\n return hits.filter((hit) => hit.key === parsedPrefix || hit.key.startsWith(parsedPrefix + \".\"));\n }\n\n /**\n * Build the source-side key by prepending the scope prefix. Object keys\n * are normalized via {@link parseCacheKey} first so they compose with the\n * prefix as plain dot-strings.\n */\n protected scopedKey(key: CacheKey): string {\n const keyString = typeof key === \"string\" ? key : parseCacheKey(key);\n\n if (!keyString) {\n return this.prefix;\n }\n\n return `${this.prefix}.${keyString}`;\n }\n\n /**\n * Coerce the polymorphic 3rd `set` argument into a {@link CacheSetOptions}\n * with scope defaults filled in. Per-call values always win; tags merge\n * additively. `expiresAt` is preserved without injecting the scope's `ttl`\n * default (absolute deadlines override relative ones).\n */\n protected mergeSetOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions | undefined {\n const options = normalizeToOptions(input);\n const ttl = options.ttl ?? (options.expiresAt === undefined ? this.defaults.ttl : undefined);\n const tags = mergeTagSets(this.defaults.tags, options.tags);\n\n const merged: CacheSetOptions = { ...options };\n\n if (ttl !== undefined) {\n merged.ttl = ttl;\n }\n\n if (tags !== undefined) {\n merged.tags = tags;\n }\n\n return merged;\n }\n\n /**\n * Same merge as {@link mergeSetOptions} but for the `remember()` shape\n * ({@link RememberOptions} — no `expiresAt`).\n */\n protected mergeRememberOptions(input: CacheTtl | RememberOptions): CacheTtl | RememberOptions {\n const options = normalizeToRememberOptions(input);\n const ttl = options.ttl ?? this.defaults.ttl;\n const tags = mergeTagSets(this.defaults.tags, options.tags);\n\n const merged: RememberOptions = { ...options };\n\n if (ttl !== undefined) {\n merged.ttl = ttl;\n }\n\n if (tags !== undefined) {\n merged.tags = tags;\n }\n\n return merged;\n }\n\n /**\n * Convert the scope's default `ttl` (which may be a duration string) into\n * seconds, for the few methods (`setMany`, `setNX`) that accept only a\n * numeric ttl.\n */\n protected scopeTtlSeconds(): number | undefined {\n if (this.defaults.ttl === undefined) {\n return undefined;\n }\n\n return parseTtl(this.defaults.ttl);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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BAAgB,IAAI,IAAI,WAAW,eAAe,GAAG,CAAC;CAChG;;;;;;CAOA,AAAU,UAAU,KAAuB;EACzC,MAAM,YAAY,OAAO,QAAQ,WAAW,MAAM,cAAc,GAAG;EAEnE,IAAI,CAAC,WACH,OAAO,KAAK;EAGd,OAAO,GAAG,KAAK,OAAO,GAAG;CAC3B;;;;;;;CAQA,AAAU,gBAAgB,OAAiE;EACzF,MAAM,UAAU,mBAAmB,KAAK;EACxC,MAAM,MAAM,QAAQ,QAAQ,QAAQ,cAAc,SAAY,KAAK,SAAS,MAAM;EAClF,MAAM,OAAO,aAAa,KAAK,SAAS,MAAM,QAAQ,IAAI;EAE1D,MAAM,SAA0B,EAAE,GAAG,QAAQ;EAE7C,IAAI,QAAQ,QACV,OAAO,MAAM;EAGf,IAAI,SAAS,QACX,OAAO,OAAO;EAGhB,OAAO;CACT;;;;;CAMA,AAAU,qBAAqB,OAA+D;EAC5F,MAAM,UAAU,2BAA2B,KAAK;EAChD,MAAM,MAAM,QAAQ,OAAO,KAAK,SAAS;EACzC,MAAM,OAAO,aAAa,KAAK,SAAS,MAAM,QAAQ,IAAI;EAE1D,MAAM,SAA0B,EAAE,GAAG,QAAQ;EAE7C,IAAI,QAAQ,QACV,OAAO,MAAM;EAGf,IAAI,SAAS,QACX,OAAO,OAAO;EAGhB,OAAO;CACT;;;;;;CAOA,AAAU,kBAAsC;EAC9C,IAAI,KAAK,SAAS,QAAQ,QACxB;EAGF,OAAO,SAAS,KAAK,SAAS,GAAG;CACnC;AACF"}
@@ -0,0 +1,33 @@
1
+ import { BloomOptions, CacheStructuresBackend } from "./types.mjs";
2
+ //#region ../../packages/cache/src/structures/bloom-filter.d.ts
3
+ export type StructureContext = {
4
+ backend(): CacheStructuresBackend;
5
+ /** Seconds, or undefined for no expiry. */
6
+ ttl: number | undefined;
7
+ };
8
+ /**
9
+ * Bloom filter: answers "definitely not added" or "probably added".
10
+ * Items can be added but not removed or listed.
11
+ */
12
+ export declare class BloomFilter {
13
+ protected readonly key: string;
14
+ protected readonly context: StructureContext;
15
+ protected readonly bits: number;
16
+ protected readonly hashes: number;
17
+ protected readonly errorRate: number;
18
+ protected readonly capacity: number;
19
+ constructor(key: string, options: BloomOptions, context: StructureContext);
20
+ protected positions(item: string): number[];
21
+ /**
22
+ * Add an item. Resolves to `true` when the item was not (probably) present
23
+ * before and `false` when it probably was.
24
+ */
25
+ add(item: string | number): Promise<boolean>;
26
+ /**
27
+ * `false` means the item was definitely never added; `true` means it
28
+ * probably was (a small, configured share of `true` answers are wrong).
29
+ */
30
+ mightContain(item: string | number): Promise<boolean>;
31
+ }
32
+ //#endregion
33
+ //# sourceMappingURL=bloom-filter.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bloom-filter.d.mts","names":[],"sources":["../../../../../../../../packages/cache/src/structures/bloom-filter.ts"],"mappings":";;YAIY;EACV,WAAW;;EAEX;;;;;;qBAWW;qBAOU;qBAEA,SAAS;qBARX;qBACA;qBACA;qBACA;EAEnB,YACqB,aACnB,SAAS,cACU,SAAS;YAWpB,UAAU;;;;;EAUP,IAAI,wBAAwB;;;;;EAwB5B,aAAa,wBAAwB"}
@@ -0,0 +1,56 @@
1
+ import { hashPair, probe } from "./hash.mjs";
2
+ import { bloomGeometry } from "./sizing.mjs";
3
+
4
+ //#region ../../packages/cache/src/structures/bloom-filter.ts
5
+ async function nativeOf(backend) {
6
+ return backend.native ? backend.native() : null;
7
+ }
8
+ /**
9
+ * Bloom filter: answers "definitely not added" or "probably added".
10
+ * Items can be added but not removed or listed.
11
+ */
12
+ var BloomFilter = class {
13
+ constructor(key, options, context) {
14
+ this.key = key;
15
+ this.context = context;
16
+ this.errorRate = options.errorRate ?? .01;
17
+ this.capacity = options.expectedItems;
18
+ const geometry = bloomGeometry(options.expectedItems, this.errorRate);
19
+ this.bits = geometry.bits;
20
+ this.hashes = geometry.hashes;
21
+ }
22
+ positions(item) {
23
+ const hashes = hashPair(item);
24
+ return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.bits));
25
+ }
26
+ /**
27
+ * Add an item. Resolves to `true` when the item was not (probably) present
28
+ * before and `false` when it probably was.
29
+ */
30
+ async add(item) {
31
+ const value = String(item);
32
+ const backend = this.context.backend();
33
+ const native = await nativeOf(backend);
34
+ if (native) return native.bloomAdd(this.key, value, {
35
+ capacity: this.capacity,
36
+ errorRate: this.errorRate,
37
+ ttl: this.context.ttl
38
+ });
39
+ return (await backend.bitSet(this.key, this.positions(value), { ttl: this.context.ttl })).some((bit) => !bit);
40
+ }
41
+ /**
42
+ * `false` means the item was definitely never added; `true` means it
43
+ * probably was (a small, configured share of `true` answers are wrong).
44
+ */
45
+ async mightContain(item) {
46
+ const value = String(item);
47
+ const backend = this.context.backend();
48
+ const native = await nativeOf(backend);
49
+ if (native) return native.bloomExists(this.key, value);
50
+ return (await backend.bitGet(this.key, this.positions(value))).every(Boolean);
51
+ }
52
+ };
53
+
54
+ //#endregion
55
+ export { BloomFilter, nativeOf };
56
+ //# sourceMappingURL=bloom-filter.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bloom-filter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/bloom-filter.ts"],"sourcesContent":["import { hashPair, probe } from \"./hash\";\nimport { bloomGeometry } from \"./sizing\";\nimport type { BloomOptions, CacheStructuresBackend, NativeStructures } from \"./types\";\n\nexport type StructureContext = {\n backend(): CacheStructuresBackend;\n /** Seconds, or undefined for no expiry. */\n ttl: number | undefined;\n};\n\nexport async function nativeOf(backend: CacheStructuresBackend): Promise<NativeStructures | null> {\n return backend.native ? backend.native() : null;\n}\n\n/**\n * Bloom filter: answers \"definitely not added\" or \"probably added\".\n * Items can be added but not removed or listed.\n */\nexport class BloomFilter {\n protected readonly bits: number;\n protected readonly hashes: number;\n protected readonly errorRate: number;\n protected readonly capacity: number;\n\n public constructor(\n protected readonly key: string,\n options: BloomOptions,\n protected readonly context: StructureContext,\n ) {\n this.errorRate = options.errorRate ?? 0.01;\n this.capacity = options.expectedItems;\n\n const geometry = bloomGeometry(options.expectedItems, this.errorRate);\n\n this.bits = geometry.bits;\n this.hashes = geometry.hashes;\n }\n\n protected positions(item: string): number[] {\n const hashes = hashPair(item);\n\n return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.bits));\n }\n\n /**\n * Add an item. Resolves to `true` when the item was not (probably) present\n * before and `false` when it probably was.\n */\n public async add(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.bloomAdd(this.key, value, {\n capacity: this.capacity,\n errorRate: this.errorRate,\n ttl: this.context.ttl,\n });\n }\n\n const previous = await backend.bitSet(this.key, this.positions(value), {\n ttl: this.context.ttl,\n });\n\n return previous.some((bit) => !bit);\n }\n\n /**\n * `false` means the item was definitely never added; `true` means it\n * probably was (a small, configured share of `true` answers are wrong).\n */\n public async mightContain(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.bloomExists(this.key, value);\n }\n\n const bits = await backend.bitGet(this.key, this.positions(value));\n\n return bits.every(Boolean);\n }\n}\n"],"mappings":";;;;AAUA,eAAsB,SAAS,SAAmE;CAChG,OAAO,QAAQ,SAAS,QAAQ,OAAO,IAAI;AAC7C;;;;;AAMA,IAAa,cAAb,MAAyB;CAMvB,AAAO,YACL,AAAmB,KACnB,SACA,AAAmB,SACnB;EAHmB;EAEA;EAEnB,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,WAAW,QAAQ;EAExB,MAAM,WAAW,cAAc,QAAQ,eAAe,KAAK,SAAS;EAEpE,KAAK,OAAO,SAAS;EACrB,KAAK,SAAS,SAAS;CACzB;CAEA,AAAU,UAAU,MAAwB;EAC1C,MAAM,SAAS,SAAS,IAAI;EAE5B,OAAO,MAAM,KAAK,EAAE,QAAQ,KAAK,OAAO,IAAI,GAAG,UAAU,MAAM,QAAQ,OAAO,KAAK,IAAI,CAAC;CAC1F;;;;;CAMA,MAAa,IAAI,MAAyC;EACxD,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM,UAAU,KAAK,QAAQ,QAAQ;EACrC,MAAM,SAAS,MAAM,SAAS,OAAO;EAErC,IAAI,QACF,OAAO,OAAO,SAAS,KAAK,KAAK,OAAO;GACtC,UAAU,KAAK;GACf,WAAW,KAAK;GAChB,KAAK,KAAK,QAAQ;EACpB,CAAC;EAOH,QAAO,MAJgB,QAAQ,OAAO,KAAK,KAAK,KAAK,UAAU,KAAK,GAAG,EACrE,KAAK,KAAK,QAAQ,IACpB,CAAC,EAEc,CAAC,MAAM,QAAQ,CAAC,GAAG;CACpC;;;;;CAMA,MAAa,aAAa,MAAyC;EACjE,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM,UAAU,KAAK,QAAQ,QAAQ;EACrC,MAAM,SAAS,MAAM,SAAS,OAAO;EAErC,IAAI,QACF,OAAO,OAAO,YAAY,KAAK,KAAK,KAAK;EAK3C,QAAO,MAFY,QAAQ,OAAO,KAAK,KAAK,KAAK,UAAU,KAAK,CAAC,EAEtD,CAAC,MAAM,OAAO;CAC3B;AACF"}
@@ -0,0 +1,36 @@
1
+ import { CuckooOptions } from "./types.mjs";
2
+ import { StructureContext } from "./bloom-filter.mjs";
3
+ //#region ../../packages/cache/src/structures/cuckoo-filter.d.ts
4
+ /**
5
+ * Membership filter that supports removal.
6
+ *
7
+ * With RedisBloom this is a real cuckoo filter (`CF.*`). Everywhere else it is
8
+ * a counting Bloom filter: the same API and error rate, with one counter per
9
+ * cell instead of one bit, so `remove()` can undo an `add()`.
10
+ *
11
+ * Never remove an item that was not added: on either implementation it
12
+ * corrupts the filter and can hide other items.
13
+ */
14
+ export declare class CuckooFilter {
15
+ protected readonly key: string;
16
+ protected readonly context: StructureContext;
17
+ protected readonly cells: number;
18
+ protected readonly hashes: number;
19
+ protected readonly capacity: number;
20
+ constructor(key: string, options: CuckooOptions, context: StructureContext);
21
+ protected positions(item: string): number[];
22
+ /**
23
+ * Add an item. Resolves to `true` when stored.
24
+ */
25
+ add(item: string | number): Promise<boolean>;
26
+ /**
27
+ * Remove an item that was added. Resolves to `true` when something was removed.
28
+ */
29
+ remove(item: string | number): Promise<boolean>;
30
+ /**
31
+ * `false` means definitely not present; `true` means probably present.
32
+ */
33
+ mightContain(item: string | number): Promise<boolean>;
34
+ }
35
+ //#endregion
36
+ //# sourceMappingURL=cuckoo-filter.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cuckoo-filter.d.mts","names":[],"sources":["../../../../../../../../packages/cache/src/structures/cuckoo-filter.ts"],"mappings":";;;;;;;;;;;;;qBAea;qBAMU;qBAEA,SAAS;qBAPX;qBACA;qBACA;EAEnB,YACqB,aACnB,SAAS,eACU,SAAS;YASpB,UAAU;;;;EASP,IAAI,wBAAwB;;;;EAoB5B,OAAO,wBAAwB;;;;EAwB/B,aAAa,wBAAwB"}
@@ -0,0 +1,70 @@
1
+ import { hashPair, probe } from "./hash.mjs";
2
+ import { bloomGeometry } from "./sizing.mjs";
3
+ import { nativeOf } from "./bloom-filter.mjs";
4
+
5
+ //#region ../../packages/cache/src/structures/cuckoo-filter.ts
6
+ /**
7
+ * Membership filter that supports removal.
8
+ *
9
+ * With RedisBloom this is a real cuckoo filter (`CF.*`). Everywhere else it is
10
+ * a counting Bloom filter: the same API and error rate, with one counter per
11
+ * cell instead of one bit, so `remove()` can undo an `add()`.
12
+ *
13
+ * Never remove an item that was not added: on either implementation it
14
+ * corrupts the filter and can hide other items.
15
+ */
16
+ var CuckooFilter = class {
17
+ constructor(key, options, context) {
18
+ this.key = key;
19
+ this.context = context;
20
+ const geometry = bloomGeometry(options.expectedItems, options.errorRate ?? .01);
21
+ this.cells = geometry.bits;
22
+ this.hashes = geometry.hashes;
23
+ this.capacity = options.expectedItems;
24
+ }
25
+ positions(item) {
26
+ const hashes = hashPair(item);
27
+ return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.cells));
28
+ }
29
+ /**
30
+ * Add an item. Resolves to `true` when stored.
31
+ */
32
+ async add(item) {
33
+ const value = String(item);
34
+ const backend = this.context.backend();
35
+ const native = await nativeOf(backend);
36
+ if (native) return native.cuckooAdd(this.key, value, {
37
+ capacity: this.capacity,
38
+ ttl: this.context.ttl
39
+ });
40
+ await backend.gridAdd(this.key, this.positions(value), 1, { ttl: this.context.ttl });
41
+ return true;
42
+ }
43
+ /**
44
+ * Remove an item that was added. Resolves to `true` when something was removed.
45
+ */
46
+ async remove(item) {
47
+ const value = String(item);
48
+ const backend = this.context.backend();
49
+ const native = await nativeOf(backend);
50
+ if (native) return native.cuckooRemove(this.key, value);
51
+ const positions = this.positions(value);
52
+ if ((await backend.gridGet(this.key, positions)).some((count) => count === 0)) return false;
53
+ await backend.gridAdd(this.key, positions, -1);
54
+ return true;
55
+ }
56
+ /**
57
+ * `false` means definitely not present; `true` means probably present.
58
+ */
59
+ async mightContain(item) {
60
+ const value = String(item);
61
+ const backend = this.context.backend();
62
+ const native = await nativeOf(backend);
63
+ if (native) return native.cuckooExists(this.key, value);
64
+ return (await backend.gridGet(this.key, this.positions(value))).every((count) => count > 0);
65
+ }
66
+ };
67
+
68
+ //#endregion
69
+ export { CuckooFilter };
70
+ //# sourceMappingURL=cuckoo-filter.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cuckoo-filter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/cuckoo-filter.ts"],"sourcesContent":["import { nativeOf, type StructureContext } from \"./bloom-filter\";\nimport { hashPair, probe } from \"./hash\";\nimport { bloomGeometry } from \"./sizing\";\nimport type { CuckooOptions } from \"./types\";\n\n/**\n * Membership filter that supports removal.\n *\n * With RedisBloom this is a real cuckoo filter (`CF.*`). Everywhere else it is\n * a counting Bloom filter: the same API and error rate, with one counter per\n * cell instead of one bit, so `remove()` can undo an `add()`.\n *\n * Never remove an item that was not added: on either implementation it\n * corrupts the filter and can hide other items.\n */\nexport class CuckooFilter {\n protected readonly cells: number;\n protected readonly hashes: number;\n protected readonly capacity: number;\n\n public constructor(\n protected readonly key: string,\n options: CuckooOptions,\n protected readonly context: StructureContext,\n ) {\n const geometry = bloomGeometry(options.expectedItems, options.errorRate ?? 0.01);\n\n this.cells = geometry.bits;\n this.hashes = geometry.hashes;\n this.capacity = options.expectedItems;\n }\n\n protected positions(item: string): number[] {\n const hashes = hashPair(item);\n\n return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.cells));\n }\n\n /**\n * Add an item. Resolves to `true` when stored.\n */\n public async add(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.cuckooAdd(this.key, value, {\n capacity: this.capacity,\n ttl: this.context.ttl,\n });\n }\n\n await backend.gridAdd(this.key, this.positions(value), 1, { ttl: this.context.ttl });\n\n return true;\n }\n\n /**\n * Remove an item that was added. Resolves to `true` when something was removed.\n */\n public async remove(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.cuckooRemove(this.key, value);\n }\n\n const positions = this.positions(value);\n const counts = await backend.gridGet(this.key, positions);\n\n if (counts.some((count) => count === 0)) {\n return false;\n }\n\n await backend.gridAdd(this.key, positions, -1);\n\n return true;\n }\n\n /**\n * `false` means definitely not present; `true` means probably present.\n */\n public async mightContain(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.cuckooExists(this.key, value);\n }\n\n const counts = await backend.gridGet(this.key, this.positions(value));\n\n return counts.every((count) => count > 0);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,IAAa,eAAb,MAA0B;CAKxB,AAAO,YACL,AAAmB,KACnB,SACA,AAAmB,SACnB;EAHmB;EAEA;EAEnB,MAAM,WAAW,cAAc,QAAQ,eAAe,QAAQ,aAAa,GAAI;EAE/E,KAAK,QAAQ,SAAS;EACtB,KAAK,SAAS,SAAS;EACvB,K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O,UAAU,QAAQ,CAAC;CAC1C;AACF"}
@@ -0,0 +1,33 @@
1
+ import { FrequencyEntry, FrequencyOptions } from "./types.mjs";
2
+ import { StructureContext } from "./bloom-filter.mjs";
3
+ //#region ../../packages/cache/src/structures/frequency-tracker.d.ts
4
+ /**
5
+ * Count-Min sketch with a Top-K list: how often a value was seen, and which
6
+ * values are seen most. Estimates never fall below the true count; they can
7
+ * only be too high.
8
+ */
9
+ export declare class FrequencyTracker {
10
+ protected readonly key: string;
11
+ protected readonly context: StructureContext;
12
+ protected readonly width: number;
13
+ protected readonly depth: number;
14
+ protected readonly topK: number;
15
+ constructor(key: string, options: FrequencyOptions, context: StructureContext);
16
+ protected cellsOf(item: string): number[];
17
+ /**
18
+ * Count `count` more occurrences of a value (default one).
19
+ */
20
+ add(value: string | number, count?: number): Promise<void>;
21
+ /**
22
+ * Estimated number of times a value was counted. Never lower than the true
23
+ * count; may be higher.
24
+ */
25
+ estimate(value: string | number): Promise<number>;
26
+ /**
27
+ * The most frequent values seen, highest count first. Holds at most `topK`
28
+ * values; `count` defaults to all of them.
29
+ */
30
+ top(count?: number): Promise<FrequencyEntry[]>;
31
+ }
32
+ //#endregion
33
+ //# sourceMappingURL=frequency-tracker.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frequency-tracker.d.mts","names":[],"sources":["../../../../../../../../packages/cache/src/structures/frequency-tracker.ts"],"mappings":";;;;;;;;qBAUa;qBAMU;qBAEA,SAAS;qBAPX;qBACA;qBACA;EAEnB,YACqB,aACnB,SAAS,kBACU,SAAS;YAWpB,QAAQ;;;;EAYL,IAAI,wBAAwB,iBAAY;;;;;EA+BxC,SAAS,yBAAyB;;;;;EAkBlC,IAAI,iBAAoB,QAAQ"}