@warlock.js/cache 5.53.0 → 5.54.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 (81) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/cjs/index.cjs +158 -7
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/cache-manager.d.mts +12 -0
  5. package/esm/cache-manager.d.mts.map +1 -1
  6. package/esm/cache-manager.mjs +18 -0
  7. package/esm/cache-manager.mjs.map +1 -1
  8. package/esm/cached/auto-key.mjs.map +1 -1
  9. package/esm/cached/cached.mjs.map +1 -1
  10. package/esm/cached/normalize-args.mjs.map +1 -1
  11. package/esm/drivers/base-cache-driver.d.mts +11 -0
  12. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  13. package/esm/drivers/base-cache-driver.mjs +43 -6
  14. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  15. package/esm/drivers/clone-value.mjs.map +1 -1
  16. package/esm/drivers/file-cache-driver.d.mts +7 -0
  17. package/esm/drivers/file-cache-driver.d.mts.map +1 -1
  18. package/esm/drivers/file-cache-driver.mjs +14 -0
  19. package/esm/drivers/file-cache-driver.mjs.map +1 -1
  20. package/esm/drivers/in-memory-tag-index.mjs.map +1 -1
  21. package/esm/drivers/lru-memory-cache-driver.d.mts +4 -0
  22. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  23. package/esm/drivers/lru-memory-cache-driver.mjs +13 -0
  24. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  25. package/esm/drivers/memory-cache-driver.d.mts +4 -0
  26. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  27. package/esm/drivers/memory-cache-driver.mjs +13 -0
  28. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  29. package/esm/drivers/memory-extended-cache-driver.mjs.map +1 -1
  30. package/esm/drivers/mock-cache-driver.d.mts +4 -0
  31. package/esm/drivers/mock-cache-driver.d.mts.map +1 -1
  32. package/esm/drivers/mock-cache-driver.mjs +9 -0
  33. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  34. package/esm/drivers/null-cache-driver.d.mts +4 -0
  35. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  36. package/esm/drivers/null-cache-driver.mjs +6 -0
  37. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  38. package/esm/drivers/pg-cache-driver.d.mts +4 -0
  39. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  40. package/esm/drivers/pg-cache-driver.mjs +8 -0
  41. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  42. package/esm/drivers/redis-cache-driver.d.mts +7 -0
  43. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  44. package/esm/drivers/redis-cache-driver.mjs +18 -0
  45. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  46. package/esm/idempotent.mjs.map +1 -1
  47. package/esm/index.d.mts +2 -2
  48. package/esm/index.mjs +2 -2
  49. package/esm/list/memory-cache-list.mjs.map +1 -1
  50. package/esm/metrics.mjs.map +1 -1
  51. package/esm/scoped-cache.d.mts.map +1 -1
  52. package/esm/scoped-cache.mjs +5 -2
  53. package/esm/scoped-cache.mjs.map +1 -1
  54. package/esm/structures/bloom-filter.mjs.map +1 -1
  55. package/esm/structures/cuckoo-filter.mjs.map +1 -1
  56. package/esm/structures/frequency-tracker.mjs.map +1 -1
  57. package/esm/structures/hash.mjs.map +1 -1
  58. package/esm/structures/hyperloglog.mjs.map +1 -1
  59. package/esm/structures/memory-structures-backend.mjs.map +1 -1
  60. package/esm/structures/redis-structures-backend.mjs.map +1 -1
  61. package/esm/structures/sizing.mjs.map +1 -1
  62. package/esm/structures/structures.mjs.map +1 -1
  63. package/esm/structures/types.mjs.map +1 -1
  64. package/esm/structures/unique-counter.mjs.map +1 -1
  65. package/esm/tag-sample.mjs.map +1 -1
  66. package/esm/tagged-cache.mjs.map +1 -1
  67. package/esm/tagged-scoped-cache.mjs.map +1 -1
  68. package/esm/types.d.mts +53 -0
  69. package/esm/types.d.mts.map +1 -1
  70. package/esm/types.mjs.map +1 -1
  71. package/esm/utils.d.mts +6 -0
  72. package/esm/utils.d.mts.map +1 -1
  73. package/esm/utils.mjs +13 -1
  74. package/esm/utils.mjs.map +1 -1
  75. package/llms-full.txt +6 -0
  76. package/package.json +4 -4
  77. package/skills/cache-basics/SKILL.md +1 -0
  78. package/skills/configure-set-options/SKILL.md +2 -0
  79. package/skills/use-cache-namespace/SKILL.md +1 -0
  80. package/skills/use-cache-similarity/SKILL.md +1 -0
  81. package/skills/use-swr/SKILL.md +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"hash.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/hash.ts"],"mappings":";AAAA,MAAM,UAAU,IAAI,YAAY;;;;;;;;AAShC,SAAgB,QAAQ,OAAe,MAAsB;CAC3D,MAAM,QAAQ,QAAQ,OAAO,KAAK;CAClC,MAAM,SAAS,MAAM;CACrB,MAAM,SAAS,UAAU;CACzB,IAAI,OAAO,SAAS;CAEpB,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,SAAS;EAC3C,MAAM,SAAS,SAAS;EACxB,IAAI,QACF,MAAM,UACL,MAAM,SAAS,MAAO,IACtB,MAAM,SAAS,MAAO,KACtB,MAAM,SAAS,MAAO;EAEzB,QAAQ,KAAK,KAAK,OAAO,UAAU;EACnC,QAAS,SAAS,KAAO,UAAU;EACnC,QAAQ,KAAK,KAAK,OAAO,SAAU;EAEnC,QAAQ;EACR,OAAQ,QAAQ,KAAO,SAAS;EAChC,OAAQ,KAAK,KAAK,MAAM,CAAC,IAAI,aAAc;CAC7C;CAEA,IAAI,OAAO;CACX,MAAM,aAAa,UAAU;CAE7B,MAAM,YAAY,SAAS;CAE3B,IAAI,cAAc,GAChB,QAAQ,MAAM,aAAa,MAAO;CAGpC,IAAI,aAAa,GACf,QAAQ,MAAM,aAAa,MAAO;CAGpC,IAAI,aAAa,GAAG;EAClB,QAAQ,MAAM;EACd,OAAO,KAAK,KAAK,MAAM,UAAU;EACjC,OAAQ,QAAQ,KAAO,SAAS;EAChC,OAAO,KAAK,KAAK,MAAM,SAAU;EACjC,QAAQ;CACV;CAEA,QAAQ;CACR,QAAQ,SAAS;CACjB,OAAO,KAAK,KAAK,MAAM,UAAU;CACjC,QAAQ,SAAS;CACjB,OAAO,KAAK,KAAK,MAAM,UAAU;CACjC,QAAQ,SAAS;CAEjB,OAAO,SAAS;AAClB;;;;;AAMA,SAAgB,SAAS,MAAgC;CACvD,OAAO,CAAC,QAAQ,MAAM,UAAU,IAAI,QAAQ,MAAM,UAAU,IAAI,OAAO,CAAC;AAC1E;;;;;AAMA,SAAgB,MAAM,QAA0B,OAAe,MAAsB;CACnF,MAAM,CAAC,OAAO,UAAU;CAExB,QAAS,QAAQ,QAAQ,SAAS,QAAQ,SAAS,SAAU;AAC/D;;;;AAKA,SAAgB,OAAO,MAAgC;CACrD,OAAO,CAAC,QAAQ,MAAM,SAAU,GAAG,QAAQ,MAAM,UAAU,CAAC;AAC9D"}
1
+ {"version":3,"file":"hash.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/hash.ts"],"sourcesContent":["const encoder = new TextEncoder();\n\n/**\n * MurmurHash3 (x86, 32-bit) over the UTF-8 bytes of `input`.\n *\n * Pure and deterministic: the same input and seed give the same hash on every\n * process, platform and release, which matters because the hashes decide where\n * an item lives in a structure stored in a shared cache.\n */\nexport function murmur3(input: string, seed: number): number {\n const bytes = encoder.encode(input);\n const length = bytes.length;\n const blocks = length >> 2;\n let hash = seed >>> 0;\n\n for (let index = 0; index < blocks; index++) {\n const offset = index << 2;\n let block =\n bytes[offset]! |\n (bytes[offset + 1]! << 8) |\n (bytes[offset + 2]! << 16) |\n (bytes[offset + 3]! << 24);\n\n block = Math.imul(block, 0xcc9e2d51);\n block = (block << 15) | (block >>> 17);\n block = Math.imul(block, 0x1b873593);\n\n hash ^= block;\n hash = (hash << 13) | (hash >>> 19);\n hash = (Math.imul(hash, 5) + 0xe6546b64) | 0;\n }\n\n let tail = 0;\n const tailOffset = blocks << 2;\n\n const remainder = length & 3;\n\n if (remainder === 3) {\n tail ^= bytes[tailOffset + 2]! << 16;\n }\n\n if (remainder >= 2) {\n tail ^= bytes[tailOffset + 1]! << 8;\n }\n\n if (remainder >= 1) {\n tail ^= bytes[tailOffset]!;\n tail = Math.imul(tail, 0xcc9e2d51);\n tail = (tail << 15) | (tail >>> 17);\n tail = Math.imul(tail, 0x1b873593);\n hash ^= tail;\n }\n\n hash ^= length;\n hash ^= hash >>> 16;\n hash = Math.imul(hash, 0x85ebca6b);\n hash ^= hash >>> 13;\n hash = Math.imul(hash, 0xc2b2ae35);\n hash ^= hash >>> 16;\n\n return hash >>> 0;\n}\n\n/**\n * Two independent 32-bit hashes of `item`, for double hashing. The second one\n * is forced odd so the probe sequence never collapses onto a few slots.\n */\nexport function hashPair(item: string): [number, number] {\n return [murmur3(item, 0x9747b28c), (murmur3(item, 0x5bd1e995) | 1) >>> 0];\n}\n\n/**\n * The `index`-th probe position of `item` inside `size` slots (enhanced double\n * hashing, so successive positions are well spread even for small `size`).\n */\nexport function probe(hashes: [number, number], index: number, size: number): number {\n const [first, second] = hashes;\n\n return ((first + index * second + index * index) % size) >>> 0;\n}\n\n/**\n * A 64-bit hash of `item` as two unsigned 32-bit halves.\n */\nexport function hash64(item: string): [number, number] {\n return [murmur3(item, 0x1b873593), murmur3(item, 0x85ebca6b)];\n}\n"],"mappings":";AAAA,MAAM,UAAU,IAAI,YAAY;;;;;;;;AAShC,SAAgB,QAAQ,OAAe,MAAsB;CAC3D,MAAM,QAAQ,QAAQ,OAAO,KAAK;CAClC,MAAM,SAAS,MAAM;CACrB,MAAM,SAAS,UAAU;CACzB,IAAI,OAAO,SAAS;CAEpB,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,SAAS;EAC3C,MAAM,SAAS,SAAS;EACxB,IAAI,QACF,MAAM,UACL,MAAM,SAAS,MAAO,IACtB,MAAM,SAAS,MAAO,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AACpB,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB,KAAK,uBAAuB;AACzD,MAAM,WAAW;;;;;;;AAQjB,IAAa,cAAb,MAAyB;CAGvB,AAAO,YAAY,WAAwB;EACzC,KAAK,YAAY,aAAa,IAAI,gBAAwB;CAC5D;;;;;CAMA,AAAO,IAAI,MAAuB;EAChC,MAAM,CAAC,MAAM,OAAO,OAAO,IAAI;EAC/B,MAAM,QAAQ,SAAS;EACvB,MAAM,YAAY,OAAO;EACzB,IAAI;EAEJ,IAAI,cAAc,GAChB,OAAO,KAAK,MAAM,SAAS,IAAK,KAA4B;OACvD,IAAI,QAAQ,GACjB,OAAO,sBAAsB,KAAK,MAAM,GAAG,IAAI;OAE/C,OAAO;EAGT,IAAI,OAAO,KAAK,UAAU,QAAS;GACjC,KAAK,UAAU,SAAS;GAExB,OAAO;EACT;EAEA,OAAO;CACT;;;;;CAMA,AAAO,MAAM,OAA0B;EACrC,KAAK,IAAI,QAAQ,GAAG,QAAQ,eAAe,SAAS;GAClD,MAAM,QAAQ,MAAM,UAAU;GAE9B,IAAI,QAAQ,KAAK,UAAU,QACzB,KAAK,UAAU,SAAS;EAE5B;EAEA,OAAO;CACT;;;;CAKA,AAAO,QAAgB;EACrB,IAAI,MAAM;EACV,IAAI,QAAQ;EAEZ,KAAK,IAAI,QAAQ,GAAG,QAAQ,eAAe,SAAS;GAClD,MAAM,QAAQ,KAAK,UAAU;GAE7B,OAAO,KAAK,CAAC;GAEb,IAAI,UAAU,GACZ;EAEJ;EAGA,MAAM,WADQ,QAAU,qBACE,gBAAgB,gBAAiB;EAG3D,IAAI,YAAY,eAAuB,QAAQ,GAC7C,OAAO,KAAK,MAAM,gBAAgB,KAAK,IAAI,gBAAgB,KAAK,CAAC;EAGnE,OAAO,KAAK,MAAM,QAAQ;CAC5B;AACF"}
1
+ {"version":3,"file":"hyperloglog.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/hyperloglog.ts"],"sourcesContent":["import { hash64 } from \"./hash\";\n\n/** Register index width: 2^14 = 16384 registers, about 12 KB, standard error 0.81%. */\nexport const HLL_PRECISION = 14;\nexport const HLL_REGISTERS = 1 << HLL_PRECISION;\n\nconst INDEX_SHIFT = 32 - HLL_PRECISION;\nconst HIGH_REMAINDER_BITS = INDEX_SHIFT;\nconst HIGH_REMAINDER_MASK = (1 << HIGH_REMAINDER_BITS) - 1;\nconst MAX_RANK = HIGH_REMAINDER_BITS + 32 + 1;\n\n/**\n * HyperLogLog cardinality estimator over a 64-bit hash.\n *\n * Used by the in-process structures backend; Redis uses its native\n * `PFADD` / `PFCOUNT` instead.\n */\nexport class HyperLogLog {\n public readonly registers: Uint8Array;\n\n public constructor(registers?: Uint8Array) {\n this.registers = registers ?? new Uint8Array(HLL_REGISTERS);\n }\n\n /**\n * Record `item`. Returns true when the estimate may have changed (a register\n * grew), which is also how `PFADD` reports a probably-new item.\n */\n public add(item: string): boolean {\n const [high, low] = hash64(item);\n const index = high >>> INDEX_SHIFT;\n const remainder = high & HIGH_REMAINDER_MASK;\n let rank: number;\n\n if (remainder !== 0) {\n rank = Math.clz32(remainder) - (32 - HIGH_REMAINDER_BITS) + 1;\n } else if (low !== 0) {\n rank = HIGH_REMAINDER_BITS + Math.clz32(low) + 1;\n } else {\n rank = MAX_RANK;\n }\n\n if (rank > this.registers[index]!) {\n this.registers[index] = rank;\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Fold `other` into this counter (register-wise maximum), so the result\n * counts the union of both sets.\n */\n public merge(other: HyperLogLog): this {\n for (let index = 0; index < HLL_REGISTERS; index++) {\n const value = other.registers[index]!;\n\n if (value > this.registers[index]!) {\n this.registers[index] = value;\n }\n }\n\n return this;\n }\n\n /**\n * Estimated number of distinct items.\n */\n public count(): number {\n let sum = 0;\n let zeros = 0;\n\n for (let index = 0; index < HLL_REGISTERS; index++) {\n const value = this.registers[index]!;\n\n sum += 2 ** -value;\n\n if (value === 0) {\n zeros++;\n }\n }\n\n const alpha = 0.7213 / (1 + 1.079 / HLL_REGISTERS);\n const estimate = (alpha * HLL_REGISTERS * HLL_REGISTERS) / sum;\n\n // Small range: linear counting is more accurate while many registers are empty.\n if (estimate <= 2.5 * HLL_REGISTERS && zeros > 0) {\n return Math.round(HLL_REGISTERS * Math.log(HLL_REGISTERS / zeros));\n }\n\n return Math.round(estimate);\n }\n}\n"],"mappings":";;;AAIA,MAAa,gBAAgB;AAE7B,MAAM,cAAc;AACpB,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB,KAAK,uBAAuB;AACzD,MAAM,WAAW;;;;;;;AAQjB,IAAa,cAAb,MAAyB;CAGvB,AAAO,YAAY,WAAwB;EACzC,KAAK,YAAY,aAAa,IAAI,gBAAwB;CAC5D;;;;;CAMA,AAAO,IAAI,MAAuB;EAChC,MAAM,CAAC,MAAM,OAAO,OAAO,IAAI;EAC/B,MAAM,QAAQ,SAAS;EACvB,MAAM,YAAY,OAAO;EACzB,IAAI;EAEJ,IAAI,cAAc,GAChB,OAAO,KAAK,MAAM,SAAS,IAAK,KAA4B;OACvD,IAAI,QAAQ,GACjB,OAAO,sBAAsB,KAAK,MAAM,GAAG,IAAI;OAE/C,OAAO;EAGT,IAAI,OAAO,KAAK,UAAU,QAAS;GACjC,KAAK,UAAU,SAAS;GAExB,OAAO;EACT;EAEA,OAAO;CACT;;;;;CAMA,AAAO,MAAM,OAA0B;EACrC,KAAK,IAAI,QAAQ,GAAG,QAAQ,eAAe,SAAS;GAClD,MAAM,QAAQ,MAAM,UAAU;GAE9B,IAAI,QAAQ,KAAK,UAAU,QACzB,KAAK,UAAU,SAAS;EAE5B;EAEA,OAAO;CACT;;;;CAKA,AAAO,QAAgB;EACrB,IAAI,MAAM;EACV,IAAI,QAAQ;EAEZ,KAAK,IAAI,QAAQ,GAAG,QAAQ,eAAe,SAAS;GAClD,MAAM,QAAQ,KAAK,UAAU;GAE7B,OAAO,KAAK,CAAC;GAEb,IAAI,UAAU,GACZ;EAEJ;EAGA,MAAM,WADQ,QAAU,qBACE,gBAAgB,gBAAiB;EAG3D,IAAI,YAAY,eAAuB,QAAQ,GAC7C,OAAO,KAAK,MAAM,gBAAgB,KAAK,IAAI,gBAAgB,KAAK,CAAC;EAGnE,OAAO,KAAK,MAAM,QAAQ;CAC5B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"memory-structures-backend.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/memory-structures-backend.ts"],"mappings":";;;;;;;;AAcA,IAAa,0BAAb,MAAuE;;;;CAMrE,AAAO,YAAY,AAAmB,UAAmC;EAAnC;+BALpB,IAAI,IAAkB;CAKkC;;CAG1E,AAAO,QAAQ;EACb,KAAK,MAAM,MAAM;CACnB;;CAGA,AAAO,YAAY,QAAgB;EACjC,KAAK,MAAM,OAAO,CAAC,GAAG,KAAK,MAAM,KAAK,CAAC,GACrC,IAAI,IAAI,WAAW,MAAM,GACvB,KAAK,MAAM,OAAO,GAAG;CAG3B;CAEA,MAAa,OAAO,KAAa,SAAmB,SAA0B;EAC5E,MAAM,OAAO,KAAK,KAAK,KAAK,8BAAc,IAAI,WAAW,CAAC,GAAG,OAAO;EAEpE,MAAM,UADY,QAAQ,QAAQ,KAAK,WAAW,KAAK,IAAI,KAAK,MAAM,GAAG,CACjD,KAAK,KAAK;EAElC,IAAI,KAAK,MAAM,SAAS,QAAQ;GAC9B,MAAM,QAAQ,IAAI,WAAW,KAAK,IAAI,QAAQ,KAAK,MAAM,SAAS,CAAC,CAAC;GAEpE,MAAM,IAAI,KAAK,KAAK;GACpB,KAAK,QAAQ;EACf;EAEA,OAAO,QAAQ,KAAK,WAAW;GAC7B,MAAM,OAAO,MAAM,SAAS;GAC5B,MAAM,OAAO,KAAK,MAAM,UAAU,MAAM;GACxC,MAAM,YAAY,OAAO,UAAU;GAEnC,KAAK,MAAM,UAAU,KAAK,OAAO;GAEjC,OAAO;EACT,CAAC;CACH;CAEA,MAAa,OAAO,KAAa,SAAmB;EAClD,MAAM,OAAO,KAAK,KAAK,KAAK,M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WAAW,UAAa,iBAAiB,KAAK,MAAM,IAAI,MAAM,GAChE,SAAS;GAIb,KAAK,MAAM,OAAO,MAAO;EAC3B;CACF;CAEA,MAAa,UAAU,KAAa,OAAuC;EACzE,MAAM,OAAO,KAAK,KAAK,KAAK,QAAQ;EAEpC,IAAI,CAAC,MACH,OAAO,CAAC;EAGV,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CACnB,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ;EAAM,EAAE,CAAC,CAC7C,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,CAAC,CACnE,MAAM,GAAG,KAAK;CACnB;CAEA,AAAU,KACR,KACA,MACwC;EACxC,MAAM,SAAS,KAAK,SAAS,GAAG;EAChC,MAAM,OAAO,KAAK,MAAM,IAAI,MAAM;EAElC,IAAI,CAAC,MACH;EAGF,IAAI,KAAK,cAAc,UAAa,KAAK,aAAa,KAAK,IAAI,GAAG;GAChE,KAAK,MAAM,OAAO,MAAM;GAExB;EACF;EAEA,OAAO,KAAK,SAAS,OAAQ,OAAsC;CACrE;CAEA,AAAU,KACR,KACA,MACA,QACA,SAC4B;EAC5B,MAAM,WAAW,KAAK,KAAK,KAAK,IAAI;EAEpC,IAAI,UACF,OAAO;EAGT,MAAM,OAAO;GAAE;GAAM,OAAO,OAAO;EAAE;EAErC,IAAI,SAAS,OAAO,OAAO,SAAS,QAAQ,GAAG,GAC7C,KAAK,YAAY,KAAK,IAAI,IAAI,QAAQ,MAAM;EAG9C,KAAK,MAAM,IAAI,KAAK,SAAS,GAAG,GAAG,IAAI;EAEvC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"memory-structures-backend.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/memory-structures-backend.ts"],"sourcesContent":["import { HyperLogLog } from \"./hyperloglog\";\nimport type { CacheStructuresBackend, RankedEntry, StructureWrite } from \"./types\";\n\ntype Slot =\n | { type: \"bits\"; value: Uint8Array; expiresAt?: number }\n | { type: \"grid\"; value: Map<number, number>; expiresAt?: number }\n | { type: \"unique\"; value: HyperLogLog; expiresAt?: number }\n | { type: \"ranked\"; value: Map<string, number>; expiresAt?: number };\n\n/**\n * In-process implementation of the structure primitives, shared by the memory\n * family of drivers. State lives next to the driver's entries and follows its\n * `flush()` and `removeNamespace()`.\n */\nexport class MemoryStructuresBackend implements CacheStructuresBackend {\n protected slots = new Map<string, Slot>();\n\n /**\n * @param parseKey the owning driver's key parser (applies the cache prefix)\n */\n public constructor(protected readonly parseKey: (key: string) => string) {}\n\n /** Drop every structure. */\n public clear() {\n this.slots.clear();\n }\n\n /** Drop every structure whose parsed key starts with `prefix`. */\n public clearPrefix(prefix: string) {\n for (const key of [...this.slots.keys()]) {\n if (key.startsWith(prefix)) {\n this.slots.delete(key);\n }\n }\n }\n\n public async bitSet(key: string, offsets: number[], options?: StructureWrite) {\n const slot = this.slot(key, \"bits\", () => new Uint8Array(0), options);\n const maxOffset = offsets.reduce((max, offset) => Math.max(max, offset), 0);\n const needed = (maxOffset >> 3) + 1;\n\n if (slot.value.length < needed) {\n const grown = new Uint8Array(Math.max(needed, slot.value.length * 2));\n\n grown.set(slot.value);\n slot.value = grown;\n }\n\n return offsets.map((offset) => {\n const mask = 1 << (offset & 7);\n const byte = slot.value[offset >> 3] ?? 0;\n const previous = (byte & mask) !== 0;\n\n slot.value[offset >> 3] = byte | mask;\n\n return previous;\n });\n }\n\n public async bitGet(key: string, offsets: number[]) {\n const slot = this.find(key, \"bits\");\n\n return offsets.map((offset) => {\n const byte = slot?.value[offset >> 3];\n\n return byte !== undefined && (byte & (1 << (offset & 7))) !== 0;\n });\n }\n\n public async gridAdd(key: string, cells: number[], delta: number, options?: StructureWrite) {\n const slot = this.slot(key, \"grid\", () => new Map<number, number>(), options);\n\n return cells.map((cell) => {\n const next = Math.max(0, (slot.value.get(cell) ?? 0) + delta);\n\n if (next === 0) {\n slot.value.delete(cell);\n } else {\n slot.value.set(cell, next);\n }\n\n return next;\n });\n }\n\n public async gridGet(key: string, cells: number[]) {\n const slot = this.find(key, \"grid\");\n\n return cells.map((cell) => slot?.value.get(cell) ?? 0);\n }\n\n public async uniqueAdd(key: string, member: string, options?: StructureWrite) {\n return this.slot(key, \"unique\", () => new HyperLogLog(), options).value.add(member);\n }\n\n public async uniqueCount(keys: string[]) {\n const merged = new HyperLogLog();\n\n for (const key of keys) {\n const slot = this.find(key, \"unique\");\n\n if (slot) {\n merged.merge(slot.value);\n }\n }\n\n return merged.count();\n }\n\n public async rankedSet(\n key: string,\n member: string,\n score: number,\n capacity: number,\n options?: StructureWrite,\n ) {\n const slot = this.slot(key, \"ranked\", () => new Map<string, number>(), options);\n\n slot.value.set(member, score);\n\n if (slot.value.size > capacity) {\n let lowest: string | undefined;\n\n for (const [candidate, candidateScore] of slot.value) {\n if (lowest === undefined || candidateScore < slot.value.get(lowest)!) {\n lowest = candidate;\n }\n }\n\n slot.value.delete(lowest!);\n }\n }\n\n public async rankedTop(key: string, count: number): Promise<RankedEntry[]> {\n const slot = this.find(key, \"ranked\");\n\n if (!slot) {\n return [];\n }\n\n return [...slot.value]\n .map(([member, score]) => ({ member, score }))\n .sort((a, b) => b.score - a.score || (a.member < b.member ? -1 : 1))\n .slice(0, count);\n }\n\n protected find<T extends Slot[\"type\"]>(\n key: string,\n type: T,\n ): Extract<Slot, { type: T }> | undefined {\n const parsed = this.parseKey(key);\n const slot = this.slots.get(parsed);\n\n if (!slot) {\n return undefined;\n }\n\n if (slot.expiresAt !== undefined && slot.expiresAt <= Date.now()) {\n this.slots.delete(parsed);\n\n return undefined;\n }\n\n return slot.type === type ? (slot as Extract<Slot, { type: T }>) : undefined;\n }\n\n protected slot<T extends Slot[\"type\"]>(\n key: string,\n type: T,\n create: () => Extract<Slot, { type: T }>[\"value\"],\n options?: StructureWrite,\n ): Extract<Slot, { type: T }> {\n const existing = this.find(key, type);\n\n if (existing) {\n return existing;\n }\n\n const slot = { type, value: create() } as Slot;\n\n if (options?.ttl && Number.isFinite(options.ttl)) {\n slot.expiresAt = Date.now() + options.ttl * 1000;\n }\n\n this.slots.set(this.parseKey(key), slot);\n\n return slot as Extract<Slot, { type: T }>;\n }\n}\n"],"mappings":";;;;;;;;AAcA,IAAa,0BAAb,MAAuE;;;;CAMrE,AAAO,YAAY,AAAmB,UAAmC;EAAnC;+BALpB,IAAI,IAAkB;CAKkC;;CAG1E,AAAO,QAAQ;EACb,KAAK,MAAM,MAAM;CACnB;;CAGA,AAAO,YAAY,QAAgB;EACjC,KAAK,MAAM,OAAO,CAAC,GAAG,KAAK,MAAM,KAAK,CAAC,GACrC,IAAI,IAAI,WAAW,MAAM,GACvB,KAAK,MAAM,OAAO,GAAG;CAG3B;CAEA,MAAa,OAAO,KAAa,SAAmB,SAA0B;EAC5E,MAAM,OAAO,KAAK,KAAK,KAAK,8BAAc,IAAI,WAAW,CAAC,GAAG,OAAO;EAEpE,MAAM,UADY,QAAQ,QAAQ,KAAK,WAAW,KAAK,IAAI,KAAK,MAAM,GAAG,CACjD,KAAK,KAAK;EAElC,IAAI,KAAK,MAAM,SAAS,QAAQ;GAC9B,MAAM,QAAQ,IAAI,WAAW,KAAK,IAAI,QAAQ,KAAK,MAAM,SAAS,CAAC,CAAC;GAEpE,MAAM,IAAI,KAAK,KAAK;GACpB,KAAK,QAAQ;EACf;EAEA,OAAO,QAAQ,KAAK,WAAW;GAC7B,MAAM,OAAO,MAAM,SAAS;GAC5B,MAAM,OAAO,KAAK,MAAM,UAAU,MAAM;GACxC,MAAM,YAAY,OAAO,UAAU;GAEnC,KAAK,MAAM,UAAU,KAAK,OAAO;GAEjC,OAAO;EACT,CAAC;CACH;CAEA,MAAa,OAAO,KAAa,SAAmB;EAClD,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM;EAElC,OAAO,QAAQ,KAAK,WAAW;GAC7B,MAAM,OAAO,MAAM,MAAM,UAAU;GAEnC,OAAO,SAAS,WAAc,OAAQ,MAAM,SAAS,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AAa,OAAuC;EACzE,MAAM,OAAO,KAAK,KAAK,KAAK,QAAQ;EAEpC,IAAI,CAAC,MACH,OAAO,CAAC;EAGV,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CACnB,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ;EAAM,EAAE,CAAC,CAC7C,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,CAAC,CACnE,MAAM,GAAG,KAAK;CACnB;CAEA,AAAU,KACR,KACA,MACwC;EACxC,MAAM,SAAS,KAAK,SAAS,GAAG;EAChC,MAAM,OAAO,KAAK,MAAM,IAAI,MAAM;EAElC,IAAI,CAAC,MACH;EAGF,IAAI,KAAK,cAAc,UAAa,KAAK,aAAa,KAAK,IAAI,GAAG;GAChE,KAAK,MAAM,OAAO,MAAM;GAExB;EACF;EAEA,OAAO,KAAK,SAAS,OAAQ,OAAsC;CACrE;CAEA,AAAU,KACR,KACA,MACA,QACA,SAC4B;EAC5B,MAAM,WAAW,KAAK,KAAK,KAAK,IAAI;EAEpC,IAAI,UACF,OAAO;EAGT,MAAM,OAAO;GAAE;GAAM,OAAO,OAAO;EAAE;EAErC,IAAI,SAAS,OAAO,OAAO,SAAS,QAAQ,GAAG,GAC7C,KAAK,YAAY,KAAK,IAAI,IAAI,QAAQ,MAAM;EAG9C,KAAK,MAAM,IAAI,KAAK,SAAS,GAAG,GAAG,IAAI;EAEvC,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"redis-structures-backend.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/redis-structures-backend.ts"],"mappings":";;;;;;;;;AAoBA,IAAa,yBAAb,MAAsE;CAGpE,AAAO,YACL,AAAmB,WACnB,AAAmB,UACnB;EAFmB;EACA;CAClB;CAEH,AAAU,KAAK,MAAgD;EAC7D,OAAO,KAAK,UAAU,CAAC,CAAC,YAAY,KAAK,IAAI,MAAM,CAAC;CACtD;;;;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,OAAiB,OAAO,CAAC,GAC3E,OAAO,CAAC;KAGV,MAAM;IACR;GACF;EACF;CACF;AACF;AAEA,SAAS,MAAS,MAA0B;CAC1C,MAAM,SAAwB,CAAC;CAE/B,KAAK,IAAI,QAAQ,GAAG,QAAQ,IAAI,KAAK,QAAQ,SAAS,GACpD,OAAO,KAAK,CAAC,KAAK,QAAS,KAAK,QAAQ,EAAG,CAAC;CAG9C,OAAO;AACT;;AAGA,SAAgB,eAAe,OAAyB;CACtD,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,OAAO,MAAM,YAAY;EAE/B,OAAO,SAAS,QAAQ,SAAS;CACnC;CAEA,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,cAAc;CAGlC,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,KAAK,cAAc;CAGjD,OAAO;AACT"}
1
+ {"version":3,"file":"redis-structures-backend.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/redis-structures-backend.ts"],"sourcesContent":["import type {\n CacheStructuresBackend,\n NativeStructures,\n RankedEntry,\n StructureWrite,\n} from \"./types\";\n\n/** The one client method this backend needs; both redis v4 and v5 clients have it. */\ntype CommandClient = {\n sendCommand(args: string[]): Promise<unknown>;\n};\n\n/**\n * Redis implementation of the structure primitives.\n *\n * Portable path (any Redis): bitmaps (`SETBIT` / `GETBIT`), hashes\n * (`HINCRBY`), native HyperLogLog (`PFADD` / `PFCOUNT`) and sorted sets.\n * When the server runs RedisBloom, {@link native} exposes `BF.*`, `CF.*`,\n * `CMS.*` and `TOPK.*` operations, detected once with `MODULE LIST`.\n */\nexport class RedisStructuresBackend implements CacheStructuresBackend {\n protected nativeProbe?: Promise<NativeStructures | null>;\n\n public constructor(\n protected readonly getClient: () => CommandClient,\n protected readonly parseKey: (key: string) => string,\n ) {}\n\n protected send(args: Array<string | number>): Promise<unknown> {\n return this.getClient().sendCommand(args.map(String));\n }\n\n /**\n * Give a key without an expiry its ttl. A key that already expires keeps its\n * deadline, so later writes never push the window back.\n */\n protected async applyTtl(key: string, options?: StructureWrite) {\n if (!options?.ttl || !Number.isFinite(options.ttl)) {\n return;\n }\n\n if (Number(await this.send([\"TTL\", key])) === -1) {\n await this.send([\"EXPIRE\", key, Math.ceil(options.ttl)]);\n }\n }\n\n public async bitSet(key: string, offsets: number[], options?: StructureWrite) {\n const parsed = this.parseKey(key);\n const previous = await Promise.all(\n offsets.map((offset) => this.send([\"SETBIT\", parsed, offset, 1])),\n );\n\n await this.applyTtl(parsed, options);\n\n return previous.map((value) => Number(value) === 1);\n }\n\n public async bitGet(key: string, offsets: number[]) {\n const parsed = this.parseKey(key);\n const bits = await Promise.all(offsets.map((offset) => this.send([\"GETBIT\", parsed, offset])));\n\n return bits.map((value) => Number(value) === 1);\n }\n\n public async gridAdd(key: string, cells: number[], delta: number, options?: StructureWrite) {\n const parsed = this.parseKey(key);\n const values = await Promise.all(\n cells.map((cell) => this.send([\"HINCRBY\", parsed, cell, delta])),\n );\n\n await this.applyTtl(parsed, options);\n\n return values.map((value) => Math.max(0, Number(value)));\n }\n\n public async gridGet(key: string, cells: number[]) {\n if (cells.length === 0) {\n return [];\n }\n\n const values = (await this.send([\"HMGET\", this.parseKey(key), ...cells])) as Array<\n string | null\n >;\n\n return values.map((value) => Math.max(0, Number(value ?? 0)));\n }\n\n public async uniqueAdd(key: string, member: string, options?: StructureWrite) {\n const parsed = this.parseKey(key);\n const changed = await this.send([\"PFADD\", parsed, member]);\n\n await this.applyTtl(parsed, options);\n\n return Number(changed) === 1;\n }\n\n public async uniqueCount(keys: string[]) {\n if (keys.length === 0) {\n return 0;\n }\n\n return Number(await this.send([\"PFCOUNT\", ...keys.map((key) => this.parseKey(key))]));\n }\n\n public async rankedSet(\n key: string,\n member: string,\n score: number,\n capacity: number,\n options?: StructureWrite,\n ) {\n const parsed = this.parseKey(key);\n\n await this.send([\"ZADD\", parsed, score, member]);\n await this.send([\"ZREMRANGEBYRANK\", parsed, 0, -(capacity + 1)]);\n await this.applyTtl(parsed, options);\n }\n\n public async rankedTop(key: string, count: number): Promise<RankedEntry[]> {\n const flat = (await this.send([\n \"ZREVRANGE\",\n this.parseKey(key),\n 0,\n count - 1,\n \"WITHSCORES\",\n ])) as Array<string | number>;\n\n return pairs(flat).map(([member, score]) => ({ member: String(member), score: Number(score) }));\n }\n\n public native(): Promise<NativeStructures | null> {\n this.nativeProbe ??= this.detectModule().then((present) =>\n present ? this.createNative() : null,\n );\n\n return this.nativeProbe;\n }\n\n protected async detectModule(): Promise<boolean> {\n try {\n return containsModule(await this.send([\"MODULE\", \"LIST\"]));\n } catch {\n // MODULE LIST can be disabled by ACLs or on managed Redis: use the portable path.\n return false;\n }\n }\n\n /** Run `command`; when the key is missing, `init` creates it and `command` runs again. */\n protected async withInit<T>(command: () => Promise<T>, init: () => Promise<unknown>): Promise<T> {\n try {\n return await command();\n } catch (error) {\n if (!/not exist|no such key|not found/i.test(String((error as Error)?.message))) {\n throw error;\n }\n\n try {\n await init();\n } catch (initError) {\n if (!/exist/i.test(String((initError as Error)?.message))) {\n throw initError;\n }\n }\n\n return command();\n }\n }\n\n protected createNative(): NativeStructures {\n const first = (reply: unknown) => (Array.isArray(reply) ? reply[0] : reply);\n\n return {\n bloomAdd: async (key, item, { capacity, errorRate, ttl }) => {\n const parsed = this.parseKey(key);\n const reply = await this.send([\n \"BF.INSERT\",\n parsed,\n \"CAPACITY\",\n capacity,\n \"ERROR\",\n errorRate,\n \"ITEMS\",\n item,\n ]);\n\n await this.applyTtl(parsed, { ttl });\n\n return Number(first(reply)) === 1;\n },\n bloomExists: async (key, item) =>\n Number(await this.send([\"BF.EXISTS\", this.parseKey(key), item])) === 1,\n cuckooAdd: async (key, item, { capacity, ttl }) => {\n const parsed = this.parseKey(key);\n const reply = await this.send([\"CF.INSERT\", parsed, \"CAPACITY\", capacity, \"ITEMS\", item]);\n\n await this.applyTtl(parsed, { ttl });\n\n return Number(first(reply)) === 1;\n },\n cuckooRemove: async (key, item) =>\n Number(await this.send([\"CF.DEL\", this.parseKey(key), item])) === 1,\n cuckooExists: async (key, item) =>\n Number(await this.send([\"CF.EXISTS\", this.parseKey(key), item])) === 1,\n frequencyAdd: async (key, item, count, { width, depth, topK, ttl }) => {\n const cms = `${this.parseKey(key)}.cms`;\n const top = `${this.parseKey(key)}.topk`;\n\n await this.withInit(\n () => this.send([\"CMS.INCRBY\", cms, item, count]),\n () => this.send([\"CMS.INITBYDIM\", cms, width, depth]),\n );\n await this.withInit(\n () => this.send([\"TOPK.INCRBY\", top, item, count]),\n () => this.send([\"TOPK.RESERVE\", top, topK, width, depth, \"0.9\"]),\n );\n await this.applyTtl(cms, { ttl });\n await this.applyTtl(top, { ttl });\n },\n frequencyEstimate: async (key, item) => {\n try {\n return Number(first(await this.send([\"CMS.QUERY\", `${this.parseKey(key)}.cms`, item])));\n } catch (error) {\n if (/not exist|no such key|not found/i.test(String((error as Error)?.message))) {\n return 0;\n }\n\n throw error;\n }\n },\n frequencyTop: async (key, count) => {\n try {\n const flat = (await this.send([\n \"TOPK.LIST\",\n `${this.parseKey(key)}.topk`,\n \"WITHCOUNT\",\n ])) as Array<string | number>;\n\n return pairs(flat)\n .map(([member, score]) => ({ member: String(member), score: Number(score) }))\n .slice(0, count);\n } catch (error) {\n if (/not exist|no such key|not found/i.test(String((error as Error)?.message))) {\n return [];\n }\n\n throw error;\n }\n },\n };\n }\n}\n\nfunction pairs<T>(flat: T[]): Array<[T, T]> {\n const result: Array<[T, T]> = [];\n\n for (let index = 0; index + 1 < flat.length; index += 2) {\n result.push([flat[index]!, flat[index + 1]!]);\n }\n\n return result;\n}\n\n/** True when a `MODULE LIST` reply (any client shape) names the RedisBloom module. */\nexport function containsModule(reply: unknown): boolean {\n if (typeof reply === \"string\") {\n const name = reply.toLowerCase();\n\n return name === \"bf\" || name === \"redisbloom\";\n }\n\n if (Array.isArray(reply)) {\n return reply.some(containsModule);\n }\n\n if (reply && typeof reply === \"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,GAAG,CAEnD;CAAE;AACxB;AAEA,SAAgB,sBAAsB,MAAc,OAAe;CACjE,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,wBAAwB,WAAW,KAAK,IAAI,MAAM,+BAA+B;AAE/F"}
1
+ {"version":3,"file":"sizing.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/sizing.ts"],"sourcesContent":["import { CacheConfigurationError } from \"../types\";\n\n/**\n * Bloom filter geometry for `expectedItems` at `errorRate`: the number of bits\n * and the number of hash functions that minimise memory for that error rate.\n *\n * One million items at 1% need about 9.6 million bits (1.2 MB) and 7 hashes;\n * at 0.1% about 14.4 million bits (1.8 MB) and 10 hashes.\n */\nexport function bloomGeometry(\n expectedItems: number,\n errorRate: number,\n): { bits: number; hashes: number } {\n assertPositiveInteger(\"expectedItems\", expectedItems);\n\n if (!(errorRate > 0 && errorRate < 1)) {\n throw new CacheConfigurationError(\n `Invalid errorRate: ${errorRate}. Expected a number between 0 and 1 (exclusive), e.g. 0.01.`,\n );\n }\n\n const bits = Math.ceil((-expectedItems * Math.log(errorRate)) / Math.LN2 ** 2);\n const hashes = Math.max(1, Math.round((bits / expectedItems) * Math.LN2));\n\n return { bits, hashes };\n}\n\nexport function assertPositiveInteger(name: string, value: number) {\n if (!Number.isInteger(value) || value <= 0) {\n throw new CacheConfigurationError(`Invalid ${name}: ${value}. Expected a positive integer.`);\n }\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,cACd,eACA,WACkC;CAClC,sBAAsB,iBAAiB,aAAa;CAEpD,IAAI,EAAE,YAAY,KAAK,YAAY,IACjC,MAAM,IAAI,wBACR,sBAAsB,UAAU,4DAClC;CAGF,MAAM,OAAO,KAAK,KAAM,CAAC,gBAAgB,KAAK,IAAI,SAAS,IAAK,KAAK,OAAO,CAAC;CAG7E,OAAO;EAAE;EAAM,QAFA,KAAK,IAAI,GAAG,KAAK,MAAO,OAAO,gBAAiB,KAAK,GAAG,CAEnD;CAAE;AACxB;AAEA,SAAgB,sBAAsB,MAAc,OAAe;CACjE,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,wBAAwB,WAAW,KAAK,IAAI,MAAM,+BAA+B;AAE/F"}
@@ -1 +1 @@
1
- {"version":3,"file":"structures.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/structures.ts"],"mappings":";;;;;;;;;;;;;AAoCA,SAAgB,oBAAoB,QAAkD;CACpF,IAAI,CAAC,oBAAoB,MAAM,GAC7B,MAAM,IAAI,sBACR,IAAI,OAAO,KAAK,2HAClB;CAGF,OAAO,OAAO,kBAAkB;AAClC;AAEA,SAAS,WAAW,SAAgD;CAClE,IAAI,SAAS,QAAQ,QACnB;CAGF,MAAM,UAAU,SAAS,QAAQ,GAAG;CAEpC,OAAO,UAAU,KAAK,OAAO,SAAS,OAAO,IAAI,UAAU;AAC7D;;;;;AAMA,SAAgB,iBAAiB,YAA2D;CAC1F,MAAM,WAAW,aAAkD;EACjE,SAAS;EACT,KAAK,WAAW,OAAO;CACzB;CAEA,MAAM,kBAAkB,KAAa,YACnC,IAAI,cAAc,qBAAqB,OAAO,QAAQ,OAAO,CAAC;CAEhE,cAAc,SAAS,SACrB,IAAI,mBACF,KAAK,KAAK,QAAQ,qBAAqB,KAAK,GAC5C,QAAQ,CACV;CAEF,OAAO;EACL,QAAQ,KAAK,YAAY,IAAI,YAAY,oBAAoB,OAAO,SAAS,QAAQ,OAAO,CAAC;EAC7F,SAAS,KAAK,YACZ,IAAI,aAAa,qBAAqB,OAAO,SAAS,QAAQ,OAAO,CAAC;EACxE;EACA,YAAY,KAAK,UAAU,CAAC,MAC1B,IAAI,iBAAiB,wBAAwB,OAAO,SAAS,QAAQ,OAAO,CAAC;CACjF;AACF"}
1
+ {"version":3,"file":"structures.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/structures.ts"],"sourcesContent":["import { CacheUnsupportedError } from \"../types\";\nimport { parseTtl } from \"../utils\";\nimport { BloomFilter, type StructureContext } from \"./bloom-filter\";\nimport { CuckooFilter } from \"./cuckoo-filter\";\nimport { FrequencyTracker } from \"./frequency-tracker\";\nimport { UniqueCounter, UniqueCounterGroup } from \"./unique-counter\";\nimport {\n isStructuresCapable,\n type BloomOptions,\n type CacheStructuresBackend,\n type CuckooOptions,\n type FrequencyOptions,\n type StructureOptions,\n type UniqueCounterOptions,\n} from \"./types\";\n\nexport type UniqueCounterFactory = {\n (key: string, options?: UniqueCounterOptions): UniqueCounter;\n /** Count distinct values across several counters without changing them. */\n merge(keys: string[]): UniqueCounterGroup;\n};\n\n/**\n * The `cache.structures` namespace.\n */\nexport type CacheStructures = {\n bloom(key: string, options: BloomOptions): BloomFilter;\n cuckoo(key: string, options: CuckooOptions): CuckooFilter;\n uniqueCounter: UniqueCounterFactory;\n frequency(key: string, options?: FrequencyOptions): FrequencyTracker;\n};\n\n/**\n * Resolve the backend of a driver, or throw {@link CacheUnsupportedError} when\n * the driver does not opt in.\n */\nexport function structuresBackendOf(driver: { name: string }): CacheStructuresBackend {\n if (!isStructuresCapable(driver)) {\n throw new CacheUnsupportedError(\n `'${driver.name}' driver does not support cache.structures. Use the 'redis' driver or a memory driver ('memory', 'memoryExtended', 'lru').`,\n );\n }\n\n return driver.structuresBackend();\n}\n\nfunction ttlSeconds(options?: StructureOptions): number | undefined {\n if (options?.ttl === undefined) {\n return undefined;\n }\n\n const seconds = parseTtl(options.ttl);\n\n return seconds > 0 && Number.isFinite(seconds) ? seconds : undefined;\n}\n\n/**\n * Build the `cache.structures` namespace. `getBackend` is called on every\n * operation, so structures always follow the manager's current driver.\n */\nexport function createStructures(getBackend: () => CacheStructuresBackend): CacheStructures {\n const context = (options?: StructureOptions): StructureContext => ({\n backend: getBackend,\n ttl: ttlSeconds(options),\n });\n\n const uniqueCounter = ((key: string, options?: UniqueCounterOptions) =>\n new UniqueCounter(`structures.unique.${key}`, context(options))) as UniqueCounterFactory;\n\n uniqueCounter.merge = (keys: string[]) =>\n new UniqueCounterGroup(\n keys.map((key) => `structures.unique.${key}`),\n context(),\n );\n\n return {\n bloom: (key, options) => new BloomFilter(`structures.bloom.${key}`, options, context(options)),\n cuckoo: (key, options) =>\n new CuckooFilter(`structures.cuckoo.${key}`, options, context(options)),\n uniqueCounter,\n frequency: (key, options = {}) =>\n new FrequencyTracker(`structures.frequency.${key}`, options, context(options)),\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAgB,oBAAoB,QAAkD;CACpF,IAAI,CAAC,oBAAoB,MAAM,GAC7B,MAAM,IAAI,sBACR,IAAI,OAAO,KAAK,2HAClB;CAGF,OAAO,OAAO,kBAAkB;AAClC;AAEA,SAAS,WAAW,SAAgD;CAClE,IAAI,SAAS,QAAQ,QACnB;CAGF,MAAM,UAAU,SAAS,QAAQ,GAAG;CAEpC,OAAO,UAAU,KAAK,OAAO,SAAS,OAAO,IAAI,UAAU;AAC7D;;;;;AAMA,SAAgB,iBAAiB,YAA2D;CAC1F,MAAM,WAAW,aAAkD;EACjE,SAAS;EACT,KAAK,WAAW,OAAO;CACzB;CAEA,MAAM,kBAAkB,KAAa,YACnC,IAAI,cAAc,qBAAqB,OAAO,QAAQ,OAAO,CAAC;CAEhE,cAAc,SAAS,SACrB,IAAI,mBACF,KAAK,KAAK,QAAQ,qBAAqB,KAAK,GAC5C,QAAQ,CACV;CAEF,OAAO;EACL,QAAQ,KAAK,YAAY,IAAI,YAAY,oBAAoB,OAAO,SAAS,QAAQ,OAAO,CAAC;EAC7F,SAAS,KAAK,YACZ,IAAI,aAAa,qBAAqB,OAAO,SAAS,QAAQ,OAAO,CAAC;EACxE;EACA,YAAY,KAAK,UAAU,CAAC,MAC1B,IAAI,iBAAiB,wBAAwB,OAAO,SAAS,QAAQ,OAAO,CAAC;CACjF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/types.ts"],"mappings":";AAsHA,SAAgB,oBAAoB,QAA8C;CAChF,OACE,OAAO,WAAW,YAClB,WAAW,QACX,OAAQ,OAA6B,sBAAsB;AAE/D"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/types.ts"],"sourcesContent":["import type { CacheTtl } from \"../types\";\n\n/**\n * Options shared by every structure.\n */\nexport type StructureOptions = {\n /**\n * Expiry of the whole structure, set when it is first written and never\n * pushed back by later writes. A number is seconds; a string is a duration\n * such as `\"40d\"`. Omit to keep the structure until it is removed.\n */\n ttl?: CacheTtl;\n};\n\nexport type BloomOptions = StructureOptions & {\n /** How many distinct items you expect to add. Sizes the filter. */\n expectedItems: number;\n /** Target false-positive rate between 0 and 1. Default `0.01`. */\n errorRate?: number;\n};\n\nexport type CuckooOptions = StructureOptions & {\n /** How many distinct items you expect to hold at once. Sizes the filter. */\n expectedItems: number;\n /** Target false-positive rate between 0 and 1. Default `0.01`. */\n errorRate?: number;\n};\n\nexport type UniqueCounterOptions = StructureOptions;\n\nexport type FrequencyOptions = StructureOptions & {\n /** Counters per row. Wider means less over-counting. Default `2000`. */\n width?: number;\n /** Number of rows (independent hashes). Default `5`. */\n depth?: number;\n /** How many of the most frequent values to remember for `top()`. Default `10`. */\n topK?: number;\n};\n\nexport type FrequencyEntry = { value: string; count: number };\n\n/** Write options a structure hands to the backend (ttl in whole seconds). */\nexport type StructureWrite = { ttl?: number };\n\n/** A member with its score, as kept by the ranked primitive. */\nexport type RankedEntry = { member: string; score: number };\n\n/**\n * Native (module) operations. The Redis driver offers them when the server\n * runs RedisBloom, and the structures prefer them over the portable path.\n */\nexport interface NativeStructures {\n bloomAdd(\n key: string,\n item: string,\n options: { capacity: number; errorRate: number } & StructureWrite,\n ): Promise<boolean>;\n bloomExists(key: string, item: string): Promise<boolean>;\n cuckooAdd(\n key: string,\n item: string,\n options: { capacity: number } & StructureWrite,\n ): Promise<boolean>;\n cuckooRemove(key: string, item: string): Promise<boolean>;\n cuckooExists(key: string, item: string): Promise<boolean>;\n frequencyAdd(\n key: string,\n item: string,\n count: number,\n options: { width: number; depth: number; topK: number } & StructureWrite,\n ): Promise<void>;\n frequencyEstimate(key: string, item: string): Promise<number>;\n frequencyTop(key: string, count: number): Promise<RankedEntry[]>;\n}\n\n/**\n * The storage primitives behind `cache.structures`. A driver opts in by\n * implementing {@link StructuresCapable}; custom drivers that do not are\n * reported as unsupported.\n *\n * Keys are logical (the driver applies its own prefix). Every primitive that\n * writes takes a ttl in seconds that is applied only when the key is created.\n */\nexport interface CacheStructuresBackend {\n /** Set bits, returning each bit's previous value. */\n bitSet(key: string, offsets: number[], options?: StructureWrite): Promise<boolean[]>;\n bitGet(key: string, offsets: number[]): Promise<boolean[]>;\n /**\n * Add `delta` to every cell, returning the new values. Cells never go below\n * zero on backends that can clamp.\n */\n gridAdd(key: string, cells: number[], delta: number, options?: StructureWrite): Promise<number[]>;\n gridGet(key: string, cells: number[]): Promise<number[]>;\n /** Add to a distinct counter. Returns true when the estimate may have changed. */\n uniqueAdd(key: string, member: string, options?: StructureWrite): Promise<boolean>;\n /** Distinct count of the union of one or more counters. */\n uniqueCount(keys: string[]): Promise<number>;\n /** Set a member's score, keeping only the `capacity` highest-scored members. */\n rankedSet(\n key: string,\n member: string,\n score: number,\n capacity: number,\n options?: StructureWrite,\n ): Promise<void>;\n /** The highest-scored members, best first. */\n rankedTop(key: string, count: number): Promise<RankedEntry[]>;\n /** Native module operations, or `null` when unavailable. Resolved once per backend. */\n native?(): Promise<NativeStructures | null>;\n}\n\n/**\n * Optional capability a cache driver implements to support `cache.structures`.\n */\nexport interface StructuresCapable {\n structuresBackend(): CacheStructuresBackend;\n}\n\nexport function isStructuresCapable(driver: unknown): driver is StructuresCapable {\n return (\n typeof driver === \"object\" &&\n driver !== null &&\n typeof (driver as StructuresCapable).structuresBackend === \"function\"\n );\n}\n"],"mappings":";AAsHA,SAAgB,oBAAoB,QAA8C;CAChF,OACE,OAAO,WAAW,YAClB,WAAW,QACX,OAAQ,OAA6B,sBAAsB;AAE/D"}
@@ -1 +1 @@
1
- {"version":3,"file":"unique-counter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/unique-counter.ts"],"mappings":";;;;;AAMA,IAAa,gBAAb,MAA2B;CACzB,AAAO,YACL,AAAmB,KACnB,AAAmB,SACnB;EAFmB;EACA;CAClB;;;;CAKH,MAAa,IAAI,GAAG,QAA+C;EACjE,MAAM,UAAU,KAAK,QAAQ,QAAQ;EAErC,KAAK,MAAM,SAAS,QAClB,MAAM,QAAQ,UAAU,KAAK,KAAK,OAAO,KAAK,GAAG,EAAE,KAAK,KAAK,QAAQ,IAAI,CAAC;CAE9E;;;;CAKA,MAAa,QAAyB;EACpC,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,CAAC,KAAK,GAAG,CAAC;CACtD;AACF;;;;AAKA,IAAa,qBAAb,MAAgC;CAC9B,AAAO,YACL,AAAmB,MACnB,AAAmB,SACnB;EAFmB;EACA;CAClB;;;;CAKH,MAAa,QAAyB;EACpC,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,KAAK,IAAI;CACrD;AACF"}
1
+ {"version":3,"file":"unique-counter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/unique-counter.ts"],"sourcesContent":["import type { StructureContext } from \"./bloom-filter\";\n\n/**\n * Approximate count of distinct values (HyperLogLog): about 12 KB per counter,\n * standard error 0.81%. Cannot tell whether one specific value was counted.\n */\nexport class UniqueCounter {\n public constructor(\n protected readonly key: string,\n protected readonly context: StructureContext,\n ) {}\n\n /**\n * Count a value. Adding the same value again changes nothing.\n */\n public async add(...values: Array<string | number>): Promise<void> {\n const backend = this.context.backend();\n\n for (const value of values) {\n await backend.uniqueAdd(this.key, String(value), { ttl: this.context.ttl });\n }\n }\n\n /**\n * Approximate number of distinct values counted so far.\n */\n public async count(): Promise<number> {\n return this.context.backend().uniqueCount([this.key]);\n }\n}\n\n/**\n * The union of several unique counters, counted without changing any of them.\n */\nexport class UniqueCounterGroup {\n public constructor(\n protected readonly keys: string[],\n protected readonly context: StructureContext,\n ) {}\n\n /**\n * Approximate number of distinct values across every counter in the group.\n */\n public async count(): Promise<number> {\n return this.context.backend().uniqueCount(this.keys);\n }\n}\n"],"mappings":";;;;;AAMA,IAAa,gBAAb,MAA2B;CACzB,AAAO,YACL,AAAmB,KACnB,AAAmB,SACnB;EAFmB;EACA;CAClB;;;;CAKH,MAAa,IAAI,GAAG,QAA+C;EACjE,MAAM,UAAU,KAAK,QAAQ,QAAQ;EAErC,KAAK,MAAM,SAAS,QAClB,MAAM,QAAQ,UAAU,KAAK,KAAK,OAAO,KAAK,GAAG,EAAE,KAAK,KAAK,QAAQ,IAAI,CAAC;CAE9E;;;;CAKA,MAAa,QAAyB;EACpC,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,CAAC,KAAK,GAAG,CAAC;CACtD;AACF;;;;AAKA,IAAa,qBAAb,MAAgC;CAC9B,AAAO,YACL,AAAmB,MACnB,AAAmB,SACnB;EAFmB;EACA;CAClB;;;;CAKH,MAAa,QAAyB;EACpC,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,KAAK,IAAI;CACrD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"tag-sample.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tag-sample.ts"],"mappings":";;;;;;;AAMA,SAAgB,cAAc,SAA4B,OAAyB;CACjF,IAAI,QAAQ,UAAU,OACpB,OAAO,CAAC,GAAG,OAAO;CAGpB,MAAM,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAI,QAAQ,MAAM;CAEvD,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,IAAI,GAAG,UAAU,SAAS,QAAQ,SAAS,QAAQ,OAAQ;AAC/F"}
1
+ {"version":3,"file":"tag-sample.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tag-sample.ts"],"sourcesContent":["/**\n * Up to `count` members starting at a random offset (all of them when there\n * are fewer), so repeated samples cover a large index over time.\n *\n * @internal\n */\nexport function sampleMembers(members: readonly string[], count: number): string[] {\n if (members.length <= count) {\n return [...members];\n }\n\n const start = Math.floor(Math.random() * members.length);\n\n return Array.from({ length: count }, (_, index) => members[(start + index) % members.length]!);\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,cAAc,SAA4B,OAAyB;CACjF,IAAI,QAAQ,UAAU,OACpB,OAAO,CAAC,GAAG,OAAO;CAGpB,MAAM,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAI,QAAQ,MAAM;CAEvD,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,IAAI,GAAG,UAAU,SAAS,QAAQ,SAAS,QAAQ,OAAQ;AAC/F"}
@@ -1 +1 @@
1
- {"version":3,"file":"tagged-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tagged-cache.ts"],"mappings":";;;;;;;;AAaA,IAAa,cAAb,MAAa,YAAyC;;;;CAcpD,AAAO,YAAY,MAAgB,QAA+B;EAChE,KAAK,YAAY;EACjB,KAAK,SAAS;CAChB;;;;CAKA,AAAU,OAAO,KAAqB;EACpC,OAAO,cAAc;CACvB;;;;CAKA,MAAgB,eAAe,KAA8B;EAC3D,MAAM,KAAK,qBAAqB,GAAG;CACrC;;;;;;;;;;CAWA,MAAa,qBAAqB,KAA8B;EAC9D,MAAM,aAAa,KAAK,WAAW,GAAG;EAEtC,KAAK,MAAM,OAAO,KAAK,WAAW;GAChC,MAAM,SAAS,KAAK,OAAO,GAAG;GAE9B,MAAM,KAAK,SAAS,QAAQ,CAAC,UAAU,CAAC;GACxC,MAAM,KAAK,SAAS,QAAQ,UAAU;EACxC;CACF;;gCAMmD;;;;;;;;CAQnD,MAAgB,SAAS,QAAgB,aAAoC;EAC3E,MAAM,QAAQ,YAAY;EAG1B,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,QAAQ,CAAC,EAAC,CACnD,QAAQ,WAAW,WAAW,WAAW,CAAC,CAC1C,MAAM,GAAG,KAAK;EAEjB,IAAI,OAAO,W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,OAAO,OAAO;EAEhE,MAAM,KAAK,eAAe,GAAG;EAE7B,OAAO;CACT;;;;CAKA,MAAa,OAAO,KAAe,KAAiC;EAClE,OAAO,KAAK,OAAO,OAAO,KAAK,GAAG;CACpC;;;;CAKA,MAAa,UAAU,KAAe,QAAgB,GAAoB;EACxE,OAAO,KAAK,UAAU,KAAK,CAAC,KAAK;CACnC;AACF"}
1
+ {"version":3,"file":"tagged-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tagged-cache.ts"],"sourcesContent":["import type { CacheDriver, CacheKey, CacheSetOptions, CacheTtl, TaggedCacheDriver } from \"./types\";\nimport { sampleMembers } from \"./tag-sample\";\nimport { parseCacheKey } from \"./utils\";\n\n/** Implemented by `BaseCacheDriver`; a custom driver may not have it. */\ntype TagsInvalidatedEmitter = {\n emitTagsInvalidated(data: { tags: string[]; keys: string[]; durationMs: number }): Promise<void>;\n};\n\n/**\n * Tagged Cache Wrapper\n * Wraps a cache driver to automatically manage tag relationships\n */\nexport class TaggedCache implements TaggedCacheDriver {\n /**\n * The tags associated with this tagged cache instance\n */\n protected cacheTags: string[];\n\n /**\n * The underlying cache driver\n */\n protected driver: CacheDriver<any, any>;\n\n /**\n * Constructor\n */\n public constructor(tags: string[], driver: CacheDriver<any, any>) {\n this.cacheTags = tags;\n this.driver = driver;\n }\n\n /**\n * Get the tag key prefix for storing tag-key relationships\n */\n protected tagKey(tag: string): string {\n return `cache:tags:${tag}`;\n }\n\n /**\n * Store tag-key relationship\n */\n protected async storeTaggedKey(key: CacheKey): Promise<void> {\n await this.storeTagRelationship(key);\n }\n\n /**\n * Public alias of the tag-index writer. Called by `BaseCacheDriver.applyTags`\n * when tags are passed inline through `CacheSetOptions.tags`.\n *\n * Takes the caller's key, never the driver-parsed one — see {@link indexedKey}.\n *\n * @internal — public for cross-class use within this package; not part of the\n * stable consumer API.\n */\n public async storeTagRelationship(key: CacheKey): Promise<void> {\n const indexedKey = this.indexedKey(key);\n\n for (const tag of this.cacheTags) {\n const tagKey = this.tagKey(tag);\n\n await this.addToTag(tagKey, [indexedKey]);\n await this.pruneTag(tagKey, indexedKey);\n }\n }\n\n /**\n * Upper bound on member-existence checks per tagged write, so pruning stays\n * O(1) per write no matter how large an index grows.\n */\n protected static readonly PRUNE_CHECKS_PER_WRITE = 20;\n\n /**\n * Drop index members whose entry no longer exists (expired, evicted, or\n * removed outside a tagged handle). Checks a random window of at most\n * {@link PRUNE_CHECKS_PER_WRITE} members, so a long-lived index converges\n * to its live members without any write paying for a full scan.\n */\n protected async pruneTag(tagKey: string, justWritten: string): Promise<void> {\n const limit = TaggedCache.PRUNE_CHECKS_PER_WRITE;\n\n // One extra so the window stays full after dropping the key just written.\n const window = (await this.sampleOf(tagKey, limit + 1))\n .filter((member) => member !== justWritten)\n .slice(0, limit);\n\n if (window.length === 0) {\n return;\n }\n\n // Checked together: a networked driver sends them as one batch.\n const present = await Promise.all(window.map((member) => this.memberExists(member)));\n const missing = window.filter((_, index) => !present[index]);\n\n if (missing.length > 0) {\n await this.removeFromTag(tagKey, missing);\n }\n }\n\n /**\n * Up to `count` random members of an index: the driver's `tagSample` when it\n * has one, else a window of the full member list.\n */\n protected async sampleOf(tagKey: string, count: number): Promise<string[]> {\n if (typeof this.driver.tagSample === \"function\") {\n return this.driver.tagSample(tagKey, count);\n }\n\n return sampleMembers(await this.membersOf(tagKey), count);\n }\n\n /**\n * Whether an indexed key still has a live entry: the driver's `exists`\n * (no value read, no hit/miss events) when it has one, else `has()`.\n */\n protected async memberExists(member: string): Promise<boolean> {\n if (typeof this.driver.exists === \"function\") {\n return this.driver.exists(member);\n }\n\n return this.driver.has(member);\n }\n\n /**\n * Remove entries by their indexed keys: the driver's batched `removeMany`\n * when it has one, else `remove()` per key.\n */\n protected async removeEntries(keys: string[]): Promise<void> {\n if (typeof this.driver.removeMany === \"function\") {\n return this.driver.removeMany(keys);\n }\n\n for (const key of keys) {\n await this.driver.remove(key);\n }\n }\n\n // ------------------------------------------------------------\n // Tag-index access: the driver's primitives when it has them, else\n // the legacy get/set array (third-party drivers without primitives).\n // ------------------------------------------------------------\n\n protected async addToTag(tagKey: string, members: string[]): Promise<void> {\n if (typeof this.driver.tagAdd === \"function\") {\n return this.driver.tagAdd(tagKey, members);\n }\n\n const current = await this.legacyMembers(tagKey);\n const merged = [...new Set([...current, ...members])];\n\n if (merged.length !== current.length) {\n await this.driver.set(tagKey, merged, Infinity);\n }\n }\n\n protected async membersOf(tagKey: string): Promise<string[]> {\n if (typeof this.driver.tagMembers === \"function\") {\n return this.driver.tagMembers(tagKey);\n }\n\n return this.legacyMembers(tagKey);\n }\n\n protected async removeFromTag(tagKey: string, members: string[]): Promise<void> {\n if (typeof this.driver.tagRemove === \"function\") {\n return this.driver.tagRemove(tagKey, members);\n }\n\n const dropped = new Set(members);\n const current = await this.legacyMembers(tagKey);\n const kept = current.filter((member) => !dropped.has(member));\n\n if (kept.length === current.length) {\n return;\n }\n\n if (kept.length === 0) {\n await this.driver.remove(tagKey);\n } else {\n await this.driver.set(tagKey, kept, Infinity);\n }\n }\n\n protected async legacyMembers(tagKey: string): Promise<string[]> {\n const value = await this.driver.get(tagKey);\n\n return Array.isArray(value)\n ? value.filter((member): member is string => typeof member === \"string\")\n : [];\n }\n\n /**\n * The form a key takes inside a tag index: normalized but un-prefixed.\n *\n * The index is read back and deleted through `driver.remove(key)`, which\n * applies `globalPrefix` itself — so the index must hold the key *before*\n * the prefix, or invalidation would prefix it twice and delete nothing.\n * With a function prefix, the current prefix is re-applied at invalidation\n * time; the tag index key is resolved under that same prefix, so the two\n * agree as long as the prefix is stable for a given request/tenant.\n */\n protected indexedKey(key: CacheKey): string {\n return parseCacheKey(key);\n }\n\n /**\n * Get all keys associated with tags\n */\n protected async getTaggedKeys(): Promise<Set<string>> {\n const allKeys = new Set<string>();\n\n for (const tag of this.cacheTags) {\n for (const key of await this.membersOf(this.tagKey(tag))) {\n allKeys.add(key);\n }\n }\n\n return allKeys;\n }\n\n /**\n * {@inheritdoc}\n */\n public async set(\n key: CacheKey,\n value: any,\n ttlOrOptions?: CacheTtl | CacheSetOptions,\n ): Promise<any> {\n await this.driver.set(key, value, ttlOrOptions);\n\n await this.storeTaggedKey(key);\n\n return value;\n }\n\n /**\n * {@inheritdoc}\n */\n public async get(key: CacheKey): Promise<any | null> {\n return this.driver.get(key);\n }\n\n /**\n * {@inheritdoc}\n */\n public async remove(key: CacheKey): Promise<void> {\n const indexedKey = this.indexedKey(key);\n\n // Remove the value\n await this.driver.remove(key);\n\n // Remove from all tag relationships\n await this.detachFromTags(indexedKey);\n }\n\n /**\n * Invalidate (clear) all keys associated with the current tags\n */\n public async invalidate(): Promise<void> {\n const startedAt = performance.now();\n const removed = new Set<string>();\n\n for (const tag of this.cacheTags) {\n const tagKey = this.tagKey(tag);\n const members = await this.membersOf(tagKey);\n\n // Remove the tagged entries — indexed un-prefixed, so `remove()` prefixes once\n await this.removeEntries(members);\n\n for (const member of members) {\n removed.add(member);\n }\n\n // Remove exactly the members read above rather than dropping the whole\n // index: a key tagged concurrently (after the read) keeps its entry in\n // the index, so a later invalidate still reaches it.\n await this.removeFromTag(tagKey, members);\n }\n\n // Drivers built on `BaseCacheDriver` emit `invalidated`; a custom driver\n // without the method simply emits nothing.\n const driver = this.driver as Partial<TagsInvalidatedEmitter>;\n\n await driver.emitTagsInvalidated?.({\n tags: [...this.cacheTags],\n keys: [...removed],\n durationMs: performance.now() - startedAt,\n });\n }\n\n /**\n * Remove `indexedKey` from every tag of this handle.\n */\n protected async detachFromTags(indexedKey: string): Promise<void> {\n for (const tag of this.cacheTags) {\n await this.removeFromTag(this.tagKey(tag), [indexedKey]);\n }\n }\n\n /**\n * Flush all keys associated with the current tags\n * @deprecated Use invalidate() instead for better semantics\n */\n public async flush(): Promise<void> {\n return this.invalidate();\n }\n\n /**\n * {@inheritdoc}\n */\n public async has(key: CacheKey): Promise<boolean> {\n return this.driver.has(key);\n }\n\n /**\n * {@inheritdoc}\n */\n public async remember(key: CacheKey, ttl: number, callback: () => Promise<any>): Promise<any> {\n const value = await this.get(key);\n\n if (value !== null) {\n return value;\n }\n\n const result = await callback();\n await this.set(key, result, ttl);\n\n return result;\n }\n\n /**\n * {@inheritdoc}\n */\n public async pull(key: CacheKey): Promise<any | null> {\n // The driver's own `pull` (atomic on redis / pg / in-process drivers)\n // hands the value out once; then the key leaves this handle's tags.\n const value = await this.driver.pull(key);\n\n if (value !== null) {\n await this.detachFromTags(this.indexedKey(key));\n }\n\n return value;\n }\n\n /**\n * {@inheritdoc}\n */\n public async forever(key: CacheKey, value: any): Promise<any> {\n return this.set(key, value, Infinity);\n }\n\n /**\n * {@inheritdoc}\n */\n public async increment(\n key: CacheKey,\n value: number = 1,\n options?: { ttl?: CacheTtl },\n ): Promise<number> {\n // The driver's atomic increment (INCRBY / pg upsert / synchronous\n // in-process), then record the tag relationship.\n const newValue = await this.driver.increment(key, value, options);\n\n await this.storeTaggedKey(key);\n\n return newValue;\n }\n\n /**\n * {@inheritdoc}\n */\n public async extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n return this.driver.extend(key, ttl);\n }\n\n /**\n * {@inheritdoc}\n */\n public async decrement(key: CacheKey, value: number = 1): Promise<number> {\n return this.increment(key, -value);\n }\n}\n"],"mappings":";;;;;;;;AAaA,IAAa,cAAb,MAAa,YAAyC;;;;CAcpD,AAAO,YAAY,MAAgB,QAA+B;EAChE,KAAK,YAAY;EACjB,KAAK,SAAS;CAChB;;;;CAKA,AAAU,OAAO,KAAqB;EACpC,OAAO,cAAc;CACvB;;;;CAKA,MAAgB,eAAe,KAA8B;EAC3D,MAAM,KAAK,qBAAqB,GAAG;CACrC;;;;;;;;;;CAWA,MAAa,qBAAqB,KAA8B;EAC9D,MAAM,aAAa,KAAK,WAAW,GAAG;EAEtC,KAAK,MAAM,OAAO,KAAK,WAAW;GAChC,MAAM,SAAS,KAAK,OAAO,GAAG;GAE9B,MAAM,KAAK,SAAS,QAAQ,CAAC,UAAU,CAAC;GACxC,MAAM,KAAK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KAAK;CACxC;;;;;;CAOA,MAAa,aAA4B;EACvC,MAAM,UAAU,aAAa,KAAK,MAAM,SAAS,MAAM,KAAK,UAAU;EAEtE,IAAI,CAAC,WAAW,QAAQ,WAAW,GACjC;EAGF,MAAM,KAAK,MAAM,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW;CACnD;;;;;;CAOA,AAAU,eAAe,KAAuB;EAC9C,MAAM,YAAY,OAAO,QAAQ,WAAW,MAAM,cAAc,GAAG;EAEnE,IAAI,CAAC,WACH,OAAO,KAAK,MAAM;EAGpB,OAAO,GAAG,KAAK,MAAM,OAAO,GAAG;CACjC;AACF"}
1
+ {"version":3,"file":"tagged-scoped-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tagged-scoped-cache.ts"],"sourcesContent":["import type { ScopedCache } from \"./scoped-cache\";\nimport type {\n CacheKey,\n CacheSetOptions,\n CacheTtl,\n RememberOptions,\n TaggedScopedCacheContract,\n} from \"./types\";\nimport {\n injectTags,\n mergeTagSets,\n normalizeToOptions,\n normalizeToRememberOptions,\n parseCacheKey,\n} from \"./utils\";\n\n/**\n * One-shot tagged write handle on top of a {@link ScopedCache}.\n *\n * **Role.** Returned by `scope.tags([...])`. Adds a fixed list of tags to\n * every write produced through this handle, on top of any tags the parent\n * scope already contributes. Stateless except for the captured tag list.\n *\n * **Responsibility.**\n * - Owns: appending the handle's tags to writes, delegating tag-index\n * bookkeeping for `setNX` (which lacks an inline `tags` knob on the driver\n * contract), and computing the union for `invalidate()` calls.\n * - Does NOT own: storage, prefix-prepending (delegated to the scope),\n * default `ttl` (delegated to the scope), or any kind of long-lived state.\n *\n * Tags compose additively: scope tags + handle tags + per-call tags, all\n * unioned and deduped. The handle never replaces scope tags — `invalidate()`\n * always sees the full union.\n *\n * @example\n * // Inside application code — scope provides the per-user tag automatically:\n * const feed = cache.namespace(`feed.${userId}`, { tags: [`user.${userId}`] });\n *\n * await feed.tags([\"unread\"]).set(\"messages.1\", message);\n * // → tagged with [user.<id>, unread]\n *\n * await feed.tags([\"unread\"]).invalidate();\n * // → wipes everything tagged with user.<id> OR unread.\n */\nexport class TaggedScopedCache implements TaggedScopedCacheContract {\n /**\n * The {@link ScopedCache} this handle delegates to. Held by reference so\n * scope-default changes (none today, but the option is preserved for the\n * future) are visible without rebuilding the handle.\n */\n protected readonly scope: ScopedCache;\n\n /**\n * Tags this handle contributes to every write. Cloned at the call site so\n * later mutation of the input array doesn't leak in.\n */\n protected readonly handleTags: string[];\n\n /**\n * Build a tagged handle. Constructed via `scope.tags([...])` — users never\n * call this directly.\n */\n public constructor(scope: ScopedCache, handleTags: string[]) {\n this.scope = scope;\n this.handleTags = [...handleTags];\n }\n\n /**\n * Write the scoped key with the handle's tags appended to whatever the\n * caller passed. Scope-level tags are added on top by the scope itself.\n */\n public set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any> {\n const options = injectTags(normalizeToOptions(ttlOrOptions), this.handleTags);\n\n return this.scope.set(key, value, options);\n }\n\n /**\n * Read the scoped key. Tags don't affect reads — pass-through.\n */\n public get<T = any>(key: CacheKey): Promise<T | null> {\n return this.scope.get<T>(key);\n }\n\n /**\n * Check presence of the scoped key.\n */\n public has(key: CacheKey): Promise<boolean> {\n return this.scope.has(key);\n }\n\n /**\n * Remove the scoped key and take it out of every tag index this handle\n * writes to (scope tags + handle tags).\n */\n public async remove(key: CacheKey): Promise<void> {\n await this.scope.remove(key);\n await this.detachFromTags(key);\n }\n\n /**\n * Read-and-remove the scoped key, then take it out of this handle's tags.\n */\n public async pull<T = any>(key: CacheKey): Promise<T | null> {\n const value = await this.scope.pull<T>(key);\n\n if (value !== null) {\n await this.detachFromTags(key);\n }\n\n return value;\n }\n\n /**\n * Remove the un-prefixed scoped key from every tag index of this handle.\n */\n protected async detachFromTags(key: CacheKey): Promise<void> {\n const allTags = mergeTagSets(this.scope.defaults.tags, this.handleTags);\n\n if (!allTags || allTags.length === 0) {\n return;\n }\n\n const scopedKey = this.buildScopedKey(key);\n const tagged = this.scope.source.tags(allTags) as unknown as {\n detachFromTags: (indexedKey: string) => Promise<void>;\n };\n\n await tagged.detachFromTags(parseCacheKey(scopedKey));\n }\n\n /**\n * Permanent write with handle tags applied. Bypasses both the scope's and\n * the caller's TTL (forever means forever) — only tags get injected.\n */\n public forever<T = any>(key: CacheKey, value: T): Promise<T> {\n return this.scope.set(key, value, {\n ttl: Infinity,\n tags: this.handleTags,\n }) as Promise<T>;\n }\n\n /**\n * Atomic create-or-skip with the handle's tags applied on success. The\n * driver contract has no inline `tags` knob on `setNX`, so we register the\n * tag relationship manually after a successful write.\n */\n public async setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean> {\n const wasSet = await this.scope.setNX(key, value, ttl);\n\n if (!wasSet) {\n return false;\n }\n\n const allTags = mergeTagSets(this.scope.defaults.tags, this.handleTags);\n\n if (!allTags || allTags.length === 0) {\n return true;\n }\n\n // Register the un-prefixed scoped key — the tag index never holds the\n // driver-parsed form, so `invalidate()` can remove it via `remove(key)`.\n const scopedKey = this.buildScopedKey(key);\n const tagged = this.scope.source.tags(allTags) as unknown as {\n storeTagRelationship: (key: CacheKey) => Promise<void>;\n };\n\n await tagged.storeTagRelationship(scopedKey);\n\n return true;\n }\n\n /**\n * Read-or-compute with handle tags appended on the cache-miss write.\n */\n public remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n const options = injectTags(normalizeToRememberOptions(ttlOrOptions), this.handleTags);\n\n return this.scope.remember<T>(key, options, callback);\n }\n\n /**\n * Atomic counter increment on the scoped key. Tags aren't applied to\n * subsequent increments — they're attached at first-write time.\n */\n public increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number> {\n return this.scope.increment(key, value, options);\n }\n\n /**\n * Reset the expiry of the scoped key to `ttl` from now. Tags are untouched.\n */\n public extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n return this.scope.extend(key, ttl);\n }\n\n /**\n * Atomic counter decrement on the scoped key. See {@link increment}.\n */\n public decrement(key: CacheKey, value?: number): Promise<number> {\n return this.scope.decrement(key, value);\n }\n\n /**\n * Wipe every entry tagged with the union of (scope tags + handle tags).\n * Tags are global across the package, so this reaches outside the scope's\n * prefix when scope tags are also used elsewhere.\n */\n public async invalidate(): Promise<void> {\n const allTags = mergeTagSets(this.scope.defaults.tags, this.handleTags);\n\n if (!allTags || allTags.length === 0) {\n return;\n }\n\n await this.scope.source.tags(allTags).invalidate();\n }\n\n /**\n * Compute the source-side key the same way `ScopedCache.scopedKey` does —\n * needed for `setNX`, where we have to register the tag relationship by\n * hand because the driver contract doesn't accept inline tags there.\n */\n protected buildScopedKey(key: CacheKey): string {\n const keyString = typeof key === \"string\" ? key : parseCacheKey(key);\n\n if (!keyString) {\n return this.scope.prefix;\n }\n\n return `${this.scope.prefix}.${keyString}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,oBAAb,MAAoE;;;;;CAkBlE,AAAO,YAAY,OAAoB,YAAsB;EAC3D,KAAK,QAAQ;EACb,KAAK,aAAa,CAAC,GAAG,UAAU;CAClC;;;;;CAMA,AAAO,IAAI,KAAe,OAAY,cAAyD;EAC7F,MAAM,UAAU,WAAW,mBAAmB,YAAY,GAAG,KAAK,UAAU;EAE5E,OAAO,KAAK,MAAM,IAAI,KAAK,OAAO,OAAO;CAC3C;;;;CAKA,AAAO,IAAa,KAAkC;EACpD,OAAO,KAAK,MAAM,IAAO,GAAG;CAC9B;;;;CAKA,AAAO,IAAI,KAAiC;EAC1C,OAAO,KAAK,MAAM,IAAI,GAAG;CAC3B;;;;;CAMA,MAAa,OAAO,KAA8B;EAChD,MAAM,KAAK,MAAM,OAAO,GAAG;EAC3B,MAAM,KAAK,eAAe,GAAG;CAC/B;;;;CAKA,MAAa,KAAc,KAAkC;EAC3D,MAAM,QAAQ,MAAM,KAAK,MAAM,KAAQ,GAAG;EAE1C,IAAI,U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EACvC,MAAM,UAAU,aAAa,KAAK,MAAM,SAAS,MAAM,KAAK,UAAU;EAEtE,IAAI,CAAC,WAAW,QAAQ,WAAW,GACjC;EAGF,MAAM,KAAK,MAAM,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW;CACnD;;;;;;CAOA,AAAU,eAAe,KAAuB;EAC9C,MAAM,YAAY,OAAO,QAAQ,WAAW,MAAM,cAAc,GAAG;EAEnE,IAAI,CAAC,WACH,OAAO,KAAK,MAAM;EAGpB,OAAO,GAAG,KAAK,MAAM,OAAO,GAAG;CACjC;AACF"}
package/esm/types.d.mts CHANGED
@@ -145,6 +145,11 @@ export type RememberOptions = {
145
145
  * Tags attached to the entry created on miss. Invalidate via `cache.tags([...]).invalidate()`.
146
146
  */
147
147
  tags?: string[];
148
+ /**
149
+ * Spread the TTL by up to this many percent, either way, so entries written
150
+ * together do not all expire together. Same semantics as `CacheSetOptions.ttlJitter`.
151
+ */
152
+ ttlJitter?: number;
148
153
  /**
149
154
  * Per-call driver override. Routes this remember call (both read and write)
150
155
  * to the named driver without mutating `currentDriver`.
@@ -170,6 +175,14 @@ export type CacheSetOptions = {
170
175
  * Absolute expiration as a Unix epoch in milliseconds or a Date. Mutually exclusive with `ttl`.
171
176
  */
172
177
  expiresAt?: number | Date;
178
+ /**
179
+ * Spread the TTL by up to this many percent, either way (a random factor per
180
+ * write), so entries written together do not all expire together. `10` turns
181
+ * a one-hour TTL into 54 to 66 minutes. Applies to relative TTLs only (`ttl`
182
+ * or the driver default), never to `expiresAt` or `Infinity`. `0` or omitted
183
+ * disables it; values are clamped to 0..100.
184
+ */
185
+ ttlJitter?: number;
173
186
  /**
174
187
  * Tags attached to this entry for tag-based invalidation. Inline equivalent of
175
188
  * `cache.tags([...]).set(key, value)`.
@@ -264,6 +277,20 @@ export type CacheSwrOptions = {
264
277
  * background refresh. Past `staleTtl`, SWR blocks and refetches.
265
278
  */
266
279
  staleTtl: CacheTtl;
280
+ /**
281
+ * Serve the stale value when the refresh throws. With `failSafe: true` a
282
+ * caller that finds the entry in its stale window waits for the refresh
283
+ * (callers of the same key share one) and gets the stale value back if the
284
+ * callback throws; the failure is logged and emitted as an `error` event.
285
+ * Without it the stale value is returned at once and the refresh runs in the
286
+ * background.
287
+ */
288
+ failSafe?: boolean;
289
+ /**
290
+ * Spread `staleTtl` and `freshTtl` by up to this many percent, either way.
291
+ * Same semantics as `CacheSetOptions.ttlJitter`.
292
+ */
293
+ ttlJitter?: number;
267
294
  /**
268
295
  * Optional tags applied on the first miss-fetch and on every successful
269
296
  * background refresh. Same semantics as `CacheSetOptions.tags`.
@@ -296,6 +323,21 @@ export type CacheSimilarOptions = {
296
323
  * tags are considered (matches the union semantics elsewhere in the package).
297
324
  */
298
325
  tags?: string[];
326
+ /**
327
+ * Keep only the entries this predicate accepts, before `threshold` and `topK`
328
+ * apply, so `topK` counts in-scope entries only (one query, no widening). It
329
+ * receives the parsed key and the stored value, and runs in process: the
330
+ * memory and LRU drivers honour it; a driver that searches in the
331
+ * database (`pg`) ignores it, so callers that need a hard guarantee keep
332
+ * checking the returned hits too.
333
+ *
334
+ * @example
335
+ * await cache.similar(vector, { topK: 5, filter: (hit) => hit.key.startsWith("tenant.7.") });
336
+ */
337
+ filter?: (hit: {
338
+ key: string;
339
+ value: any;
340
+ }) => boolean;
299
341
  };
300
342
  /**
301
343
  * One result from a `similar()` query — the original key, its stored value,
@@ -688,6 +730,17 @@ export interface CacheDriver<ClientType, Options> {
688
730
  * Remove all cached items by namespace
689
731
  */
690
732
  removeNamespace(namespace: string): Promise<any>;
733
+ /**
734
+ * List the live keys stored under `namespace` (the namespace key itself and
735
+ * every `<namespace>.*` key; an empty namespace lists everything), in the
736
+ * form `get()` and `remove()` accept, so a caller can delete or read exactly
737
+ * the entries it owns instead of sweeping with `similar()`.
738
+ *
739
+ * Optional: a driver that cannot enumerate its keys leaves it out, and
740
+ * callers fall back to what they did before. Shipped by the memory, LRU
741
+ * memory, extended memory, file, Postgres, Redis, mock and null drivers.
742
+ */
743
+ listKeys?(namespace: string): Promise<string[]>;
691
744
  /**
692
745
  * Set the cache driver options
693
746
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/types.ts"],"mappings":";;;;;;;;;;;;;;;;qBAiBa,mBAAmB;EAC9B,YAAmB;;;;;qBASR,6BAA6B;EACxC,YAAmB;;;;;qBASR,gCAAgC;EAC3C,YAAmB;;;;;qBASR,uCAAuC;EAClD,YACE;;;;;;;;qBAaS,8BAA8B;EACzC,YAAmB;;;;;qBASR,8BAA8B;EACzC,YAAmB;;;;;;;;;YAaT;;;;;;;;YASA;;;;YAKA,eAAe;;;;EAIzB;;;;;EAKA,UAAU;;;;;;;;;;;;YAaA;;;;;EAKV,KAAK;;;;;EAKL;;;;EAIA;;;;;;;;;;;;;;;YAgBU,YAAY;EAAO;EAAgB,OAAO;;EAAQ;;;;;;;;;;;;;YAalD;;;;EAIV,MAAM;;;;EAIN;;;;;EAKA;;;;;;;;;;;;YAaU;;;;EAIV,MAAM;;;;EAIN,qBAAqB;;;;;EAKrB;;;;EAIA,aAAa;;;;EAIb;;;;;EAKA;;;;;;;;;;;;EAYA;;;;;;;;;;EAUA;;;;;;;;;;YAWU;;;;;EAKV,MAAM;;;;;;;;EAQN;;;;;;;;;;;;;;;;;;;YAoBU;;;;;;EAMV,UAAU;;;;;;EAMV,UAAU;;;;;EAKV;;;;;;EAMA;;;;;;YAOU;;;;;EAKV;;;;;EAKA;;;;;EAKA;;;;;;YAOU,gBAAgB;;;;EAI1B;;;;;EAKA,OAAO;;;;EAIP;;;;;YAMU,oBAAoB;YAEpB;;;;YAuBA;;;;YAeA;;;;EAIV;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;EAEA;;EAEA;;EAEA;;;;;YAMU,qBAAqB,WAAW,0BAA0B;;;;;;;;;YAU1D;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;IACE;IACA;IAC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YAE9E,oBACV,0CACA,aAAa,wBAAwB;;;;EAKrC,UAAU;;;;;;;;;EASV;;;;EAIA;IACE,eAAe;IACf,cAAc;IACd,cAAc;IACd,gBAAgB;IAChB,wBAAwB;IACxB,aAAa;IACb,YAAY;IACZ,cAAc;SAEb,OAAO,QAAQ,qBAAqB;;;;EAKvC;IACE,QAAQ;IACR,OAAO;IACP,SAAS;IACT,iBAAiB;IACjB,OAAO;IACP,MAAM;IACN,KAAK;IACL,OAAO;SAEN,OAAO,QAAQ,cAAc"}
package/esm/types.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../packages/cache/src/types.ts"],"mappings":";;;;AAiBA,IAAa,aAAb,cAAgC,MAAM;CACpC,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,uBAAb,cAA0C,WAAW;CACnD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,0BAAb,cAA6C,WAAW;CACtD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,iCAAb,cAAoD,WAAW;CAC7D,AAAO,YACL,UAAkB,wEAClB;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../packages/cache/src/types.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport type { RedisClientOptions } from \"redis\";\nimport type {\n BaseCacheDriver,\n FileCacheDriver,\n LRUMemoryCacheDriver,\n MemoryCacheDriver,\n MockCacheDriver,\n MemoryExtendedCacheDriver,\n NullCacheDriver,\n PgCacheDriver,\n RedisCacheDriver,\n} from \"./drivers\";\n\n/**\n * Base error class for cache-related errors\n */\nexport class CacheError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheError\";\n }\n}\n\n/**\n * Error thrown when cache connection fails\n */\nexport class CacheConnectionError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConnectionError\";\n }\n}\n\n/**\n * Error thrown when cache driver configuration is invalid\n */\nexport class CacheConfigurationError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConfigurationError\";\n }\n}\n\n/**\n * Error thrown when cache driver is not initialized\n */\nexport class CacheDriverNotInitializedError extends CacheError {\n public constructor(\n message: string = \"No cache driver initialized. Call cache.init() or cache.use() first.\",\n ) {\n super(message);\n this.name = \"CacheDriverNotInitializedError\";\n }\n}\n\n/**\n * Error thrown when a driver does not implement a requested operation.\n *\n * Raised when a caller invokes a method the driver cannot fulfill —\n * e.g. `update()` on the file driver before the file-lock primitive lands.\n */\nexport class CacheUnsupportedError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheUnsupportedError\";\n }\n}\n\n/**\n * Error thrown when an optimistic-concurrency update exhausts its retry budget.\n */\nexport class CacheConcurrencyError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConcurrencyError\";\n }\n}\n\n/**\n * TTL shape accepted by set/remember/config calls.\n *\n * - `number` — seconds\n * - `string` — human-readable duration parsed via `ms` (`\"1h\"`, `\"30m\"`, `\"7d\"`, `\"2 weeks\"`, …)\n * - `Infinity` — no expiration\n */\nexport type CacheTtl = number | string;\n\n/**\n * Conflict resolution policy for `set` operations.\n *\n * - `\"create\"` — set only if the key does not exist (Redis `NX`)\n * - `\"update\"` — set only if the key already exists (Redis `XX`)\n * - `\"upsert\"` — default; overwrite whether the key exists or not\n */\nexport type CacheConflictPolicy = \"create\" | \"update\" | \"upsert\";\n\n/**\n * Result of a conditional write (`onConflict: \"create\" | \"update\"`).\n */\nexport type CacheSetResult<T = any> = {\n /**\n * Whether the write actually took effect.\n */\n wasSet: boolean;\n /**\n * The existing value when the write was rejected. Undefined for successful writes\n * and for unconditional `upsert` writes.\n */\n existing: T | null;\n};\n\n/**\n * Options for `lock()` — TTL is required (forgotten locks would stay forever),\n * `owner` identifies who holds the lock (handy for debugging), `driver` routes\n * the call through a non-default driver.\n *\n * @example\n * await cache.lock(\"lock.import\", { ttl: \"5m\", driver: \"redis\" }, async () => {\n * await runImport();\n * });\n */\nexport type LockOptions = {\n /**\n * How long the lock lives before auto-release. Required — guards against\n * forgotten locks if the process crashes between acquire and release.\n */\n ttl: CacheTtl;\n /**\n * Identifying value stored under the lock key. Defaults to `pid.<process.pid>`.\n * Use a custom owner when you want a human-readable label (e.g. `\"worker.jobs-2\"`).\n */\n owner?: string;\n /**\n * Per-call driver override by registered name. Manager-level only.\n */\n driver?: string;\n};\n\n/**\n * Discriminated-union result of `lock()`. Unambiguous even when the wrapped\n * function legitimately returns `undefined` — the `acquired` flag tells you\n * whether `fn` ran at all.\n *\n * @example\n * const outcome = await cache.lock(\"lock.x\", \"1m\", async () => computeValue());\n * if (outcome.acquired) {\n * console.log(\"ran, got\", outcome.value);\n * } else {\n * console.log(\"skipped — someone else holds the lock\");\n * }\n */\nexport type LockOutcome<T> = { acquired: true; value: T } | { acquired: false };\n\n/**\n * Options for `remember()` when you need more than just a TTL — e.g. attaching\n * tags to the cache-miss write, or routing the single call to a non-default driver.\n *\n * Passed in the TTL position: `cache.remember(key, { ttl: \"1h\", tags: [\"users\"] }, fn)`.\n *\n * @example\n * await cache.remember(\"user.1\", { ttl: \"1h\", tags: [\"users\"] }, () =>\n * db.users.find(1),\n * );\n */\nexport type RememberOptions = {\n /**\n * TTL applied on cache miss. Accepts seconds (number) or duration string.\n */\n ttl?: CacheTtl;\n /**\n * Tags attached to the entry created on miss. Invalidate via `cache.tags([...]).invalidate()`.\n */\n tags?: string[];\n /**\n * Spread the TTL by up to this many percent, either way, so entries written\n * together do not all expire together. Same semantics as `CacheSetOptions.ttlJitter`.\n */\n ttlJitter?: number;\n /**\n * Per-call driver override. Routes this remember call (both read and write)\n * to the named driver without mutating `currentDriver`.\n */\n driver?: string;\n};\n\n/**\n * Rich options for the `set` call-site. Mutually exclusive with a positional TTL.\n *\n * @example\n * await cache.set(\"user:1\", user, {\n * ttl: \"1h\",\n * tags: [\"users\", \"active\"],\n * onConflict: \"create\",\n * });\n */\nexport type CacheSetOptions = {\n /**\n * Relative TTL (seconds or duration string). Mutually exclusive with `expiresAt`.\n */\n ttl?: CacheTtl;\n /**\n * Absolute expiration as a Unix epoch in milliseconds or a Date. Mutually exclusive with `ttl`.\n */\n expiresAt?: number | Date;\n /**\n * Spread the TTL by up to this many percent, either way (a random factor per\n * write), so entries written together do not all expire together. `10` turns\n * a one-hour TTL into 54 to 66 minutes. Applies to relative TTLs only (`ttl`\n * or the driver default), never to `expiresAt` or `Infinity`. `0` or omitted\n * disables it; values are clamped to 0..100.\n */\n ttlJitter?: number;\n /**\n * Tags attached to this entry for tag-based invalidation. Inline equivalent of\n * `cache.tags([...]).set(key, value)`.\n */\n tags?: string[];\n /**\n * Conflict resolution policy. Defaults to `\"upsert\"`.\n */\n onConflict?: CacheConflictPolicy;\n /**\n * Per-call namespace override. Applied ahead of `globalPrefix` for this write only.\n */\n namespace?: string;\n /**\n * Per-call driver override by registered name. Routes this write to a non-default driver\n * without mutating `currentDriver`.\n */\n driver?: string;\n /**\n * Optional embedding vector indexed alongside the entry for similarity retrieval\n * via `cache.similar(...)`. Drivers without similarity support throw\n * {@link CacheUnsupportedError} when this option is supplied.\n *\n * Cache is embedding-agnostic — callers compute the vector with whichever embedder\n * they like and pass the result here.\n *\n * @example\n * await cache.set(\"doc.123\", doc, { vector: await embed(doc.text), ttl: \"1d\" });\n */\n vector?: number[];\n /**\n * Freshness deadline as a Unix epoch in milliseconds. Primarily set by\n * {@link CacheSwrOptions} flow — entries with `staleAt` in the future are\n * considered \"fresh\" by `cache.swr()`; entries past `staleAt` but before\n * `expiresAt` are \"stale-but-revalidatable.\"\n *\n * Direct callers can pin this manually when bypassing `swr()`, but the\n * common path is `cache.swr(key, { freshTtl, staleTtl }, fn)`.\n */\n staleAt?: number;\n};\n\n/**\n * Options for `cache.namespace(prefix, options)` — defaults applied to every\n * write produced through the returned scope.\n *\n * Per-call options always win over scope defaults. Tags merge additively\n * (scope tags + call tags, deduped). Nested scopes inherit from the parent;\n * the child's own values override.\n */\nexport type CacheNamespaceOptions = {\n /**\n * Default TTL for writes inside this scope. Same shape as everywhere else\n * — number of seconds or a duration string (`\"1h\"`, `\"30d\"`, …).\n */\n ttl?: CacheTtl;\n /**\n * Tags auto-attached to every write inside this scope. Useful for cross-scope\n * invalidation hooks (e.g. tag every entry with `user.<id>` so a single\n * `cache.flushTag(\"user.42\")` wipes the user's footprint everywhere).\n *\n * Merged additively with per-call tags; scope tags are never replaced.\n */\n tags?: string[];\n};\n\n/**\n * Options for `cache.swr(key, options, callback)` — stale-while-revalidate.\n *\n * Two TTLs split the entry's lifecycle into three windows:\n * - `now < freshTtl` → fresh, return cached value, no upstream call.\n * - `freshTtl <= now < staleTtl` → stale-but-revalidatable, return cached\n * value immediately, kick off `callback` in the background to refresh.\n * - `now >= staleTtl` → expired, block on `callback` like a normal miss.\n *\n * Concurrent SWR callers in the stale window all return the cached value;\n * the background refresh runs exactly once per key (deduped via the\n * driver's per-key lock map).\n *\n * If the background refresh fails, the stale entry is preserved and the\n * error is logged + emitted on the `error` event. Callers that received\n * the stale value never see the failure — they got their data.\n */\nexport type CacheSwrOptions = {\n /**\n * How long the value is considered fresh. Within this window, SWR returns\n * the cached value with no upstream call. Accepts seconds or duration\n * string (`\"1m\"`, `\"30s\"`).\n */\n freshTtl: CacheTtl;\n /**\n * Total lifetime of the entry (must be greater than `freshTtl`). Between\n * `freshTtl` and `staleTtl`, SWR returns the stale value and triggers a\n * background refresh. Past `staleTtl`, SWR blocks and refetches.\n */\n staleTtl: CacheTtl;\n /**\n * Serve the stale value when the refresh throws. With `failSafe: true` a\n * caller that finds the entry in its stale window waits for the refresh\n * (callers of the same key share one) and gets the stale value back if the\n * callback throws; the failure is logged and emitted as an `error` event.\n * Without it the stale value is returned at once and the refresh runs in the\n * background.\n */\n failSafe?: boolean;\n /**\n * Spread `staleTtl` and `freshTtl` by up to this many percent, either way.\n * Same semantics as `CacheSetOptions.ttlJitter`.\n */\n ttlJitter?: number;\n /**\n * Optional tags applied on the first miss-fetch and on every successful\n * background refresh. Same semantics as `CacheSetOptions.tags`.\n */\n tags?: string[];\n /**\n * Per-call driver override by registered name. Routes both the read and\n * any write/refresh through the named driver without mutating\n * `currentDriver`. Same semantics as `RememberOptions.driver`.\n */\n driver?: string;\n};\n\n/**\n * Options for `cache.similar(vector, options)` — similarity retrieval against\n * stored entries previously written with `set({ vector })`.\n */\nexport type CacheSimilarOptions = {\n /**\n * Maximum number of hits to return. Required — no implicit default keeps\n * callers from accidentally pulling the entire candidate set.\n */\n topK: number;\n /**\n * Cosine similarity floor in `[0, 1]`. Hits scoring strictly below this are\n * filtered out before `topK` truncation.\n */\n threshold?: number;\n /**\n * Optional tag filter. Only entries tagged with at least one of the given\n * tags are considered (matches the union semantics elsewhere in the package).\n */\n tags?: string[];\n /**\n * Keep only the entries this predicate accepts, before `threshold` and `topK`\n * apply, so `topK` counts in-scope entries only (one query, no widening). It\n * receives the parsed key and the stored value, and runs in process: the\n * memory and LRU drivers honour it; a driver that searches in the\n * database (`pg`) ignores it, so callers that need a hard guarantee keep\n * checking the returned hits too.\n *\n * @example\n * await cache.similar(vector, { topK: 5, filter: (hit) => hit.key.startsWith(\"tenant.7.\") });\n */\n filter?: (hit: { key: string; value: any }) => boolean;\n};\n\n/**\n * One result from a `similar()` query — the original key, its stored value,\n * and the cosine similarity to the query vector.\n */\nexport type CacheSimilarHit<T = unknown> = {\n /**\n * The original cache key, post-`parseKey` normalization.\n */\n key: string;\n /**\n * Stored value, deep-cloned to protect the cache from accidental mutation\n * (same semantics as `get`).\n */\n value: T;\n /**\n * Cosine similarity in `[0, 1]`. Higher means more similar.\n */\n score: number;\n};\n\n/**\n * Cache key type - can be a string or an object\n */\nexport type CacheKey = string | GenericObject;\n\nexport type CacheOperationType =\n | \"fetching\"\n | \"fetched\"\n | \"caching\"\n | \"cached\"\n | \"flushing\"\n | \"flushed\"\n | \"removing\"\n | \"removed\"\n | \"clearing\"\n | \"cleared\"\n | \"expired\"\n | \"notFound\"\n | \"connecting\"\n | \"error\"\n | \"connectionFailed\"\n | \"connected\"\n | \"disconnecting\"\n | \"disconnected\";\n\n/**\n * Cache event types for observability\n */\nexport type CacheEventType =\n | \"hit\"\n | \"miss\"\n | \"set\"\n | \"removed\"\n | \"invalidated\"\n | \"flushed\"\n | \"expired\"\n | \"connected\"\n | \"disconnected\"\n | \"error\";\n\n/**\n * Cache event data structure\n */\nexport type CacheEventData = {\n /**\n * The cache key involved in the event\n */\n key?: string;\n /**\n * The value (for set/hit events)\n */\n value?: any;\n /**\n * TTL in seconds (for set events)\n */\n ttl?: number;\n /**\n * Driver name that emitted the event\n */\n driver: string;\n /**\n * Error object (for error events)\n */\n error?: any;\n /**\n * Namespace (for namespace operations)\n */\n namespace?: string;\n /** Tags passed to `tags([...]).invalidate()` (`invalidated` events only). */\n tags?: string[];\n /** Keys a tag invalidation removed (`invalidated` events only). */\n keys?: string[];\n /** How long the operation took, in milliseconds (`invalidated` events only). */\n durationMs?: number;\n};\n\n/**\n * Event handler function type\n */\nexport type CacheEventHandler = (eventData: CacheEventData) => void | Promise<void>;\n\n/**\n * Per-operation latency + counter snapshot returned by `cache.metrics()`.\n *\n * The shape is a single recursive level — the top object covers all drivers\n * and each entry under `byDriver` repeats the same fields without nesting\n * further. Use this for ad-hoc dashboards, exporters to Prometheus / StatsD,\n * or just `console.log` during development.\n */\nexport type CacheMetricsSnapshot = {\n /** Cumulative cache hits across the lifetime of the collector. */\n hits: number;\n /** Cumulative cache misses (lookups that returned null). */\n misses: number;\n /** Cumulative successful writes. */\n sets: number;\n /** Cumulative key removals. */\n removed: number;\n /** Cumulative cache errors emitted via the `error` event. */\n errors: number;\n /** `hits / (hits + misses)` — `0` when no read ops have happened yet. */\n hitRate: number;\n /** Latency percentiles in milliseconds, computed from a circular buffer. */\n latencyMs: {\n p50: number;\n p95: number;\n p99: number;\n /** Size of the underlying buffer at snapshot time (capped at the configured max). */\n samples: number;\n };\n /** Per-driver breakdowns keyed by driver name (`\"memory\"`, `\"redis\"`, …). */\n byDriver: Record<string, Omit<CacheMetricsSnapshot, \"byDriver\">>;\n /** Millisecond timestamp the collector last reset (or was instantiated). */\n startedAt: number;\n};\n\n/**\n * Tagged cache interface for working with cache tags\n */\nexport interface TaggedCacheDriver {\n /**\n * Set a value in cache with tags\n */\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n /**\n * Get a value from cache (checks tags)\n */\n get(key: CacheKey): Promise<any | null>;\n /**\n * Remove a specific key\n */\n remove(key: CacheKey): Promise<void>;\n /**\n * Invalidate (clear) all keys associated with the current tags\n */\n invalidate(): Promise<void>;\n /**\n * Flush all keys associated with the current tags\n * @deprecated Use invalidate() instead\n */\n flush(): Promise<void>;\n /**\n * Check if a key exists\n */\n has(key: CacheKey): Promise<boolean>;\n /**\n * Remember pattern with tags\n */\n remember(key: CacheKey, ttl: number, callback: () => Promise<any>): Promise<any>;\n /**\n * Pull value with tags\n */\n pull(key: CacheKey): Promise<any | null>;\n /**\n * Forever with tags\n */\n forever(key: CacheKey, value: any): Promise<any>;\n /**\n * Increment with tags\n */\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n /**\n * Decrement with tags\n */\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n}\n\nexport type MemoryCacheOptions = {\n /**\n * The global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for the cache. Accepts a number of seconds or a human-readable\n * duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Maximum number of entries. When exceeded, the least recently used\n * entries are evicted. `Infinity` (or `0`) removes the limit.\n *\n * @default 10000\n */\n maxSize?: number;\n};\n\nexport type MemoryExtendedCacheOptions = MemoryCacheOptions;\n\nexport type LRUMemoryCacheOptions = {\n /**\n * The maximum number of items in the cache\n *\n * @default 1000\n */\n capacity?: number;\n /**\n * The global prefix for the cache key. Applied via `parseCacheKey`, same\n * semantics as the other drivers.\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for new entries. Accepts a number of seconds or a\n * human-readable duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n};\n\nexport type FileCacheOptions = {\n /**\n * The global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for the cache. Accepts a number of seconds or a human-readable\n * duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default 0\n */\n ttl?: CacheTtl;\n /**\n * Storage cache directory\n *\n * @default storagePath(\"cache\")\n */\n directory: string | (() => string);\n /**\n * File name\n *\n * @default cache.json\n */\n fileName?: string | (() => string);\n};\n\nexport type RedisOptions = {\n /**\n * Redis Port\n *\n * @default 6379\n */\n port?: number;\n /**\n * Redis Host\n */\n host?: string;\n /**\n * Redis Username\n */\n username?: string;\n /**\n * Redis Password\n */\n password?: string;\n /**\n * Redis URL\n *\n * If used, it will override the host and port options\n */\n url?: string;\n /**\n * Global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL. Accepts a number of seconds or a human-readable duration string\n * like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Redis client options\n */\n clientOptions?: RedisClientOptions;\n};\n\nexport type NullCacheDriverOptions = GenericObject;\n\n/**\n * Options accepted by {@link MockCacheDriver}. Same shape as the memory\n * driver — only `globalPrefix` and `ttl` apply, since the mock's storage is\n * a plain `Map` with no eviction policy.\n */\nexport type MockCacheOptions = {\n /**\n * Global key prefix, applied via `parseKey` (matches the other drivers).\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL for new entries. Accepts seconds or a duration string.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n};\n\n/**\n * One row in {@link MockCacheDriver.callLog} — captures every public op\n * the driver received in arrival order. Useful for behavioral assertions\n * in downstream tests (\"did my service actually invalidate the cache?\").\n */\nexport type CacheCall = {\n /**\n * Operation name as it appears on the driver contract — `\"set\"`, `\"get\"`,\n * `\"remove\"`, `\"flush\"`, `\"removeNamespace\"`, `\"has\"`, etc.\n */\n operation: string;\n /**\n * Post-`parseKey` cache key when the op is key-addressed; `undefined` for\n * keyless ops (`flush`, `connect`, `disconnect`).\n */\n key?: string;\n /**\n * Raw arguments passed to the call site, in declaration order. Lets\n * callers assert on TTLs, options objects, vector payloads, etc.\n */\n args: unknown[];\n /**\n * `Date.now()` when the call was recorded. Useful for timing-related\n * assertions (e.g. \"the second invalidation came within 100ms\").\n */\n timestamp: number;\n};\n\n/**\n * Minimal `pg`-compatible client surface the cache driver depends on.\n *\n * Both `pg.Pool` and `pg.Client` from the `pg` package satisfy this — the\n * driver only ever calls `query(text, values)`. Typing it loosely keeps\n * `pg` strictly optional: consumers without the `pg` package installed\n * never hit a missing import.\n */\nexport type PgClientLike = {\n query(text: string, values?: unknown[]): Promise<{ rows: any[]; rowCount?: number | null }>;\n};\n\nexport type PgCacheOptions = {\n /**\n * User-supplied `pg.Pool` or `pg.Client`. The driver does NOT own the\n * connection lifecycle — `cache.disconnect()` will not close this client.\n */\n client: PgClientLike;\n /**\n * Database table name. Default: `\"warlock_cache\"`.\n *\n * Sanitized: only `[A-Za-z0-9_]` are allowed; anything else throws\n * {@link CacheConfigurationError} at `setOptions` time.\n */\n table?: string;\n /**\n * Global key prefix, applied via `parseKey` (same semantics as the other drivers).\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL for new entries. Accepts seconds or a duration string\n * (`\"1h\"`, `\"7d\"`, …).\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Optional pgvector configuration. When present, the driver provisions an\n * `embedding VECTOR(dimensions)` column + similarity index, and `similar()`\n * queries via the `<=>` cosine-distance operator.\n *\n * Requires the pgvector extension (`CREATE EXTENSION vector;`) — the driver\n * verifies its presence on the first vector operation and throws\n * {@link CacheConfigurationError} if missing.\n *\n * Omit this block (or remove it) to run the driver in KV-only mode —\n * `set({ vector })` and `similar()` then throw {@link CacheUnsupportedError}.\n */\n vector?: {\n /**\n * Vector dimension count. Must match the embedder you use throughout the\n * lifetime of the table. Mixing dimensions on the same table is unsupported.\n */\n dimensions: number;\n /**\n * pgvector index strategy. `hnsw` (default) is faster to query and slightly\n * slower to build; `ivfflat` is faster to build but typically slower to query.\n *\n * @default \"hnsw\"\n */\n index?: \"hnsw\" | \"ivfflat\";\n };\n};\n\nexport interface CacheDriver<ClientType, Options> {\n /**\n * The cache driver options\n */\n options: Options;\n /**\n * Cache driver name\n */\n name: string;\n /**\n * Set logging state\n */\n setLoggingState(shouldLog: boolean): any;\n /**\n * Remove all cached items by namespace\n */\n removeNamespace(namespace: string): Promise<any>;\n /**\n * List the live keys stored under `namespace` (the namespace key itself and\n * every `<namespace>.*` key; an empty namespace lists everything), in the\n * form `get()` and `remove()` accept, so a caller can delete or read exactly\n * the entries it owns instead of sweeping with `similar()`.\n *\n * Optional: a driver that cannot enumerate its keys leaves it out, and\n * callers fall back to what they did before. Shipped by the memory, LRU\n * memory, extended memory, file, Postgres, Redis, mock and null drivers.\n */\n listKeys?(namespace: string): Promise<string[]>;\n /**\n * Set the cache driver options\n */\n setOptions(options: Options): any;\n /**\n * Parse the key to be used in the cache\n */\n parseKey(key: CacheKey): string;\n /**\n * Set a value in the cache.\n *\n * @param key The cache key, could be an object or string\n * @param value The value to be stored in the cache\n * @param ttlOrOptions Either a TTL (seconds number, or duration string like `\"1h\"`),\n * or a full {@link CacheSetOptions} object.\n *\n * @example\n * // Positional TTL (back-compat)\n * await cache.set(\"user:1\", user, 3600);\n *\n * @example\n * // Human-readable duration\n * await cache.set(\"user:1\", user, \"1h\");\n *\n * @example\n * // Rich options\n * await cache.set(\"user:1\", user, { ttl: \"1h\", tags: [\"users\"], onConflict: \"create\" });\n */\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n /**\n * Get a value from the cache\n */\n get<T = any>(key: CacheKey): Promise<T | null>;\n /**\n * Remove a value from the cache\n */\n remove(key: CacheKey): Promise<void>;\n /**\n * Flush the entire cache\n */\n flush(): Promise<void>;\n /**\n * Connect to the cache driver\n */\n connect(): Promise<any>;\n /**\n * The cache client\n */\n client?: ClientType;\n /**\n * Disconnect the cache driver\n */\n disconnect(): Promise<void>;\n /**\n * Check if a key exists in the cache without fetching its value\n */\n has(key: CacheKey): Promise<boolean>;\n /**\n * Get value from cache or execute callback and cache the result.\n *\n * The second argument accepts a TTL (number of seconds or duration string like `\"1h\"`)\n * or a full {@link RememberOptions} object when you need to attach tags or route to\n * a non-default driver.\n *\n * @example\n * // Positional TTL — the common case\n * const user = await cache.remember(\"user.1\", \"1h\", () => db.users.find(1));\n *\n * @example\n * // Options form — tag the cache-miss write for bulk invalidation\n * const user = await cache.remember(\"user.1\", { ttl: \"1h\", tags: [\"users\"] }, () =>\n * db.users.find(1),\n * );\n */\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n /**\n * Stale-while-revalidate. Returns the cached value when fresh; returns\n * the stale value + kicks off a background refresh when within the\n * `freshTtl..staleTtl` window; blocks like a normal miss when past\n * `staleTtl`. Concurrent stale-window callers share one in-flight\n * refresh.\n *\n * Background refresh failures preserve the stale entry and emit an\n * `error` event — the stale-returning caller never sees the failure.\n *\n * @example\n * const product = await cache.swr(\n * \"product.42\",\n * { freshTtl: \"1m\", staleTtl: \"1h\" },\n * () => db.products.find(42),\n * );\n */\n swr<T = any>(key: CacheKey, options: CacheSwrOptions, callback: () => Promise<T>): Promise<T>;\n /**\n * Get a value and remove it, handing it out exactly once.\n *\n * Atomicity: across servers on `redis` (`GETDEL`) and `pg`\n * (`DELETE … RETURNING`); within the process on `memory`, `memoryExtended`,\n * `lru` and `mock`; serialized per key within the process only on `file`.\n */\n pull<T = any>(key: CacheKey): Promise<T | null>;\n /**\n * Set a value in cache permanently (no expiration)\n */\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n /**\n * Read, transform, and write a cached value without losing concurrent updates.\n *\n * The callback receives the current value (or `null` on miss) and returns the\n * next value. Returning `null` removes the key. TTL is preserved unless\n * explicitly overridden via options.\n *\n * Atomicity: across servers on `redis` and `pg` (optimistic\n * compare-and-set with retries — `fn` may run more than once under\n * contention, so keep it side-effect free). On every other driver updates\n * are serialized per key within ONE process only. `file` does not support it.\n *\n * @example\n * await cache.update<User>(\"user:1\", (current) => {\n * if (!current) return null;\n * return { ...current, lastSeen: Date.now() };\n * });\n */\n 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 /**\n * Shallow-merge a partial object into a cached value.\n *\n * If the key is missing, treats the current value as `{}`. Preserves TTL by default.\n *\n * @example\n * await cache.merge<User>(\"user:1\", { name: \"Jane\" });\n */\n merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T>;\n /**\n * List sub-API factory — returns a {@link CacheListAccessor} bound to the given key.\n *\n * @example\n * const recent = cache.list<Event>(\"recent-events\");\n * await recent.push(event);\n * const last10 = await recent.slice(0, 10);\n */\n list<T = any>(key: CacheKey): CacheListAccessor<T>;\n /**\n * Acquire a distributed lock, run `fn`, and auto-release. Returns a\n * {@link LockOutcome} so callers can distinguish \"ran and produced this value\"\n * from \"skipped because someone else holds the lock.\"\n *\n * Built on top of `set({ onConflict: \"create\" })` — Redis-native, emulated\n * on other drivers (single-process semantics elsewhere).\n *\n * @example\n * const outcome = await cache.lock(\"lock.import\", \"5m\", async () => {\n * await runImport();\n * return \"done\";\n * });\n */\n lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>>;\n /**\n * Increment a numeric value in cache. A missing key starts from 0 with the\n * per-call `options.ttl` (or driver default); an existing expiry is preserved.\n * An explicit TTL also repairs a live counter with no expiry.\n * Supply the TTL on every call for expiring counters: a separate seed may\n * expire before the atomic increment recreates the key.\n *\n * Atomicity: across servers on `redis` (`INCRBY`) and `pg` (single\n * upsert statement); within the process on `memory`, `memoryExtended`,\n * `lru` and `mock`; serialized per key within the process only on `file`.\n *\n * @param key The cache key\n * @param value The value to increment by (default 1)\n */\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n /**\n * Decrement a numeric value in cache\n *\n * @param key The cache key\n * @param value The value to decrement by (default 1)\n */\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Keep an entry and make it expire `ttl` from now (a sliding expiry).\n *\n * The deadline is RESET to `ttl` from the moment of the call; `ttl` is not\n * added to the time the entry had left. Resolves to `false` when the key is\n * missing or already expired (nothing is created). `0` or `Infinity` removes\n * the expiry.\n *\n * @param key The cache key\n * @param ttl Seconds, or a duration string such as `\"30m\"`\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n /**\n * Get multiple values from cache at once\n */\n many(keys: CacheKey[]): Promise<any[]>;\n /**\n * Set multiple values in cache at once\n */\n setMany(items: Record<string, any>, ttl?: number): Promise<void>;\n /**\n * Register an event listener\n */\n on(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Remove an event listener\n */\n off(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Register a one-time event listener\n */\n once(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Set if not exists (atomic operation)\n * Returns true if key was set, false if key already existed\n * Note: Not all drivers support this operation\n */\n setNX?(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n /**\n * Create a tagged cache instance for the given tags\n */\n tags(tags: string[]): TaggedCacheDriver;\n /**\n * Tag-index primitive: add `members` (normalized, un-prefixed cache keys)\n * to the index stored under `tagKey`. Optional — `TaggedCache` falls back to\n * a get/set array when a driver has none.\n *\n * Built-in drivers: redis → a native SET (`SADD`, atomic across servers);\n * pg → one atomic upsert of a JSON array row; memory / lru / mock → an\n * in-process set that is never evicted or expired; file (base default) →\n * a get/set array serialized per tag key in this process only.\n */\n tagAdd?(tagKey: CacheKey, members: string[]): Promise<void>;\n /**\n * Tag-index primitive: the members stored under `tagKey` (empty when none).\n */\n tagMembers?(tagKey: CacheKey): Promise<string[]>;\n /**\n * Tag-index primitive: remove `members` from `tagKey`. Members added\n * concurrently and not listed are kept.\n */\n tagRemove?(tagKey: CacheKey, members: string[]): Promise<void>;\n /**\n * Tag-index primitive: drop the whole index stored under `tagKey`.\n */\n tagDelete?(tagKey: CacheKey): Promise<void>;\n /**\n * Tag-index primitive: up to `count` members of `tagKey` picked at random\n * (every member when the index is smaller). Lets a tagged write check a\n * sample of the index without reading all of it.\n */\n tagSample?(tagKey: CacheKey, count: number): Promise<string[]>;\n /**\n * Whether a live (unexpired) entry exists for `key`, without reading its\n * value, emitting `hit`/`miss` or logging. Used by tag-index pruning.\n */\n exists?(key: CacheKey): Promise<boolean>;\n /**\n * Remove several keys in as few round trips as the backend allows. Each key\n * emits `removed`, as `remove()` does. Used by tag invalidation.\n */\n removeMany?(keys: CacheKey[]): Promise<void>;\n /**\n * Similarity retrieval. Returns the nearest stored entries to `vector` by\n * cosine similarity, ordered by descending score.\n *\n * Drivers without a similarity index throw {@link CacheUnsupportedError}.\n * Memory-family drivers brute-force scan in O(N) — suitable for development\n * but not for production knowledge bases beyond a few thousand entries; use\n * the `pg` driver (with pgvector) or `redis` driver (with RediSearch) instead.\n *\n * @example\n * const hits = await cache.similar(await embed(query), { topK: 5, threshold: 0.7 });\n */\n similar<T = any>(vector: number[], options: CacheSimilarOptions): Promise<CacheSimilarHit<T>[]>;\n}\n\n/**\n * Accessor for list-shaped cached values.\n *\n * Defaults to read-mutate-write semantics on non-native drivers (memory, file, LRU).\n * The Redis driver overrides this with native `LPUSH` / `RPUSH` / `LRANGE` / `LTRIM` for O(1) ops.\n */\nexport interface CacheListAccessor<T = any> {\n /**\n * Append one or more items to the tail of the list. Returns the new length.\n */\n push(...items: T[]): Promise<number>;\n /**\n * Prepend one or more items to the head of the list. Returns the new length.\n */\n unshift(...items: T[]): Promise<number>;\n /**\n * Remove and return the tail item, or `null` if the list is empty.\n */\n pop(): Promise<T | null>;\n /**\n * Remove and return the head item, or `null` if the list is empty.\n */\n shift(): Promise<T | null>;\n /**\n * Return a slice of the list. End is exclusive, mirroring `Array.prototype.slice`.\n */\n slice(start?: number, end?: number): Promise<T[]>;\n /**\n * Return the full list.\n */\n all(): Promise<T[]>;\n /**\n * Return the length of the list.\n */\n length(): Promise<number>;\n /**\n * Trim the list to the inclusive range `[start, end]`. Outside elements are dropped.\n */\n trim(start: number, end: number): Promise<void>;\n /**\n * Remove the entire list.\n */\n clear(): Promise<void>;\n}\n\n/**\n * One-shot tagged handle returned by `ScopedCacheContract.tags(...)`.\n *\n * Identical write surface to {@link TaggedCacheDriver}, except the underlying\n * scope's prefix is applied to every key and the scope's default TTL/tags\n * still flow through. Tags supplied here merge additively with scope-level\n * tags.\n */\nexport interface TaggedScopedCacheContract {\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n get<T = any>(key: CacheKey): Promise<T | null>;\n has(key: CacheKey): Promise<boolean>;\n remove(key: CacheKey): Promise<void>;\n pull<T = any>(key: CacheKey): Promise<T | null>;\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n /**\n * Invalidate every entry tagged with the union of scope tags + handle tags.\n * Forwarded to the underlying tag index — tags are global, scope-agnostic.\n */\n invalidate(): Promise<void>;\n}\n\n/**\n * Scoped view over the cache. Returned by `cache.namespace(prefix, options?)`.\n *\n * A scope prepends its `prefix` to every key, applies optional default TTL/tags\n * to every write, and forwards everything else to the underlying source. It\n * stores nothing of its own — purely a convenience wrapper.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * await chat.set(\"messages.1\", msg); // → \"chats.10.messages.1\", TTL 30d\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call ttl wins\n * await chat.clear(); // wipe the whole scope\n */\nexport interface ScopedCacheContract {\n /** The fully-qualified prefix this scope prepends to every key. */\n readonly prefix: string;\n\n /**\n * Nested scope. Inherits the parent's defaults; child's own options override.\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 namespace(prefix: string, options?: CacheNamespaceOptions): ScopedCacheContract;\n\n /**\n * One-shot tagged write handle. Tags merge additively with scope defaults.\n */\n tags(tags: string[]): TaggedScopedCacheContract;\n\n /** Wipe every entry under this scope's prefix. Sugar for `removeNamespace(prefix)`. */\n clear(): Promise<void>;\n\n // Reads\n get<T = any>(key: CacheKey): Promise<T | null>;\n has(key: CacheKey): Promise<boolean>;\n many(keys: CacheKey[]): Promise<any[]>;\n pull<T = any>(key: CacheKey): Promise<T | null>;\n\n // Writes\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n setMany(items: Record<string, any>, ttl?: number): Promise<void>;\n setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n remove(key: CacheKey): Promise<void>;\n\n // Read-or-compute\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n swr<T = any>(key: CacheKey, options: CacheSwrOptions, callback: () => Promise<T>): Promise<T>;\n\n // Mutations\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n 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 merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T>;\n\n // Structured accessors\n list<T = any>(key: CacheKey): CacheListAccessor<T>;\n\n // Coordination\n lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>>;\n\n // Similarity (delegated; throws CacheUnsupportedError if the driver lacks it)\n similar<T = any>(vector: number[], options: CacheSimilarOptions): Promise<CacheSimilarHit<T>[]>;\n}\n\nexport type CacheData = {\n /**\n * Value stored in the cache\n */\n data: any;\n /**\n * The expiration date in milliseconds\n */\n expiresAt?: number;\n /**\n * Time to live in seconds\n */\n ttl?: number;\n /**\n * Freshness deadline as a millisecond timestamp. Used by `swr()` — entries\n * with `staleAt` in the future are \"fresh\"; past `staleAt` but before\n * `expiresAt` are \"stale-but-revalidatable\" and trigger a background\n * refresh on the next read. Optional — entries written through plain\n * `set()` skip this field entirely and `swr()` treats them as always-fresh.\n */\n staleAt?: number;\n};\n\nexport type DriverClass = new () => CacheDriver<any, any>;\n\ntype DefaultDrivers =\n | \"redis\"\n | \"file\"\n | \"memory\"\n | \"memoryExtended\"\n | \"null\"\n | \"lru\"\n | \"pg\"\n | \"mock\";\n\ntype MergeWithDefaultDrivers<T> = T extends undefined ? DefaultDrivers : DefaultDrivers | T;\n\nexport type CacheConfigurations<\n T extends string | undefined = undefined,\n DriverName = MergeWithDefaultDrivers<T>,\n> = {\n /**\n * The default cache driver name\n */\n default?: DriverName;\n /**\n * Log every cache operation (fetching, caching, removing…) at `info` /\n * `success`. Off by default: the lines cost CPU on every cache call and\n * put cache keys in the logs. Errors and connection failures are logged\n * either way.\n *\n * @default false\n */\n logging?: boolean;\n /**\n * The cache drivers list\n */\n drivers: {\n redis?: typeof RedisCacheDriver;\n file?: typeof FileCacheDriver;\n null?: typeof NullCacheDriver;\n memory?: typeof MemoryCacheDriver;\n memoryExtended?: typeof MemoryExtendedCacheDriver;\n lru?: typeof LRUMemoryCacheDriver;\n pg?: typeof PgCacheDriver;\n mock?: typeof MockCacheDriver;\n } & {\n [key in Extract<T, string>]?: typeof BaseCacheDriver<any, any> | undefined;\n };\n /**\n * The cache driver options\n */\n options: {\n redis?: RedisOptions;\n file?: FileCacheOptions;\n memory?: MemoryCacheOptions;\n memoryExtended?: MemoryExtendedCacheOptions;\n null?: NullCacheDriverOptions;\n lru?: LRUMemoryCacheOptions;\n pg?: PgCacheOptions;\n mock?: MockCacheOptions;\n } & {\n [key in Extract<T, string>]?: GenericObject;\n };\n};\n"],"mappings":";;;;AAiBA,IAAa,aAAb,cAAgC,MAAM;CACpC,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,uBAAb,cAA0C,WAAW;CACnD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,0BAAb,cAA6C,WAAW;CACtD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,iCAAb,cAAoD,WAAW;CAC7D,AAAO,YACL,UAAkB,wEAClB;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
package/esm/utils.d.mts CHANGED
@@ -95,6 +95,12 @@ export declare function normalizeToRememberOptions(input?: CacheTtl | RememberOp
95
95
  * supplied together (mutually exclusive).
96
96
  */
97
97
  export declare function resolveTtl(ttl: CacheTtl | undefined, expiresAt: number | Date | undefined, fallback: number): number;
98
+ /**
99
+ * Spread a relative TTL by up to `jitterPercent` percent either way. An
100
+ * absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or
101
+ * non-positive percentage leave the TTL as it is. The result is at least 1.
102
+ */
103
+ export declare function applyTtlJitter(ttl: number, jitterPercent: number | undefined, expiresAt?: number | Date): number;
98
104
  /**
99
105
  * Combine any number of tag lists into a single deduped array, dropping
100
106
  * `undefined`/empty entries. Returns `undefined` when no tags survive — lets
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"mappings":";;;;;;;;;;;;;;;wBAwBgB,sBAAsB;;;;;;;;;wBA2CtB,cACd,KAAK,UACL;EAAW;;;;;;;;;;;;;;;;;;;;;;;;wBAqCG,SAAS,OAAO;;;;;;;;;;;;;wBAoDhB,eAAe,oBAAoB;;;;;;;;;;wBAsBnC,mBAAmB,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBxD,2BAA2B,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBhE,WACd,KAAK,sBACL,oBAAoB,kBACpB;;;;;;;;;;;;;;;wBAiCc,gBAAgB;;;;;;;;;;wBA2BhB,WAAW;EAAY;GAAmB,SAAS,GAAG,sBAAsB;;;;;;;;;;;;;;;;wBA0B5E,iBAAiB,aAAa;;;;;wBAwD9B,kBAAkB;;;;;;;;wBAWlB,cAAc;EAAmB;EAAiB;;oBAetD;;;;EAIV;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"mappings":";;;;;;;;;;;;;;;wBAwBgB,sBAAsB;;;;;;;;;wBA2CtB,cACd,KAAK,UACL;EAAW;;;;;;;;;;;;;;;;;;;;;;;;wBAqCG,SAAS,OAAO;;;;;;;;;;;;;wBAoDhB,eAAe,oBAAoB;;;;;;;;;;wBAsBnC,mBAAmB,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBxD,2BAA2B,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBhE,WACd,KAAK,sBACL,oBAAoB,kBACpB;;;;;;wBAwBc,eACd,aACA,mCACA,qBAAqB;;;;;;;;;;;;;;;wBAyBP,gBAAgB;;;;;;;;;;wBA2BhB,WAAW;EAAY;GAAmB,SAAS,GAAG,sBAAsB;;;;;;;;;;;;;;;;wBA0B5E,iBAAiB,aAAa;;;;;wBAwD9B,kBAAkB;;;;;;;;wBAWlB,cAAc;EAAmB;EAAiB;;oBAetD;;;;EAIV;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA"}
package/esm/utils.mjs CHANGED
@@ -153,6 +153,18 @@ function resolveTtl(ttl, expiresAt, fallback) {
153
153
  return fallback;
154
154
  }
155
155
  /**
156
+ * Spread a relative TTL by up to `jitterPercent` percent either way. An
157
+ * absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or
158
+ * non-positive percentage leave the TTL as it is. The result is at least 1.
159
+ */
160
+ function applyTtlJitter(ttl, jitterPercent, expiresAt) {
161
+ if (!jitterPercent || jitterPercent <= 0 || expiresAt !== void 0) return ttl;
162
+ if (!Number.isFinite(ttl) || ttl <= 0) return ttl;
163
+ const spread = Math.min(jitterPercent, 100) / 100;
164
+ const factor = 1 + (Math.random() * 2 - 1) * spread;
165
+ return Math.max(1, Math.round(ttl * factor));
166
+ }
167
+ /**
156
168
  * Combine any number of tag lists into a single deduped array, dropping
157
169
  * `undefined`/empty entries. Returns `undefined` when no tags survive — lets
158
170
  * callers skip emitting empty `tags: []` into option payloads.
@@ -298,5 +310,5 @@ let CACHE_FOR = /* @__PURE__ */ function(CACHE_FOR) {
298
310
  }({});
299
311
 
300
312
  //#endregion
301
- export { CACHE_FOR, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
313
+ export { CACHE_FOR, applyTtlJitter, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
302
314
  //# sourceMappingURL=utils.mjs.map
package/esm/utils.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"mappings":";;;;;;;;;AASA,MAAM,2BAA2B;;;;;;;;;;;;;;AAejC,SAAgB,sBAAsB,OAAuB;CAC3D,OAAO,MAAM,QACX,2BACC,cAAc,IAAI,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC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K,CAAC,EAAE;AACrD;AAEA,IAAY,YAAL;;;;CAIL;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;AACF"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"sourcesContent":["import { rtrim } from \"@mongez/reinforcements\";\nimport ms, { type StringValue } from \"ms\";\nimport type { CacheKey, CacheSetOptions, CacheTtl, RememberOptions } from \"./types\";\nimport { CacheConfigurationError } from \"./types\";\n\n/**\n * Characters that `parseCacheKey` strips or turns into the `.` separator.\n * Inside a value they would make two different keys equal.\n */\nconst KEY_SEPARATOR_CHARACTERS = /[%.,:{}\"[\\]]/g;\n\n/**\n * Escape a value for use as ONE segment of a cache key or namespace: the\n * characters the key format treats as separators or strips (`.` `,` `:`\n * `{` `}` `\"` `[` `]`, and `%` itself) are percent-encoded, so the value can\n * never reach into another key or namespace. Values without those\n * characters are returned unchanged.\n *\n * Use it for request-derived text (slugs, search terms, ids from a client).\n *\n * @example\n * cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);\n * // slug \"acme.billing\" → namespace \"tenant.acme%2Ebilling\", never inside \"tenant.acme\"\n */\nexport function escapeCacheKeySegment(value: string): string {\n return value.replace(\n KEY_SEPARATOR_CHARACTERS,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`,\n );\n}\n\n/**\n * Escape every string (and object key) inside an object key, so a value that\n * contains a separator cannot be read as two segments. Values without\n * separator characters keep their exact previous encoding.\n */\nfunction escapeKeyObject(value: unknown): unknown {\n if (typeof value === \"string\") {\n return escapeCacheKeySegment(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(escapeKeyObject);\n }\n\n if (value === null || typeof value !== \"object\" || value instanceof Date) {\n return value;\n }\n\n // A null-prototype object keeps an own `__proto__` key as data.\n const escaped: Record<string, unknown> = Object.create(null);\n\n for (const [name, child] of Object.entries(value)) {\n escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);\n }\n\n return escaped;\n}\n\n/**\n * Make a proper key for the cache.\n *\n * String keys are used as they are (`:` and `,` become `.`; `{}\"[]` are\n * removed). In an object key, separator characters inside the object's keys\n * and string values are escaped first (see {@link escapeCacheKeySegment}),\n * so `{ a: \"b.c\" }` and `{ a: \"b\", c: \"\" }` are different keys.\n */\nexport function parseCacheKey(\n key: CacheKey,\n options: { globalPrefix?: string | (() => string) } = {},\n): string {\n if (typeof key === \"object\") {\n key = JSON.stringify(escapeKeyObject(key));\n }\n\n // remove any curly braces and double quotes along with []\n key = key.replace(/[{}\"[\\]]/g, \"\").replaceAll(/[:,]/g, \".\");\n\n const cachePrefix =\n typeof options.globalPrefix === \"function\" ? options.globalPrefix() : options.globalPrefix;\n\n return rtrim(String(cachePrefix ? rtrim(cachePrefix, \".\") + \".\" + key : key), \".\");\n}\n\n/**\n * Parse a TTL value into seconds.\n *\n * Accepts:\n * - a number (seconds) — fractions are rounded UP to whole seconds\n * (so Redis `EX` never receives a fraction); `0` means \"no expiry\"\n * - `Infinity` — no expiration, returned unchanged\n * - a bare numeric string (e.g. `\"3600\"`, from env vars) — treated as seconds\n * - a human-readable duration string (e.g. `\"1h\"`, `\"30m\"`, `\"7d\"`) — parsed via `ms`,\n * then converted to seconds, rounding up\n *\n * Throws `CacheConfigurationError` on NaN, negative numbers, or unparseable strings.\n *\n * @example\n * parseTtl(3600); // 3600\n * parseTtl(0.5); // 1\n * parseTtl(\"3600\"); // 3600\n * parseTtl(\"500ms\"); // 1\n * parseTtl(\"1h\"); // 3600\n * parseTtl(\"7d\"); // 604800\n * parseTtl(Infinity); // Infinity\n */\nexport function parseTtl(input: CacheTtl): number {\n if (typeof input === \"number\") {\n if (Number.isNaN(input)) {\n throw new CacheConfigurationError(\"Invalid TTL: NaN.\");\n }\n\n if (input < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative number (${input}).`);\n }\n\n return Math.ceil(input);\n }\n\n if (typeof input !== \"string\" || input.trim() === \"\") {\n throw new CacheConfigurationError(\n `Invalid TTL: expected number or duration string, got ${typeof input}.`,\n );\n }\n\n const trimmed = input.trim();\n\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.ceil(Number(trimmed));\n }\n\n const milliseconds = ms(trimmed as StringValue);\n\n if (milliseconds === undefined || Number.isNaN(milliseconds)) {\n throw new CacheConfigurationError(\n `Invalid TTL duration string: \"${input}\". Expected forms like \"1h\", \"30m\", \"7d\".`,\n );\n }\n\n if (milliseconds < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative duration (\"${input}\").`);\n }\n\n return Math.ceil(milliseconds / 1000);\n}\n\n/**\n * Convert an absolute `expiresAt` (Date or epoch milliseconds) into a\n * relative TTL in seconds.\n *\n * Throws {@link CacheConfigurationError} when the deadline is in the past —\n * the caller almost certainly has a bug (stale timestamp, wrong unit, etc.)\n * and silently storing an already-expired entry would hide it.\n *\n * @example\n * expiresAtToTtl(new Date(Date.now() + 60_000)); // ~60\n * expiresAtToTtl(Date.now() + 30 * 60 * 1000); // ~1800\n */\nexport function expiresAtToTtl(expiresAt: number | Date): number {\n const deadline = expiresAt instanceof Date ? expiresAt.getTime() : expiresAt;\n const relativeMs = deadline - Date.now();\n\n if (relativeMs <= 0) {\n throw new CacheConfigurationError(\n `\\`expiresAt\\` must be in the future; got ${new Date(deadline).toISOString()}.`,\n );\n }\n\n return Math.ceil(relativeMs / 1000);\n}\n\n/**\n * Coerce the polymorphic 3rd `set` argument into a uniform `CacheSetOptions`\n * shape. Lets callers (and `BaseCacheDriver.resolveSetOptions`) skip per-shape\n * branching.\n *\n * - `undefined` / `null` → `{}` (resolves to driver-level defaults later)\n * - `number` / `string` (positional TTL) → `{ ttl }`\n * - already an options object → returned as-is\n */\nexport function normalizeToOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Sibling of {@link normalizeToOptions} for the `remember()` call site, where\n * the polymorphic 2nd argument is `CacheTtl | RememberOptions` (no `expiresAt`,\n * no `onConflict`). Returns the same shape so callers can `{ ...opts, ... }`\n * without branching.\n *\n * @example\n * normalizeToRememberOptions(60); // { ttl: 60 }\n * normalizeToRememberOptions(\"1h\"); // { ttl: \"1h\" }\n * normalizeToRememberOptions({ ttl: \"1h\", tags: [\"x\"] }); // returned as-is\n */\nexport function normalizeToRememberOptions(input?: CacheTtl | RememberOptions): RememberOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Resolve the final TTL in seconds for a `set` call. Precedence:\n *\n * 1. Caller's `ttl` (number or duration string) wins.\n * 2. Otherwise, caller's `expiresAt` is converted to relative seconds.\n * 3. Otherwise, `fallback` is used (driver-level default — typically\n * `Infinity` when no default is configured, meaning \"never expires\").\n *\n * Throws {@link CacheConfigurationError} when `ttl` and `expiresAt` are\n * supplied together (mutually exclusive).\n */\nexport function resolveTtl(\n ttl: CacheTtl | undefined,\n expiresAt: number | Date | undefined,\n fallback: number,\n): number {\n if (ttl !== undefined && expiresAt !== undefined) {\n throw new CacheConfigurationError(\n \"Cache set options cannot specify both `ttl` and `expiresAt` — choose one.\",\n );\n }\n\n if (ttl !== undefined) {\n return parseTtl(ttl);\n }\n\n if (expiresAt !== undefined) {\n return expiresAtToTtl(expiresAt);\n }\n\n return fallback;\n}\n\n/**\n * Spread a relative TTL by up to `jitterPercent` percent either way. An\n * absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or\n * non-positive percentage leave the TTL as it is. The result is at least 1.\n */\nexport function applyTtlJitter(\n ttl: number,\n jitterPercent: number | undefined,\n expiresAt?: number | Date,\n): number {\n if (!jitterPercent || jitterPercent <= 0 || expiresAt !== undefined) return ttl;\n if (!Number.isFinite(ttl) || ttl <= 0) return ttl;\n\n const spread = Math.min(jitterPercent, 100) / 100;\n const factor = 1 + (Math.random() * 2 - 1) * spread;\n\n return Math.max(1, Math.round(ttl * factor));\n}\n\n/**\n * Combine any number of tag lists into a single deduped array, dropping\n * `undefined`/empty entries. Returns `undefined` when no tags survive — lets\n * callers skip emitting empty `tags: []` into option payloads.\n *\n * Used by scoped-cache merging where scope tags + handle tags + per-call tags\n * must union additively without duplicates.\n *\n * @example\n * mergeTagSets([\"a\", \"b\"], [\"b\", \"c\"]); // [\"a\", \"b\", \"c\"]\n * mergeTagSets(undefined, [\"x\"]); // [\"x\"]\n * mergeTagSets(undefined, undefined); // undefined\n * mergeTagSets([], []); // undefined\n */\nexport function mergeTagSets(...lists: (string[] | undefined)[]): string[] | undefined {\n const flat: string[] = [];\n\n for (const list of lists) {\n if (!list || list.length === 0) {\n continue;\n }\n\n flat.push(...list);\n }\n\n if (flat.length === 0) {\n return undefined;\n }\n\n return Array.from(new Set(flat));\n}\n\n/**\n * Add extra tags to any option-bag that already shapes `tags?: string[]`.\n * Pure — clones the input shape, never mutates. Tags are appended (caller\n * is responsible for de-duplication if needed; pair with {@link mergeTagSets}).\n *\n * @example\n * injectTags({ ttl: \"1h\" }, [\"unread\"]); // { ttl: \"1h\", tags: [\"unread\"] }\n * injectTags({ tags: [\"a\"] }, [\"b\"]); // { tags: [\"a\", \"b\"] }\n */\nexport function injectTags<T extends { tags?: string[] }>(options: T, extraTags: string[]): T {\n if (extraTags.length === 0) {\n return options;\n }\n\n return {\n ...options,\n tags: [...(options.tags ?? []), ...extraTags],\n };\n}\n\n/**\n * Cosine similarity between two equal-length numeric vectors.\n *\n * Returns a value in `[-1, 1]` where `1` means perfectly aligned, `0` means\n * orthogonal, and `-1` means opposing. For typical embedding spaces (where\n * vectors live in the positive cone) the practical range is `[0, 1]`.\n *\n * Throws {@link CacheConfigurationError} on dimension mismatch — fail loud at\n * the call site rather than silently returning a misleading score. A zero-norm\n * vector on either side returns `0` (no defined direction to compare).\n *\n * @example\n * cosineSimilarity([1, 0, 0], [1, 0, 0]); // 1\n * cosineSimilarity([1, 0, 0], [0, 1, 0]); // 0\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n throw new CacheConfigurationError(\n `Vector dimension mismatch: got ${a.length} and ${b.length}.`,\n );\n }\n\n if (a.length === 0) {\n throw new CacheConfigurationError(\n \"Vector dimension mismatch: empty vector cannot be compared.\",\n );\n }\n\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n const x = a[i];\n const y = b[i];\n\n if (x === undefined || y === undefined) {\n // Unreachable: both guards above establish `a.length === b.length` and\n // a non-zero length, so every index in range exists on both sides. Said\n // out loud rather than asserted with `as number`, because the two guards\n // that make it true are the kind of thing a later edit removes — and if\n // one ever did, an assertion would let `undefined` into the arithmetic\n // and return NaN as a similarity SCORE. A silently wrong ranking is\n // worse than a stopped one.\n break;\n }\n\n dot += x * y;\n normA += x * x;\n normB += y * y;\n }\n\n if (normA === 0 || normB === 0) {\n return 0;\n }\n\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Matches userinfo credentials embedded in a connection URL\n * (e.g. `redis://user:pass@host`). Node/Redis/Postgres client errors\n * frequently echo the target connection string — including the password —\n * back in `error.message` on connection failure.\n */\nconst CREDENTIALS_IN_URL = /(:\\/\\/)[^\\s/@]+:[^\\s/@]+@/g;\n\n/**\n * Strip embedded `user:pass@` credentials from a string before it reaches\n * any log sink.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(CREDENTIALS_IN_URL, \"$1[REDACTED]@\");\n}\n\n/**\n * Reduce an unknown thrown value to a log-safe `{ message, code? }` shape.\n * Callers must never log the raw error object itself — it may carry the\n * connection URL (with password) in the top-level message, `cause`, or\n * driver-specific fields, all of which `console.log`/`util.inspect` would\n * still print in full.\n */\nexport function safeErrorInfo(error: unknown): { message: string; code?: string } {\n if (error instanceof Error) {\n const info: { message: string; code?: string } = {\n message: redactCredentials(error.message),\n };\n\n const code = (error as any).code;\n if (code) info.code = String(code);\n\n return info;\n }\n\n return { message: redactCredentials(String(error)) };\n}\n\nexport enum CACHE_FOR {\n /**\n * Cache for 30 Minutes (in seconds)\n */\n HALF_HOUR = 1800,\n /**\n * Cache for 1 Hour (in seconds)\n */\n ONE_HOUR = 3600,\n /**\n * Cache for 12 Hours (in seconds)\n */\n HALF_DAY = 43200,\n /**\n * Cache for 24 Hours (in seconds)\n */\n ONE_DAY = 86400,\n /**\n * Cache for 7 Days (in seconds)\n */\n ONE_WEEK = 604800,\n /**\n * Cache for 15 Days (in seconds)\n */\n HALF_MONTH = 1296000,\n /**\n * Cache for 30 Days (in seconds)\n */\n ONE_MONTH = 2592000,\n /**\n * Cache for 60 Days (in seconds)\n */\n TWO_MONTHS = 5184000,\n /**\n * Cache for 180 Days (in seconds)\n */\n SIX_MONTHS = 15768000,\n /**\n * Cache for 365 Days (in seconds)\n */\n ONE_YEAR = 31536000,\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,2BAA2B;;;;;;;;;;;;;;AAejC,SAAgB,sBAAsB,OAAuB;CAC3D,OAAO,MAAM,QACX,2BACC,cAAc,IAAI,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG,GACvF;AACF;;;;;;AAOA,SAAS,gBAAgB,OAAyB;CAChD,IAAI,OAAO,UAAU,UACnB,OAAO,sBAAsB,KAAK;CAGpC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,eAAe;CAGlC,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,iBAAiB,MAClE,OAAO;CAIT,MAAM,UAAmC,OAAO,OAAO,IAAI;CAE3D,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,GAC9C,QAAQ,sBAAsB,IAAI,KAAK,gBAAgB,KAAK;CAG9D,OAAO;AACT;;;;;;;;;AAUA,SAAgB,cACd,KACA,UA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