@warlock.js/cache 5.51.0 → 5.53.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.
- package/CHANGELOG.md +36 -0
- package/cjs/index.cjs +528 -122
- package/cjs/index.cjs.map +1 -1
- package/esm/cache-manager.mjs.map +1 -1
- package/esm/cached/auto-key.d.mts +3 -1
- package/esm/cached/auto-key.d.mts.map +1 -1
- package/esm/cached/auto-key.mjs +9 -4
- package/esm/cached/auto-key.mjs.map +1 -1
- package/esm/cached/cached.mjs.map +1 -1
- package/esm/cached/normalize-args.mjs.map +1 -1
- package/esm/drivers/base-cache-driver.d.mts +40 -3
- package/esm/drivers/base-cache-driver.d.mts.map +1 -1
- package/esm/drivers/base-cache-driver.mjs +57 -7
- package/esm/drivers/base-cache-driver.mjs.map +1 -1
- package/esm/drivers/clone-value.mjs +17 -0
- package/esm/drivers/clone-value.mjs.map +1 -0
- package/esm/drivers/file-cache-driver.d.mts +40 -2
- package/esm/drivers/file-cache-driver.d.mts.map +1 -1
- package/esm/drivers/file-cache-driver.mjs +142 -18
- package/esm/drivers/file-cache-driver.mjs.map +1 -1
- package/esm/drivers/in-memory-tag-index.d.mts +5 -0
- package/esm/drivers/in-memory-tag-index.d.mts.map +1 -1
- package/esm/drivers/in-memory-tag-index.mjs +17 -0
- package/esm/drivers/in-memory-tag-index.mjs.map +1 -1
- package/esm/drivers/lru-memory-cache-driver.d.mts +18 -1
- package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
- package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
- package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
- package/esm/drivers/memory-cache-driver.d.mts +16 -1
- package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
- package/esm/drivers/memory-cache-driver.mjs +34 -5
- package/esm/drivers/memory-cache-driver.mjs.map +1 -1
- package/esm/drivers/memory-extended-cache-driver.mjs.map +1 -1
- package/esm/drivers/mock-cache-driver.mjs.map +1 -1
- package/esm/drivers/null-cache-driver.d.mts.map +1 -1
- package/esm/drivers/null-cache-driver.mjs +22 -12
- package/esm/drivers/null-cache-driver.mjs.map +1 -1
- package/esm/drivers/pg-cache-driver.d.mts +19 -0
- package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
- package/esm/drivers/pg-cache-driver.mjs +52 -26
- package/esm/drivers/pg-cache-driver.mjs.map +1 -1
- package/esm/drivers/redis-cache-driver.d.mts +29 -0
- package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
- package/esm/drivers/redis-cache-driver.mjs +70 -36
- package/esm/drivers/redis-cache-driver.mjs.map +1 -1
- package/esm/idempotent.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/esm/list/memory-cache-list.mjs.map +1 -1
- package/esm/metrics.mjs.map +1 -1
- package/esm/scoped-cache.mjs.map +1 -1
- package/esm/structures/bloom-filter.mjs.map +1 -1
- package/esm/structures/cuckoo-filter.mjs.map +1 -1
- package/esm/structures/frequency-tracker.mjs.map +1 -1
- package/esm/structures/hash.mjs.map +1 -1
- package/esm/structures/hyperloglog.mjs.map +1 -1
- package/esm/structures/memory-structures-backend.mjs.map +1 -1
- package/esm/structures/redis-structures-backend.mjs.map +1 -1
- package/esm/structures/sizing.mjs.map +1 -1
- package/esm/structures/structures.mjs.map +1 -1
- package/esm/structures/types.mjs.map +1 -1
- package/esm/structures/unique-counter.mjs.map +1 -1
- package/esm/tag-sample.mjs +16 -0
- package/esm/tag-sample.mjs.map +1 -0
- package/esm/tagged-cache.d.mts +15 -0
- package/esm/tagged-cache.d.mts.map +1 -1
- package/esm/tagged-cache.mjs +31 -10
- package/esm/tagged-cache.mjs.map +1 -1
- package/esm/tagged-scoped-cache.mjs.map +1 -1
- package/esm/types.d.mts +24 -5
- package/esm/types.d.mts.map +1 -1
- package/esm/types.mjs.map +1 -1
- package/esm/utils.d.mts +20 -1
- package/esm/utils.d.mts.map +1 -1
- package/esm/utils.mjs +42 -3
- package/esm/utils.mjs.map +1 -1
- package/llms-full.txt +9 -6
- package/llms.txt +1 -1
- package/package.json +3 -3
- package/skills/cache-basics/SKILL.md +1 -1
- package/skills/pick-cache-driver/SKILL.md +1 -1
- package/skills/use-cache-namespace/SKILL.md +1 -0
- package/skills/use-cache-tags/SKILL.md +1 -1
- package/skills/use-cache-utils/SKILL.md +4 -2
- package/skills/use-cached-hof/SKILL.md +1 -1
|
@@ -1 +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,K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AC3E,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"],"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,KA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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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sizing.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/sizing.ts"],"
|
|
1
|
+
{"version":3,"file":"sizing.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/sizing.ts"],"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"],"
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/types.ts"],"
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unique-counter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/unique-counter.ts"],"
|
|
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"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region ../../packages/cache/src/tag-sample.ts
|
|
2
|
+
/**
|
|
3
|
+
* Up to `count` members starting at a random offset (all of them when there
|
|
4
|
+
* are fewer), so repeated samples cover a large index over time.
|
|
5
|
+
*
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
function sampleMembers(members, count) {
|
|
9
|
+
if (members.length <= count) return [...members];
|
|
10
|
+
const start = Math.floor(Math.random() * members.length);
|
|
11
|
+
return Array.from({ length: count }, (_, index) => members[(start + index) % members.length]);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
export { sampleMembers };
|
|
16
|
+
//# sourceMappingURL=tag-sample.mjs.map
|
|
@@ -0,0 +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"}
|
package/esm/tagged-cache.d.mts
CHANGED
|
@@ -47,6 +47,21 @@ export declare class TaggedCache implements TaggedCacheDriver {
|
|
|
47
47
|
* to its live members without any write paying for a full scan.
|
|
48
48
|
*/
|
|
49
49
|
protected pruneTag(tagKey: string, justWritten: string): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Up to `count` random members of an index: the driver's `tagSample` when it
|
|
52
|
+
* has one, else a window of the full member list.
|
|
53
|
+
*/
|
|
54
|
+
protected sampleOf(tagKey: string, count: number): Promise<string[]>;
|
|
55
|
+
/**
|
|
56
|
+
* Whether an indexed key still has a live entry: the driver's `exists`
|
|
57
|
+
* (no value read, no hit/miss events) when it has one, else `has()`.
|
|
58
|
+
*/
|
|
59
|
+
protected memberExists(member: string): Promise<boolean>;
|
|
60
|
+
/**
|
|
61
|
+
* Remove entries by their indexed keys: the driver's batched `removeMany`
|
|
62
|
+
* when it has one, else `remove()` per key.
|
|
63
|
+
*/
|
|
64
|
+
protected removeEntries(keys: string[]): Promise<void>;
|
|
50
65
|
protected addToTag(tagKey: string, members: string[]): Promise<void>;
|
|
51
66
|
protected membersOf(tagKey: string): Promise<string[]>;
|
|
52
67
|
protected removeFromTag(tagKey: string, members: string[]): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tagged-cache.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/tagged-cache.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"tagged-cache.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/tagged-cache.ts"],"mappings":";;;;;;qBAaa,uBAAuB;;;;YAIxB;;;;YAKA,QAAQ;;;;EAKlB,YAAmB,gBAAgB,QAAQ;;;;YAQjC,OAAO;;;;YAOD,eAAe,KAAK,WAAW;;;;;;;;;;EAalC,qBAAqB,KAAK,WAAW;;;;;4BAexB;;;;;;;YAQV,SAAS,gBAAgB,sBAAsB;;;;;YAyB/C,SAAS,gBAAgB,gBAAgB;;;;;YAYzC,aAAa,iBAAiB;;;;;YAY9B,cAAc,iBAAiB;YAe/B,SAAS,gBAAgB,oBAAoB;YAa7C,UAAU,iBAAiB;YAQ3B,cAAc,gBAAgB,oBAAoB;YAoBlD,cAAc,iBAAiB;;;;;;;;;;;YAkBrC,WAAW,KAAK;;;;YAOV,iBAAiB,QAAQ;;;;EAe5B,IACX,KAAK,UACL,YACA,eAAe,WAAW,kBACzB;;;;EAWU,IAAI,KAAK,WAAW;;;;EAOpB,OAAO,KAAK,WAAW;;;;EAavB,cAAc;;;;YAmCX,eAAe,qBAAqB;;;;;EAUvC,SAAS;;;;EAOT,IAAI,KAAK,WAAW;;;;EAOpB,SAAS,KAAK,UAAU,aAAa,gBAAgB,eAAe;;;;EAgBpE,KAAK,KAAK,WAAW;;;;EAerB,QAAQ,KAAK,UAAU,aAAa;;;;EAOpC,UACX,KAAK,UACL,gBACA;IAAY,MAAM;MACjB;;;;EAaU,OAAO,KAAK,UAAU,KAAK,WAAW;;;;EAOtC,UAAU,KAAK,UAAU,iBAAoB"}
|
package/esm/tagged-cache.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseCacheKey } from "./utils.mjs";
|
|
2
|
+
import { sampleMembers } from "./tag-sample.mjs";
|
|
2
3
|
|
|
3
4
|
//#region ../../packages/cache/src/tagged-cache.ts
|
|
4
5
|
/**
|
|
@@ -52,15 +53,37 @@ var TaggedCache = class TaggedCache {
|
|
|
52
53
|
* to its live members without any write paying for a full scan.
|
|
53
54
|
*/
|
|
54
55
|
async pruneTag(tagKey, justWritten) {
|
|
55
|
-
const members = (await this.membersOf(tagKey)).filter((member) => member !== justWritten);
|
|
56
|
-
if (members.length === 0) return;
|
|
57
56
|
const limit = TaggedCache.PRUNE_CHECKS_PER_WRITE;
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
57
|
+
const window = (await this.sampleOf(tagKey, limit + 1)).filter((member) => member !== justWritten).slice(0, limit);
|
|
58
|
+
if (window.length === 0) return;
|
|
59
|
+
const present = await Promise.all(window.map((member) => this.memberExists(member)));
|
|
60
|
+
const missing = window.filter((_, index) => !present[index]);
|
|
62
61
|
if (missing.length > 0) await this.removeFromTag(tagKey, missing);
|
|
63
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Up to `count` random members of an index: the driver's `tagSample` when it
|
|
65
|
+
* has one, else a window of the full member list.
|
|
66
|
+
*/
|
|
67
|
+
async sampleOf(tagKey, count) {
|
|
68
|
+
if (typeof this.driver.tagSample === "function") return this.driver.tagSample(tagKey, count);
|
|
69
|
+
return sampleMembers(await this.membersOf(tagKey), count);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Whether an indexed key still has a live entry: the driver's `exists`
|
|
73
|
+
* (no value read, no hit/miss events) when it has one, else `has()`.
|
|
74
|
+
*/
|
|
75
|
+
async memberExists(member) {
|
|
76
|
+
if (typeof this.driver.exists === "function") return this.driver.exists(member);
|
|
77
|
+
return this.driver.has(member);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Remove entries by their indexed keys: the driver's batched `removeMany`
|
|
81
|
+
* when it has one, else `remove()` per key.
|
|
82
|
+
*/
|
|
83
|
+
async removeEntries(keys) {
|
|
84
|
+
if (typeof this.driver.removeMany === "function") return this.driver.removeMany(keys);
|
|
85
|
+
for (const key of keys) await this.driver.remove(key);
|
|
86
|
+
}
|
|
64
87
|
async addToTag(tagKey, members) {
|
|
65
88
|
if (typeof this.driver.tagAdd === "function") return this.driver.tagAdd(tagKey, members);
|
|
66
89
|
const current = await this.legacyMembers(tagKey);
|
|
@@ -136,10 +159,8 @@ var TaggedCache = class TaggedCache {
|
|
|
136
159
|
for (const tag of this.cacheTags) {
|
|
137
160
|
const tagKey = this.tagKey(tag);
|
|
138
161
|
const members = await this.membersOf(tagKey);
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
removed.add(member);
|
|
142
|
-
}
|
|
162
|
+
await this.removeEntries(members);
|
|
163
|
+
for (const member of members) removed.add(member);
|
|
143
164
|
await this.removeFromTag(tagKey, members);
|
|
144
165
|
}
|
|
145
166
|
await this.driver.emitTagsInvalidated?.({
|
package/esm/tagged-cache.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 { 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 members = (await this.membersOf(tagKey)).filter((member) => member !== justWritten);\n\n if (members.length === 0) {\n return;\n }\n\n const limit = TaggedCache.PRUNE_CHECKS_PER_WRITE;\n const start = members.length > limit ? Math.floor(Math.random() * members.length) : 0;\n const window = Array.from(\n { length: Math.min(limit, members.length) },\n (_, index) => members[(start + index) % members.length]!,\n );\n\n const missing: string[] = [];\n\n for (const member of window) {\n if (!(await this.driver.has(member))) {\n missing.push(member);\n }\n }\n\n if (missing.length > 0) {\n await this.removeFromTag(tagKey, missing);\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 for (const member of members) {\n await this.driver.remove(member);\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":";;;;;;;AAYA,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,WAAW,MAAM,KAAK,UAAU,MAAM,EAAC,CAAE,QAAQ,WAAW,WAAW,WAAW;EAExF,IAAI,QAAQ,WAAW,GACrB;EAGF,MAAM,QAAQ,YAAY;EAC1B,MAAM,QAAQ,QAAQ,SAAS,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAI,QAAQ,MAAM,IAAI;EACpF,MAAM,SAAS,MAAM,KACnB,EAAE,QAAQ,KAAK,IAAI,OAAO,QAAQ,MAAM,EAAE,IACzC,GAAG,UAAU,SAAS,QAAQ,SAAS,QAAQ,OAClD;EAEA,MAAM,UAAoB,CAAC;EAE3B,KAAK,MAAM,UAAU,QACnB,IAAI,CAAE,MAA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UAAU,MACZ,OAAO;EAGT,MAAM,SAAS,MAAM,SAAS;EAC9B,MAAM,KAAK,IAAI,KAAK,QAAQ,GAAG;EAE/B,OAAO;CACT;;;;CAKA,MAAa,KAAK,KAAoC;EAGpD,MAAM,QAAQ,MAAM,KAAK,OAAO,KAAK,GAAG;EAExC,IAAI,UAAU,MACZ,MAAM,KAAK,eAAe,KAAK,WAAW,GAAG,CAAC;EAGhD,OAAO;CACT;;;;CAKA,MAAa,QAAQ,KAAe,OAA0B;EAC5D,OAAO,KAAK,IAAI,KAAK,OAAO,QAAQ;CACtC;;;;CAKA,MAAa,UACX,KACA,QAAgB,GAChB,SACiB;EAGjB,MAAM,WAAW,MAAM,KAAK,OAAO,UAAU,KAAK,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tagged-scoped-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tagged-scoped-cache.ts"],"
|
|
1
|
+
{"version":3,"file":"tagged-scoped-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/tagged-scoped-cache.ts"],"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;;;;C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AAO,KAAK,MAAM,SAAY,KAAK,SAAS,QAAQ;CACtD;;;;;CAMA,AAAO,UAAU,KAAe,OAAgB,SAA+C;EAC7F,OAAO,KAAK,MAAM,UAAU,KAAK,OAAO,OAAO;CACjD;;;;CAKA,AAAO,OAAO,KAAe,KAAiC;EAC5D,OAAO,KAAK,MAAM,OAAO,KAAK,GAAG;CACnC;;;;CAKA,AAAO,UAAU,KAAe,OAAiC;EAC/D,OAAO,KAAK,MAAM,UAAU,KAAK,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"}
|
package/esm/types.d.mts
CHANGED
|
@@ -467,10 +467,10 @@ export type MemoryCacheOptions = {
|
|
|
467
467
|
*/
|
|
468
468
|
ttl?: CacheTtl;
|
|
469
469
|
/**
|
|
470
|
-
* Maximum number of
|
|
471
|
-
*
|
|
470
|
+
* Maximum number of entries. When exceeded, the least recently used
|
|
471
|
+
* entries are evicted. `Infinity` (or `0`) removes the limit.
|
|
472
472
|
*
|
|
473
|
-
* @default
|
|
473
|
+
* @default 10000
|
|
474
474
|
*/
|
|
475
475
|
maxSize?: number;
|
|
476
476
|
};
|
|
@@ -939,6 +939,22 @@ export interface CacheDriver<ClientType, Options> {
|
|
|
939
939
|
* Tag-index primitive: drop the whole index stored under `tagKey`.
|
|
940
940
|
*/
|
|
941
941
|
tagDelete?(tagKey: CacheKey): Promise<void>;
|
|
942
|
+
/**
|
|
943
|
+
* Tag-index primitive: up to `count` members of `tagKey` picked at random
|
|
944
|
+
* (every member when the index is smaller). Lets a tagged write check a
|
|
945
|
+
* sample of the index without reading all of it.
|
|
946
|
+
*/
|
|
947
|
+
tagSample?(tagKey: CacheKey, count: number): Promise<string[]>;
|
|
948
|
+
/**
|
|
949
|
+
* Whether a live (unexpired) entry exists for `key`, without reading its
|
|
950
|
+
* value, emitting `hit`/`miss` or logging. Used by tag-index pruning.
|
|
951
|
+
*/
|
|
952
|
+
exists?(key: CacheKey): Promise<boolean>;
|
|
953
|
+
/**
|
|
954
|
+
* Remove several keys in as few round trips as the backend allows. Each key
|
|
955
|
+
* emits `removed`, as `remove()` does. Used by tag invalidation.
|
|
956
|
+
*/
|
|
957
|
+
removeMany?(keys: CacheKey[]): Promise<void>;
|
|
942
958
|
/**
|
|
943
959
|
* Similarity retrieval. Returns the nearest stored entries to `vector` by
|
|
944
960
|
* cosine similarity, ordered by descending score.
|
|
@@ -1119,9 +1135,12 @@ export type CacheConfigurations<T extends string | undefined = undefined, Driver
|
|
|
1119
1135
|
*/
|
|
1120
1136
|
default?: DriverName;
|
|
1121
1137
|
/**
|
|
1122
|
-
*
|
|
1138
|
+
* Log every cache operation (fetching, caching, removing…) at `info` /
|
|
1139
|
+
* `success`. Off by default: the lines cost CPU on every cache call and
|
|
1140
|
+
* put cache keys in the logs. Errors and connection failures are logged
|
|
1141
|
+
* either way.
|
|
1123
1142
|
*
|
|
1124
|
-
* @default
|
|
1143
|
+
* @default false
|
|
1125
1144
|
*/
|
|
1126
1145
|
logging?: boolean;
|
|
1127
1146
|
/**
|
package/esm/types.d.mts.map
CHANGED
|
@@ -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,uC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|
|
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 * 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 * 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 * 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\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 items in cache\n * When exceeded, least recently used items will be evicted\n *\n * @default undefined (no limit)\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 * 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 * 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 * Determine whether to log or not\n *\n * @default true\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"}
|
|
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"}
|
package/esm/utils.d.mts
CHANGED
|
@@ -1,7 +1,26 @@
|
|
|
1
1
|
import { CacheKey, CacheSetOptions, CacheTtl, RememberOptions } from "./types.mjs";
|
|
2
2
|
//#region ../../packages/cache/src/utils.d.ts
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Escape a value for use as ONE segment of a cache key or namespace: the
|
|
5
|
+
* characters the key format treats as separators or strips (`.` `,` `:`
|
|
6
|
+
* `{` `}` `"` `[` `]`, and `%` itself) are percent-encoded, so the value can
|
|
7
|
+
* never reach into another key or namespace. Values without those
|
|
8
|
+
* characters are returned unchanged.
|
|
9
|
+
*
|
|
10
|
+
* Use it for request-derived text (slugs, search terms, ids from a client).
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);
|
|
14
|
+
* // slug "acme.billing" → namespace "tenant.acme%2Ebilling", never inside "tenant.acme"
|
|
15
|
+
*/
|
|
16
|
+
export declare function escapeCacheKeySegment(value: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Make a proper key for the cache.
|
|
19
|
+
*
|
|
20
|
+
* String keys are used as they are (`:` and `,` become `.`; `{}"[]` are
|
|
21
|
+
* removed). In an object key, separator characters inside the object's keys
|
|
22
|
+
* and string values are escaped first (see {@link escapeCacheKeySegment}),
|
|
23
|
+
* so `{ a: "b.c" }` and `{ a: "b", c: "" }` are different keys.
|
|
5
24
|
*/
|
|
6
25
|
export declare function parseCacheKey(key: CacheKey, options?: {
|
|
7
26
|
globalPrefix?: string | (() => string);
|
package/esm/utils.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"mappings":"
|
|
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"}
|
package/esm/utils.mjs
CHANGED
|
@@ -4,10 +4,49 @@ import ms from "ms";
|
|
|
4
4
|
|
|
5
5
|
//#region ../../packages/cache/src/utils.ts
|
|
6
6
|
/**
|
|
7
|
-
*
|
|
7
|
+
* Characters that `parseCacheKey` strips or turns into the `.` separator.
|
|
8
|
+
* Inside a value they would make two different keys equal.
|
|
9
|
+
*/
|
|
10
|
+
const KEY_SEPARATOR_CHARACTERS = /[%.,:{}"[\]]/g;
|
|
11
|
+
/**
|
|
12
|
+
* Escape a value for use as ONE segment of a cache key or namespace: the
|
|
13
|
+
* characters the key format treats as separators or strips (`.` `,` `:`
|
|
14
|
+
* `{` `}` `"` `[` `]`, and `%` itself) are percent-encoded, so the value can
|
|
15
|
+
* never reach into another key or namespace. Values without those
|
|
16
|
+
* characters are returned unchanged.
|
|
17
|
+
*
|
|
18
|
+
* Use it for request-derived text (slugs, search terms, ids from a client).
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);
|
|
22
|
+
* // slug "acme.billing" → namespace "tenant.acme%2Ebilling", never inside "tenant.acme"
|
|
23
|
+
*/
|
|
24
|
+
function escapeCacheKeySegment(value) {
|
|
25
|
+
return value.replace(KEY_SEPARATOR_CHARACTERS, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Escape every string (and object key) inside an object key, so a value that
|
|
29
|
+
* contains a separator cannot be read as two segments. Values without
|
|
30
|
+
* separator characters keep their exact previous encoding.
|
|
31
|
+
*/
|
|
32
|
+
function escapeKeyObject(value) {
|
|
33
|
+
if (typeof value === "string") return escapeCacheKeySegment(value);
|
|
34
|
+
if (Array.isArray(value)) return value.map(escapeKeyObject);
|
|
35
|
+
if (value === null || typeof value !== "object" || value instanceof Date) return value;
|
|
36
|
+
const escaped = Object.create(null);
|
|
37
|
+
for (const [name, child] of Object.entries(value)) escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);
|
|
38
|
+
return escaped;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Make a proper key for the cache.
|
|
42
|
+
*
|
|
43
|
+
* String keys are used as they are (`:` and `,` become `.`; `{}"[]` are
|
|
44
|
+
* removed). In an object key, separator characters inside the object's keys
|
|
45
|
+
* and string values are escaped first (see {@link escapeCacheKeySegment}),
|
|
46
|
+
* so `{ a: "b.c" }` and `{ a: "b", c: "" }` are different keys.
|
|
8
47
|
*/
|
|
9
48
|
function parseCacheKey(key, options = {}) {
|
|
10
|
-
if (typeof key === "object") key = JSON.stringify(key);
|
|
49
|
+
if (typeof key === "object") key = JSON.stringify(escapeKeyObject(key));
|
|
11
50
|
key = key.replace(/[{}"[\]]/g, "").replaceAll(/[:,]/g, ".");
|
|
12
51
|
const cachePrefix = typeof options.globalPrefix === "function" ? options.globalPrefix() : options.globalPrefix;
|
|
13
52
|
return rtrim(String(cachePrefix ? rtrim(cachePrefix, ".") + "." + key : key), ".");
|
|
@@ -259,5 +298,5 @@ let CACHE_FOR = /* @__PURE__ */ function(CACHE_FOR) {
|
|
|
259
298
|
}({});
|
|
260
299
|
|
|
261
300
|
//#endregion
|
|
262
|
-
export { CACHE_FOR, cosineSimilarity, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
|
|
301
|
+
export { CACHE_FOR, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
|
|
263
302
|
//# sourceMappingURL=utils.mjs.map
|