@warlock.js/cache 5.41.0 → 5.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/cjs/index.cjs +1341 -271
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/cache-manager.d.mts +41 -0
  5. package/esm/cache-manager.d.mts.map +1 -1
  6. package/esm/cache-manager.mjs +47 -2
  7. package/esm/cache-manager.mjs.map +1 -1
  8. package/esm/drivers/base-cache-driver.d.mts +14 -0
  9. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  10. package/esm/drivers/base-cache-driver.mjs +26 -1
  11. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  12. package/esm/drivers/lru-memory-cache-driver.d.mts +17 -1
  13. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  14. package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
  15. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  16. package/esm/drivers/memory-cache-driver.d.mts +19 -1
  17. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  18. package/esm/drivers/memory-cache-driver.mjs +34 -0
  19. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  20. package/esm/drivers/mock-cache-driver.d.mts +4 -0
  21. package/esm/drivers/mock-cache-driver.d.mts.map +1 -1
  22. package/esm/drivers/mock-cache-driver.mjs +18 -0
  23. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  24. package/esm/drivers/null-cache-driver.d.mts +6 -0
  25. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  26. package/esm/drivers/null-cache-driver.mjs +8 -0
  27. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  28. package/esm/drivers/pg-cache-driver.d.mts +7 -0
  29. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  30. package/esm/drivers/pg-cache-driver.mjs +17 -0
  31. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  32. package/esm/drivers/redis-cache-driver.d.mts +17 -1
  33. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  34. package/esm/drivers/redis-cache-driver.mjs +29 -0
  35. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  36. package/esm/idempotent.d.mts +35 -0
  37. package/esm/idempotent.d.mts.map +1 -0
  38. package/esm/idempotent.mjs +74 -0
  39. package/esm/idempotent.mjs.map +1 -0
  40. package/esm/index.d.mts +12 -2
  41. package/esm/index.mjs +7 -3
  42. package/esm/scoped-cache.d.mts +5 -0
  43. package/esm/scoped-cache.d.mts.map +1 -1
  44. package/esm/scoped-cache.mjs +7 -0
  45. package/esm/scoped-cache.mjs.map +1 -1
  46. package/esm/structures/bloom-filter.d.mts +33 -0
  47. package/esm/structures/bloom-filter.d.mts.map +1 -0
  48. package/esm/structures/bloom-filter.mjs +56 -0
  49. package/esm/structures/bloom-filter.mjs.map +1 -0
  50. package/esm/structures/cuckoo-filter.d.mts +36 -0
  51. package/esm/structures/cuckoo-filter.d.mts.map +1 -0
  52. package/esm/structures/cuckoo-filter.mjs +70 -0
  53. package/esm/structures/cuckoo-filter.mjs.map +1 -0
  54. package/esm/structures/frequency-tracker.d.mts +33 -0
  55. package/esm/structures/frequency-tracker.d.mts.map +1 -0
  56. package/esm/structures/frequency-tracker.mjs +75 -0
  57. package/esm/structures/frequency-tracker.mjs.map +1 -0
  58. package/esm/structures/hash.mjs +69 -0
  59. package/esm/structures/hash.mjs.map +1 -0
  60. package/esm/structures/hyperloglog.d.mts +27 -0
  61. package/esm/structures/hyperloglog.d.mts.map +1 -0
  62. package/esm/structures/hyperloglog.mjs +67 -0
  63. package/esm/structures/hyperloglog.mjs.map +1 -0
  64. package/esm/structures/index.d.mts +10 -0
  65. package/esm/structures/index.mjs +11 -0
  66. package/esm/structures/memory-structures-backend.d.mts +56 -0
  67. package/esm/structures/memory-structures-backend.d.mts.map +1 -0
  68. package/esm/structures/memory-structures-backend.mjs +114 -0
  69. package/esm/structures/memory-structures-backend.mjs.map +1 -0
  70. package/esm/structures/redis-structures-backend.d.mts +42 -0
  71. package/esm/structures/redis-structures-backend.d.mts.map +1 -0
  72. package/esm/structures/redis-structures-backend.mjs +259 -0
  73. package/esm/structures/redis-structures-backend.mjs.map +1 -0
  74. package/esm/structures/sizing.mjs +26 -0
  75. package/esm/structures/sizing.mjs.map +1 -0
  76. package/esm/structures/structures.d.mts +22 -0
  77. package/esm/structures/structures.d.mts.map +1 -0
  78. package/esm/structures/structures.mjs +44 -0
  79. package/esm/structures/structures.mjs.map +1 -0
  80. package/esm/structures/types.d.mts +108 -0
  81. package/esm/structures/types.d.mts.map +1 -0
  82. package/esm/structures/types.mjs +8 -0
  83. package/esm/structures/types.mjs.map +1 -0
  84. package/esm/structures/unique-counter.d.mts +33 -0
  85. package/esm/structures/unique-counter.d.mts.map +1 -0
  86. package/esm/structures/unique-counter.mjs +43 -0
  87. package/esm/structures/unique-counter.mjs.map +1 -0
  88. package/esm/tagged-cache.d.mts +4 -0
  89. package/esm/tagged-cache.d.mts.map +1 -1
  90. package/esm/tagged-cache.mjs +6 -0
  91. package/esm/tagged-cache.mjs.map +1 -1
  92. package/esm/tagged-scoped-cache.d.mts +4 -0
  93. package/esm/tagged-scoped-cache.d.mts.map +1 -1
  94. package/esm/tagged-scoped-cache.mjs +6 -0
  95. package/esm/tagged-scoped-cache.mjs.map +1 -1
  96. package/esm/types.d.mts +24 -0
  97. package/esm/types.d.mts.map +1 -1
  98. package/esm/types.mjs.map +1 -1
  99. package/llms-full.txt +112 -1
  100. package/llms.txt +3 -0
  101. package/package.json +3 -3
  102. package/skills/index.md +3 -1
  103. package/skills/use-cache-extend/SKILL.md +22 -0
  104. package/skills/use-cache-idempotent/SKILL.md +27 -0
  105. package/skills/use-cache-structures/SKILL.md +48 -0
@@ -0,0 +1,259 @@
1
+ //#region ../../packages/cache/src/structures/redis-structures-backend.ts
2
+ /**
3
+ * Redis implementation of the structure primitives.
4
+ *
5
+ * Portable path (any Redis): bitmaps (`SETBIT` / `GETBIT`), hashes
6
+ * (`HINCRBY`), native HyperLogLog (`PFADD` / `PFCOUNT`) and sorted sets.
7
+ * When the server runs RedisBloom, {@link native} exposes `BF.*`, `CF.*`,
8
+ * `CMS.*` and `TOPK.*` operations, detected once with `MODULE LIST`.
9
+ */
10
+ var RedisStructuresBackend = class {
11
+ constructor(getClient, parseKey) {
12
+ this.getClient = getClient;
13
+ this.parseKey = parseKey;
14
+ }
15
+ send(args) {
16
+ return this.getClient().sendCommand(args.map(String));
17
+ }
18
+ /**
19
+ * Give a key without an expiry its ttl. A key that already expires keeps its
20
+ * deadline, so later writes never push the window back.
21
+ */
22
+ async applyTtl(key, options) {
23
+ if (!options?.ttl || !Number.isFinite(options.ttl)) return;
24
+ if (Number(await this.send(["TTL", key])) === -1) await this.send([
25
+ "EXPIRE",
26
+ key,
27
+ Math.ceil(options.ttl)
28
+ ]);
29
+ }
30
+ async bitSet(key, offsets, options) {
31
+ const parsed = this.parseKey(key);
32
+ const previous = await Promise.all(offsets.map((offset) => this.send([
33
+ "SETBIT",
34
+ parsed,
35
+ offset,
36
+ 1
37
+ ])));
38
+ await this.applyTtl(parsed, options);
39
+ return previous.map((value) => Number(value) === 1);
40
+ }
41
+ async bitGet(key, offsets) {
42
+ const parsed = this.parseKey(key);
43
+ return (await Promise.all(offsets.map((offset) => this.send([
44
+ "GETBIT",
45
+ parsed,
46
+ offset
47
+ ])))).map((value) => Number(value) === 1);
48
+ }
49
+ async gridAdd(key, cells, delta, options) {
50
+ const parsed = this.parseKey(key);
51
+ const values = await Promise.all(cells.map((cell) => this.send([
52
+ "HINCRBY",
53
+ parsed,
54
+ cell,
55
+ delta
56
+ ])));
57
+ await this.applyTtl(parsed, options);
58
+ return values.map((value) => Math.max(0, Number(value)));
59
+ }
60
+ async gridGet(key, cells) {
61
+ if (cells.length === 0) return [];
62
+ return (await this.send([
63
+ "HMGET",
64
+ this.parseKey(key),
65
+ ...cells
66
+ ])).map((value) => Math.max(0, Number(value ?? 0)));
67
+ }
68
+ async uniqueAdd(key, member, options) {
69
+ const parsed = this.parseKey(key);
70
+ const changed = await this.send([
71
+ "PFADD",
72
+ parsed,
73
+ member
74
+ ]);
75
+ await this.applyTtl(parsed, options);
76
+ return Number(changed) === 1;
77
+ }
78
+ async uniqueCount(keys) {
79
+ if (keys.length === 0) return 0;
80
+ return Number(await this.send(["PFCOUNT", ...keys.map((key) => this.parseKey(key))]));
81
+ }
82
+ async rankedSet(key, member, score, capacity, options) {
83
+ const parsed = this.parseKey(key);
84
+ await this.send([
85
+ "ZADD",
86
+ parsed,
87
+ score,
88
+ member
89
+ ]);
90
+ await this.send([
91
+ "ZREMRANGEBYRANK",
92
+ parsed,
93
+ 0,
94
+ -(capacity + 1)
95
+ ]);
96
+ await this.applyTtl(parsed, options);
97
+ }
98
+ async rankedTop(key, count) {
99
+ return pairs(await this.send([
100
+ "ZREVRANGE",
101
+ this.parseKey(key),
102
+ 0,
103
+ count - 1,
104
+ "WITHSCORES"
105
+ ])).map(([member, score]) => ({
106
+ member: String(member),
107
+ score: Number(score)
108
+ }));
109
+ }
110
+ native() {
111
+ this.nativeProbe ??= this.detectModule().then((present) => present ? this.createNative() : null);
112
+ return this.nativeProbe;
113
+ }
114
+ async detectModule() {
115
+ try {
116
+ return containsModule(await this.send(["MODULE", "LIST"]));
117
+ } catch {
118
+ return false;
119
+ }
120
+ }
121
+ /** Run `command`; when the key is missing, `init` creates it and `command` runs again. */
122
+ async withInit(command, init) {
123
+ try {
124
+ return await command();
125
+ } catch (error) {
126
+ if (!/not exist|no such key|not found/i.test(String(error?.message))) throw error;
127
+ try {
128
+ await init();
129
+ } catch (initError) {
130
+ if (!/exist/i.test(String(initError?.message))) throw initError;
131
+ }
132
+ return command();
133
+ }
134
+ }
135
+ createNative() {
136
+ const first = (reply) => Array.isArray(reply) ? reply[0] : reply;
137
+ return {
138
+ bloomAdd: async (key, item, { capacity, errorRate, ttl }) => {
139
+ const parsed = this.parseKey(key);
140
+ const reply = await this.send([
141
+ "BF.INSERT",
142
+ parsed,
143
+ "CAPACITY",
144
+ capacity,
145
+ "ERROR",
146
+ errorRate,
147
+ "ITEMS",
148
+ item
149
+ ]);
150
+ await this.applyTtl(parsed, { ttl });
151
+ return Number(first(reply)) === 1;
152
+ },
153
+ bloomExists: async (key, item) => Number(await this.send([
154
+ "BF.EXISTS",
155
+ this.parseKey(key),
156
+ item
157
+ ])) === 1,
158
+ cuckooAdd: async (key, item, { capacity, ttl }) => {
159
+ const parsed = this.parseKey(key);
160
+ const reply = await this.send([
161
+ "CF.INSERT",
162
+ parsed,
163
+ "CAPACITY",
164
+ capacity,
165
+ "ITEMS",
166
+ item
167
+ ]);
168
+ await this.applyTtl(parsed, { ttl });
169
+ return Number(first(reply)) === 1;
170
+ },
171
+ cuckooRemove: async (key, item) => Number(await this.send([
172
+ "CF.DEL",
173
+ this.parseKey(key),
174
+ item
175
+ ])) === 1,
176
+ cuckooExists: async (key, item) => Number(await this.send([
177
+ "CF.EXISTS",
178
+ this.parseKey(key),
179
+ item
180
+ ])) === 1,
181
+ frequencyAdd: async (key, item, count, { width, depth, topK, ttl }) => {
182
+ const cms = `${this.parseKey(key)}.cms`;
183
+ const top = `${this.parseKey(key)}.topk`;
184
+ await this.withInit(() => this.send([
185
+ "CMS.INCRBY",
186
+ cms,
187
+ item,
188
+ count
189
+ ]), () => this.send([
190
+ "CMS.INITBYDIM",
191
+ cms,
192
+ width,
193
+ depth
194
+ ]));
195
+ await this.withInit(() => this.send([
196
+ "TOPK.INCRBY",
197
+ top,
198
+ item,
199
+ count
200
+ ]), () => this.send([
201
+ "TOPK.RESERVE",
202
+ top,
203
+ topK,
204
+ width,
205
+ depth,
206
+ "0.9"
207
+ ]));
208
+ await this.applyTtl(cms, { ttl });
209
+ await this.applyTtl(top, { ttl });
210
+ },
211
+ frequencyEstimate: async (key, item) => {
212
+ try {
213
+ return Number(first(await this.send([
214
+ "CMS.QUERY",
215
+ `${this.parseKey(key)}.cms`,
216
+ item
217
+ ])));
218
+ } catch (error) {
219
+ if (/not exist|no such key|not found/i.test(String(error?.message))) return 0;
220
+ throw error;
221
+ }
222
+ },
223
+ frequencyTop: async (key, count) => {
224
+ try {
225
+ return pairs(await this.send([
226
+ "TOPK.LIST",
227
+ `${this.parseKey(key)}.topk`,
228
+ "WITHCOUNT"
229
+ ])).map(([member, score]) => ({
230
+ member: String(member),
231
+ score: Number(score)
232
+ })).slice(0, count);
233
+ } catch (error) {
234
+ if (/not exist|no such key|not found/i.test(String(error?.message))) return [];
235
+ throw error;
236
+ }
237
+ }
238
+ };
239
+ }
240
+ };
241
+ function pairs(flat) {
242
+ const result = [];
243
+ for (let index = 0; index + 1 < flat.length; index += 2) result.push([flat[index], flat[index + 1]]);
244
+ return result;
245
+ }
246
+ /** True when a `MODULE LIST` reply (any client shape) names the RedisBloom module. */
247
+ function containsModule(reply) {
248
+ if (typeof reply === "string") {
249
+ const name = reply.toLowerCase();
250
+ return name === "bf" || name === "redisbloom";
251
+ }
252
+ if (Array.isArray(reply)) return reply.some(containsModule);
253
+ if (reply && typeof reply === "object") return Object.values(reply).some(containsModule);
254
+ return false;
255
+ }
256
+
257
+ //#endregion
258
+ export { RedisStructuresBackend, containsModule };
259
+ //# sourceMappingURL=redis-structures-backend.mjs.map
@@ -0,0 +1 @@
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 === \"object\") {\n return Object.values(reply).some(containsModule);\n }\n\n return false;\n}\n"],"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;;;;;CAMA,MAAgB,SAAS,KAAa,SAA0B;EAC9D,IAAI,CAAC,SAAS,OAAO,CAAC,OAAO,SAAS,QAAQ,GAAG,GAC/C;EAGF,IAAI,OAAO,MAAM,KAAK,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,MAAM,IAC5C,MAAM,KAAK,KAAK;GAAC;GAAU;GAAK,KAAK,KAAK,QAAQ,GAAG;EAAC,CAAC;CAE3D;CAEA,MAAa,OAAO,KAAa,SAAmB,SAA0B;EAC5E,MAAM,SAAS,KAAK,SAAS,GAAG;EAChC,MAAM,WAAW,MAAM,QAAQ,IAC7B,QAAQ,KAAK,WAAW,KAAK,KAAK;GAAC;GAAU;GAAQ;GAAQ;EAAC,CAAC,CAAC,CAClE;EAEA,MAAM,KAAK,SAAS,QAAQ,OAAO;EAEnC,OAAO,SAAS,KAAK,UAAU,OAAO,KAAK,MAAM,CAAC;CACpD;CAEA,MAAa,OAAO,KAAa,SAAmB;EAClD,MAAM,SAAS,KAAK,SAAS,GAAG;EAGhC,QAAO,MAFY,QAAQ,IAAI,QAAQ,KAAK,WAAW,KAAK,KAAK;GAAC;GAAU;GAAQ;EAAM,CAAC,CAAC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AK,KAAK;MAAC;MAAa,GAAG,KAAK,SAAS,GAAG,EAAE;MAAO;KAAI,CAAC,CAAC,CAAC;IACxF,SAAS,OAAO;KACd,IAAI,mCAAmC,KAAK,OAAQ,OAAiB,OAAO,CAAC,GAC3E,OAAO;KAGT,MAAM;IACR;GACF;GACA,cAAc,OAAO,KAAK,UAAU;IAClC,IAAI;KAOF,OAAO,MAAM,MANO,KAAK,KAAK;MAC5B;MACA,GAAG,KAAK,SAAS,GAAG,EAAE;MACtB;KACF,CAAC,CAEgB,CAAC,CACf,KAAK,CAAC,QAAQ,YAAY;MAAE,QAAQ,OAAO,MAAM;MAAG,OAAO,OAAO,KAAK;KAAE,EAAE,CAAC,CAC5E,MAAM,GAAG,KAAK;IACnB,SAAS,OAAO;KACd,IAAI,mCAAmC,KAAK,OAAQ,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"}
@@ -0,0 +1,26 @@
1
+ import { CacheConfigurationError } from "../types.mjs";
2
+
3
+ //#region ../../packages/cache/src/structures/sizing.ts
4
+ /**
5
+ * Bloom filter geometry for `expectedItems` at `errorRate`: the number of bits
6
+ * and the number of hash functions that minimise memory for that error rate.
7
+ *
8
+ * One million items at 1% need about 9.6 million bits (1.2 MB) and 7 hashes;
9
+ * at 0.1% about 14.4 million bits (1.8 MB) and 10 hashes.
10
+ */
11
+ function bloomGeometry(expectedItems, errorRate) {
12
+ assertPositiveInteger("expectedItems", expectedItems);
13
+ if (!(errorRate > 0 && errorRate < 1)) throw new CacheConfigurationError(`Invalid errorRate: ${errorRate}. Expected a number between 0 and 1 (exclusive), e.g. 0.01.`);
14
+ const bits = Math.ceil(-expectedItems * Math.log(errorRate) / Math.LN2 ** 2);
15
+ return {
16
+ bits,
17
+ hashes: Math.max(1, Math.round(bits / expectedItems * Math.LN2))
18
+ };
19
+ }
20
+ function assertPositiveInteger(name, value) {
21
+ if (!Number.isInteger(value) || value <= 0) throw new CacheConfigurationError(`Invalid ${name}: ${value}. Expected a positive integer.`);
22
+ }
23
+
24
+ //#endregion
25
+ export { assertPositiveInteger, bloomGeometry };
26
+ //# sourceMappingURL=sizing.mjs.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,22 @@
1
+ import { BloomOptions, CuckooOptions, FrequencyOptions, UniqueCounterOptions } from "./types.mjs";
2
+ import { BloomFilter } from "./bloom-filter.mjs";
3
+ import { CuckooFilter } from "./cuckoo-filter.mjs";
4
+ import { FrequencyTracker } from "./frequency-tracker.mjs";
5
+ import { UniqueCounter, UniqueCounterGroup } from "./unique-counter.mjs";
6
+ //#region ../../packages/cache/src/structures/structures.d.ts
7
+ export type UniqueCounterFactory = {
8
+ (key: string, options?: UniqueCounterOptions): UniqueCounter;
9
+ /** Count distinct values across several counters without changing them. */
10
+ merge(keys: string[]): UniqueCounterGroup;
11
+ };
12
+ /**
13
+ * The `cache.structures` namespace.
14
+ */
15
+ export type CacheStructures = {
16
+ bloom(key: string, options: BloomOptions): BloomFilter;
17
+ cuckoo(key: string, options: CuckooOptions): CuckooFilter;
18
+ uniqueCounter: UniqueCounterFactory;
19
+ frequency(key: string, options?: FrequencyOptions): FrequencyTracker;
20
+ };
21
+ //#endregion
22
+ //# sourceMappingURL=structures.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structures.d.mts","names":[],"sources":["../../../../../../../../packages/cache/src/structures/structures.ts"],"mappings":";;;;;;YAgBY;GACT,aAAa,UAAU,uBAAuB;;EAE/C,MAAM,iBAAiB;;;;;YAMb;EACV,MAAM,aAAa,SAAS,eAAe;EAC3C,OAAO,aAAa,SAAS,gBAAgB;EAC7C,eAAe;EACf,UAAU,aAAa,UAAU,mBAAmB"}
@@ -0,0 +1,44 @@
1
+ import { CacheUnsupportedError } from "../types.mjs";
2
+ import { parseTtl } from "../utils.mjs";
3
+ import { BloomFilter } from "./bloom-filter.mjs";
4
+ import { CuckooFilter } from "./cuckoo-filter.mjs";
5
+ import { FrequencyTracker } from "./frequency-tracker.mjs";
6
+ import { UniqueCounter, UniqueCounterGroup } from "./unique-counter.mjs";
7
+ import { isStructuresCapable } from "./types.mjs";
8
+
9
+ //#region ../../packages/cache/src/structures/structures.ts
10
+ /**
11
+ * Resolve the backend of a driver, or throw {@link CacheUnsupportedError} when
12
+ * the driver does not opt in.
13
+ */
14
+ function structuresBackendOf(driver) {
15
+ if (!isStructuresCapable(driver)) throw new CacheUnsupportedError(`'${driver.name}' driver does not support cache.structures. Use the 'redis' driver or a memory driver ('memory', 'memoryExtended', 'lru').`);
16
+ return driver.structuresBackend();
17
+ }
18
+ function ttlSeconds(options) {
19
+ if (options?.ttl === void 0) return;
20
+ const seconds = parseTtl(options.ttl);
21
+ return seconds > 0 && Number.isFinite(seconds) ? seconds : void 0;
22
+ }
23
+ /**
24
+ * Build the `cache.structures` namespace. `getBackend` is called on every
25
+ * operation, so structures always follow the manager's current driver.
26
+ */
27
+ function createStructures(getBackend) {
28
+ const context = (options) => ({
29
+ backend: getBackend,
30
+ ttl: ttlSeconds(options)
31
+ });
32
+ const uniqueCounter = ((key, options) => new UniqueCounter(`structures.unique.${key}`, context(options)));
33
+ uniqueCounter.merge = (keys) => new UniqueCounterGroup(keys.map((key) => `structures.unique.${key}`), context());
34
+ return {
35
+ bloom: (key, options) => new BloomFilter(`structures.bloom.${key}`, options, context(options)),
36
+ cuckoo: (key, options) => new CuckooFilter(`structures.cuckoo.${key}`, options, context(options)),
37
+ uniqueCounter,
38
+ frequency: (key, options = {}) => new FrequencyTracker(`structures.frequency.${key}`, options, context(options))
39
+ };
40
+ }
41
+
42
+ //#endregion
43
+ export { createStructures, structuresBackendOf };
44
+ //# sourceMappingURL=structures.mjs.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,108 @@
1
+ import { CacheTtl } from "../types.mjs";
2
+ //#region ../../packages/cache/src/structures/types.d.ts
3
+ /**
4
+ * Options shared by every structure.
5
+ */
6
+ export type StructureOptions = {
7
+ /**
8
+ * Expiry of the whole structure, set when it is first written and never
9
+ * pushed back by later writes. A number is seconds; a string is a duration
10
+ * such as `"40d"`. Omit to keep the structure until it is removed.
11
+ */
12
+ ttl?: CacheTtl;
13
+ };
14
+ export type BloomOptions = StructureOptions & {
15
+ /** How many distinct items you expect to add. Sizes the filter. */
16
+ expectedItems: number;
17
+ /** Target false-positive rate between 0 and 1. Default `0.01`. */
18
+ errorRate?: number;
19
+ };
20
+ export type CuckooOptions = StructureOptions & {
21
+ /** How many distinct items you expect to hold at once. Sizes the filter. */
22
+ expectedItems: number;
23
+ /** Target false-positive rate between 0 and 1. Default `0.01`. */
24
+ errorRate?: number;
25
+ };
26
+ export type UniqueCounterOptions = StructureOptions;
27
+ export type FrequencyOptions = StructureOptions & {
28
+ /** Counters per row. Wider means less over-counting. Default `2000`. */
29
+ width?: number;
30
+ /** Number of rows (independent hashes). Default `5`. */
31
+ depth?: number;
32
+ /** How many of the most frequent values to remember for `top()`. Default `10`. */
33
+ topK?: number;
34
+ };
35
+ export type FrequencyEntry = {
36
+ value: string;
37
+ count: number;
38
+ };
39
+ /** Write options a structure hands to the backend (ttl in whole seconds). */
40
+ export type StructureWrite = {
41
+ ttl?: number;
42
+ };
43
+ /** A member with its score, as kept by the ranked primitive. */
44
+ export type RankedEntry = {
45
+ member: string;
46
+ score: number;
47
+ };
48
+ /**
49
+ * Native (module) operations. The Redis driver offers them when the server
50
+ * runs RedisBloom, and the structures prefer them over the portable path.
51
+ */
52
+ export interface NativeStructures {
53
+ bloomAdd(key: string, item: string, options: {
54
+ capacity: number;
55
+ errorRate: number;
56
+ } & StructureWrite): Promise<boolean>;
57
+ bloomExists(key: string, item: string): Promise<boolean>;
58
+ cuckooAdd(key: string, item: string, options: {
59
+ capacity: number;
60
+ } & StructureWrite): Promise<boolean>;
61
+ cuckooRemove(key: string, item: string): Promise<boolean>;
62
+ cuckooExists(key: string, item: string): Promise<boolean>;
63
+ frequencyAdd(key: string, item: string, count: number, options: {
64
+ width: number;
65
+ depth: number;
66
+ topK: number;
67
+ } & StructureWrite): Promise<void>;
68
+ frequencyEstimate(key: string, item: string): Promise<number>;
69
+ frequencyTop(key: string, count: number): Promise<RankedEntry[]>;
70
+ }
71
+ /**
72
+ * The storage primitives behind `cache.structures`. A driver opts in by
73
+ * implementing {@link StructuresCapable}; custom drivers that do not are
74
+ * reported as unsupported.
75
+ *
76
+ * Keys are logical (the driver applies its own prefix). Every primitive that
77
+ * writes takes a ttl in seconds that is applied only when the key is created.
78
+ */
79
+ export interface CacheStructuresBackend {
80
+ /** Set bits, returning each bit's previous value. */
81
+ bitSet(key: string, offsets: number[], options?: StructureWrite): Promise<boolean[]>;
82
+ bitGet(key: string, offsets: number[]): Promise<boolean[]>;
83
+ /**
84
+ * Add `delta` to every cell, returning the new values. Cells never go below
85
+ * zero on backends that can clamp.
86
+ */
87
+ gridAdd(key: string, cells: number[], delta: number, options?: StructureWrite): Promise<number[]>;
88
+ gridGet(key: string, cells: number[]): Promise<number[]>;
89
+ /** Add to a distinct counter. Returns true when the estimate may have changed. */
90
+ uniqueAdd(key: string, member: string, options?: StructureWrite): Promise<boolean>;
91
+ /** Distinct count of the union of one or more counters. */
92
+ uniqueCount(keys: string[]): Promise<number>;
93
+ /** Set a member's score, keeping only the `capacity` highest-scored members. */
94
+ rankedSet(key: string, member: string, score: number, capacity: number, options?: StructureWrite): Promise<void>;
95
+ /** The highest-scored members, best first. */
96
+ rankedTop(key: string, count: number): Promise<RankedEntry[]>;
97
+ /** Native module operations, or `null` when unavailable. Resolved once per backend. */
98
+ native?(): Promise<NativeStructures | null>;
99
+ }
100
+ /**
101
+ * Optional capability a cache driver implements to support `cache.structures`.
102
+ */
103
+ export interface StructuresCapable {
104
+ structuresBackend(): CacheStructuresBackend;
105
+ }
106
+ export declare function isStructuresCapable(driver: unknown): driver is StructuresCapable;
107
+ //#endregion
108
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/cache/src/structures/types.ts"],"mappings":";;;;;YAKY;;;;;;EAMV,MAAM;;YAGI,eAAe;;EAEzB;;EAEA;;YAGU,gBAAgB;;EAE1B;;EAEA;;YAGU,uBAAuB;YAEvB,mBAAmB;;EAE7B;;EAEA;;EAEA;;YAGU;EAAmB;EAAe;;;YAGlC;EAAmB;;;YAGnB;EAAgB;EAAgB;;;;;;iBAM3B;EACf,SACE,aACA,cACA;IAAW;IAAkB;MAAsB,iBAClD;EACH,YAAY,aAAa,eAAe;EACxC,UACE,aACA,cACA;IAAW;MAAqB,iBAC/B;EACH,aAAa,aAAa,eAAe;EACzC,aAAa,aAAa,eAAe;EACzC,aACE,aACA,cACA,eACA;IAAW;IAAe;IAAe;MAAiB,iBACzD;EACH,kBAAkB,aAAa,eAAe;EAC9C,aAAa,aAAa,gBAAgB,QAAQ;;;;;;;;;;iBAWnC;;EAEf,OAAO,aAAa,mBAAmB,UAAU,iBAAiB;EAClE,OAAO,aAAa,oBAAoB;;;;;EAKxC,QAAQ,aAAa,iBAAiB,eAAe,UAAU,iBAAiB;EAChF,QAAQ,aAAa,kBAAkB;;EAEvC,UAAU,aAAa,gBAAgB,UAAU,iBAAiB;;EAElE,YAAY,iBAAiB;;EAE7B,UACE,aACA,gBACA,eACA,kBACA,UAAU,iBACT;;EAEH,UAAU,aAAa,gBAAgB,QAAQ;;EAE/C,WAAW,QAAQ;;;;;iBAMJ;EACf,qBAAqB;;wBAGP,oBAAoB,kBAAkB,UAAU"}
@@ -0,0 +1,8 @@
1
+ //#region ../../packages/cache/src/structures/types.ts
2
+ function isStructuresCapable(driver) {
3
+ return typeof driver === "object" && driver !== null && typeof driver.structuresBackend === "function";
4
+ }
5
+
6
+ //#endregion
7
+ export { isStructuresCapable };
8
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,33 @@
1
+ import { StructureContext } from "./bloom-filter.mjs";
2
+ //#region ../../packages/cache/src/structures/unique-counter.d.ts
3
+ /**
4
+ * Approximate count of distinct values (HyperLogLog): about 12 KB per counter,
5
+ * standard error 0.81%. Cannot tell whether one specific value was counted.
6
+ */
7
+ export declare class UniqueCounter {
8
+ protected readonly key: string;
9
+ protected readonly context: StructureContext;
10
+ constructor(key: string, context: StructureContext);
11
+ /**
12
+ * Count a value. Adding the same value again changes nothing.
13
+ */
14
+ add(...values: Array<string | number>): Promise<void>;
15
+ /**
16
+ * Approximate number of distinct values counted so far.
17
+ */
18
+ count(): Promise<number>;
19
+ }
20
+ /**
21
+ * The union of several unique counters, counted without changing any of them.
22
+ */
23
+ export declare class UniqueCounterGroup {
24
+ protected readonly keys: string[];
25
+ protected readonly context: StructureContext;
26
+ constructor(keys: string[], context: StructureContext);
27
+ /**
28
+ * Approximate number of distinct values across every counter in the group.
29
+ */
30
+ count(): Promise<number>;
31
+ }
32
+ //#endregion
33
+ //# sourceMappingURL=unique-counter.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unique-counter.d.mts","names":[],"sources":["../../../../../../../../packages/cache/src/structures/unique-counter.ts"],"mappings":";;;;;;qBAMa;qBAEU;qBACA,SAAS;EAF9B,YACqB,aACA,SAAS;;;;EAMjB,OAAO,QAAQ,yBAAyB;;;;EAWxC,SAAS;;;;;qBAQX;qBAEU;qBACA,SAAS;EAF9B,YACqB,gBACA,SAAS;;;;EAMjB,SAAS"}
@@ -0,0 +1,43 @@
1
+ //#region ../../packages/cache/src/structures/unique-counter.ts
2
+ /**
3
+ * Approximate count of distinct values (HyperLogLog): about 12 KB per counter,
4
+ * standard error 0.81%. Cannot tell whether one specific value was counted.
5
+ */
6
+ var UniqueCounter = class {
7
+ constructor(key, context) {
8
+ this.key = key;
9
+ this.context = context;
10
+ }
11
+ /**
12
+ * Count a value. Adding the same value again changes nothing.
13
+ */
14
+ async add(...values) {
15
+ const backend = this.context.backend();
16
+ for (const value of values) await backend.uniqueAdd(this.key, String(value), { ttl: this.context.ttl });
17
+ }
18
+ /**
19
+ * Approximate number of distinct values counted so far.
20
+ */
21
+ async count() {
22
+ return this.context.backend().uniqueCount([this.key]);
23
+ }
24
+ };
25
+ /**
26
+ * The union of several unique counters, counted without changing any of them.
27
+ */
28
+ var UniqueCounterGroup = class {
29
+ constructor(keys, context) {
30
+ this.keys = keys;
31
+ this.context = context;
32
+ }
33
+ /**
34
+ * Approximate number of distinct values across every counter in the group.
35
+ */
36
+ async count() {
37
+ return this.context.backend().uniqueCount(this.keys);
38
+ }
39
+ };
40
+
41
+ //#endregion
42
+ export { UniqueCounter, UniqueCounterGroup };
43
+ //# sourceMappingURL=unique-counter.mjs.map
@@ -0,0 +1 @@
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"}
@@ -113,6 +113,10 @@ export declare class TaggedCache implements TaggedCacheDriver {
113
113
  increment(key: CacheKey, value?: number, options?: {
114
114
  ttl?: CacheTtl;
115
115
  }): Promise<number>;
116
+ /**
117
+ * {@inheritdoc}
118
+ */
119
+ extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;
116
120
  /**
117
121
  * {@inheritdoc}
118
122
  */
@@ -1 +1 @@
1
- {"version":3,"file":"tagged-cache.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/tagged-cache.ts"],"mappings":";;;;;;qBAYa,uBAAuB;;;;YAIxB;;;;YAKA,QAAQ;;;;EAKlB,YAAmB,gBAAgB,Q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