@open-mercato/cache-provider-jsonfile 0.0.0-stage → 0.11.1-develop.8687.1.adb16f62b3

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.
@@ -0,0 +1,2 @@
1
+ [build:cache-provider-jsonfile] found 1 entry points
2
+ [build:cache-provider-jsonfile] built successfully
package/build.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import { dirname } from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { buildPackage } from '../../scripts/build-package.mjs'
4
+
5
+ const packageDir = dirname(fileURLToPath(import.meta.url))
6
+
7
+ await buildPackage(packageDir, {
8
+ name: 'cache-provider-jsonfile',
9
+ entryPoints: 'src/**/*.ts',
10
+ })
package/dist/index.js ADDED
@@ -0,0 +1,187 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { DEFAULT_JSON_FILE_CACHE_PATH } from "@open-mercato/cache-provider-kit/defaults";
4
+ import { matchCacheKeyPattern } from "@open-mercato/cache-provider-kit/patterns";
5
+ function createJsonFileStrategy(filePath, options) {
6
+ const defaultTtl = options?.defaultTtl;
7
+ const cacheFile = filePath || process.env.CACHE_JSON_FILE_PATH || DEFAULT_JSON_FILE_CACHE_PATH;
8
+ const dir = path.dirname(cacheFile);
9
+ function ensureDir() {
10
+ if (!fs.existsSync(dir)) {
11
+ fs.mkdirSync(dir, { recursive: true });
12
+ }
13
+ }
14
+ function readData() {
15
+ ensureDir();
16
+ if (!fs.existsSync(cacheFile)) {
17
+ return { entries: {}, tagIndex: {} };
18
+ }
19
+ try {
20
+ const content = fs.readFileSync(cacheFile, "utf8");
21
+ return JSON.parse(content);
22
+ } catch {
23
+ return { entries: {}, tagIndex: {} };
24
+ }
25
+ }
26
+ function writeData(data) {
27
+ ensureDir();
28
+ fs.writeFileSync(cacheFile, JSON.stringify(data, null, 2), "utf8");
29
+ }
30
+ function isExpired(entry) {
31
+ if (entry.expiresAt === null) return false;
32
+ return Date.now() > entry.expiresAt;
33
+ }
34
+ function addToTagIndex(data, key, tags) {
35
+ for (const tag of tags) {
36
+ if (!data.tagIndex[tag]) {
37
+ data.tagIndex[tag] = [];
38
+ }
39
+ if (!data.tagIndex[tag].includes(key)) {
40
+ data.tagIndex[tag].push(key);
41
+ }
42
+ }
43
+ }
44
+ function removeFromTagIndex(data, key, tags) {
45
+ for (const tag of tags) {
46
+ if (data.tagIndex[tag]) {
47
+ data.tagIndex[tag] = data.tagIndex[tag].filter((k) => k !== key);
48
+ if (data.tagIndex[tag].length === 0) {
49
+ delete data.tagIndex[tag];
50
+ }
51
+ }
52
+ }
53
+ }
54
+ const get = async (key, options2) => {
55
+ const data = readData();
56
+ const entry = data.entries[key];
57
+ if (!entry) return null;
58
+ if (isExpired(entry)) {
59
+ if (options2?.returnExpired) {
60
+ return entry.value;
61
+ }
62
+ removeFromTagIndex(data, key, entry.tags);
63
+ delete data.entries[key];
64
+ writeData(data);
65
+ return null;
66
+ }
67
+ return entry.value;
68
+ };
69
+ const set = async (key, value, options2) => {
70
+ const data = readData();
71
+ const oldEntry = data.entries[key];
72
+ if (oldEntry) {
73
+ removeFromTagIndex(data, key, oldEntry.tags);
74
+ }
75
+ const ttl = options2?.ttl ?? defaultTtl;
76
+ const tags = options2?.tags || [];
77
+ const expiresAt = ttl ? Date.now() + ttl : null;
78
+ const entry = {
79
+ key,
80
+ value,
81
+ tags,
82
+ expiresAt,
83
+ createdAt: Date.now()
84
+ };
85
+ data.entries[key] = entry;
86
+ addToTagIndex(data, key, tags);
87
+ writeData(data);
88
+ };
89
+ const has = async (key) => {
90
+ const data = readData();
91
+ const entry = data.entries[key];
92
+ if (!entry) return false;
93
+ if (isExpired(entry)) {
94
+ removeFromTagIndex(data, key, entry.tags);
95
+ delete data.entries[key];
96
+ writeData(data);
97
+ return false;
98
+ }
99
+ return true;
100
+ };
101
+ const deleteKey = async (key) => {
102
+ const data = readData();
103
+ const entry = data.entries[key];
104
+ if (!entry) return false;
105
+ removeFromTagIndex(data, key, entry.tags);
106
+ delete data.entries[key];
107
+ writeData(data);
108
+ return true;
109
+ };
110
+ const deleteByTags = async (tags) => {
111
+ const data = readData();
112
+ const keysToDelete = /* @__PURE__ */ new Set();
113
+ for (const tag of tags) {
114
+ const keys2 = data.tagIndex[tag] || [];
115
+ for (const key of keys2) {
116
+ keysToDelete.add(key);
117
+ }
118
+ }
119
+ for (const key of keysToDelete) {
120
+ const entry = data.entries[key];
121
+ if (entry) {
122
+ removeFromTagIndex(data, key, entry.tags);
123
+ delete data.entries[key];
124
+ }
125
+ }
126
+ writeData(data);
127
+ return keysToDelete.size;
128
+ };
129
+ const clear = async () => {
130
+ const data = readData();
131
+ const size = Object.keys(data.entries).length;
132
+ writeData({ entries: {}, tagIndex: {} });
133
+ return size;
134
+ };
135
+ const keys = async (pattern) => {
136
+ const data = readData();
137
+ const allKeys = Object.keys(data.entries);
138
+ if (!pattern) return allKeys;
139
+ return allKeys.filter((key) => matchCacheKeyPattern(key, pattern));
140
+ };
141
+ const stats = async () => {
142
+ const data = readData();
143
+ const allEntries = Object.values(data.entries);
144
+ let expired = 0;
145
+ for (const entry of allEntries) {
146
+ if (isExpired(entry)) {
147
+ expired++;
148
+ }
149
+ }
150
+ return { size: allEntries.length, expired };
151
+ };
152
+ const cleanup = async () => {
153
+ const data = readData();
154
+ let removed = 0;
155
+ const keysToRemove = [];
156
+ for (const [key, entry] of Object.entries(data.entries)) {
157
+ if (isExpired(entry)) {
158
+ keysToRemove.push(key);
159
+ }
160
+ }
161
+ for (const key of keysToRemove) {
162
+ const entry = data.entries[key];
163
+ removeFromTagIndex(data, key, entry.tags);
164
+ delete data.entries[key];
165
+ removed++;
166
+ }
167
+ if (removed > 0) {
168
+ writeData(data);
169
+ }
170
+ return removed;
171
+ };
172
+ return {
173
+ get,
174
+ set,
175
+ has,
176
+ delete: deleteKey,
177
+ deleteByTags,
178
+ clear,
179
+ keys,
180
+ stats,
181
+ cleanup
182
+ };
183
+ }
184
+ export {
185
+ createJsonFileStrategy
186
+ };
187
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["import type { CacheStrategy, CacheEntry, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { DEFAULT_JSON_FILE_CACHE_PATH } from '@open-mercato/cache-provider-kit/defaults'\nimport { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'\n\n/**\n * JSON file cache strategy with tag support\n * Persistent across process restarts, stored in JSON files\n * Simple and requires no external dependencies, but not suitable for high-performance scenarios\n */\nexport function createJsonFileStrategy(filePath?: string, options?: { defaultTtl?: number }): CacheStrategy {\n const defaultTtl = options?.defaultTtl\n const cacheFile = filePath || process.env.CACHE_JSON_FILE_PATH || DEFAULT_JSON_FILE_CACHE_PATH\n const dir = path.dirname(cacheFile)\n\n type StorageData = {\n entries: Record<string, CacheEntry>\n tagIndex: Record<string, string[]> // tag -> array of keys\n }\n\n function ensureDir(): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true })\n }\n }\n\n function readData(): StorageData {\n ensureDir()\n if (!fs.existsSync(cacheFile)) {\n return { entries: {}, tagIndex: {} }\n }\n try {\n const content = fs.readFileSync(cacheFile, 'utf8')\n return JSON.parse(content) as StorageData\n } catch {\n return { entries: {}, tagIndex: {} }\n }\n }\n\n function writeData(data: StorageData): void {\n ensureDir()\n fs.writeFileSync(cacheFile, JSON.stringify(data, null, 2), 'utf8')\n }\n\n function isExpired(entry: CacheEntry): boolean {\n if (entry.expiresAt === null) return false\n return Date.now() > entry.expiresAt\n }\n\n function addToTagIndex(data: StorageData, key: string, tags: string[]): void {\n for (const tag of tags) {\n if (!data.tagIndex[tag]) {\n data.tagIndex[tag] = []\n }\n if (!data.tagIndex[tag].includes(key)) {\n data.tagIndex[tag].push(key)\n }\n }\n }\n\n function removeFromTagIndex(data: StorageData, key: string, tags: string[]): void {\n for (const tag of tags) {\n if (data.tagIndex[tag]) {\n data.tagIndex[tag] = data.tagIndex[tag].filter((k) => k !== key)\n if (data.tagIndex[tag].length === 0) {\n delete data.tagIndex[tag]\n }\n }\n }\n }\n\n const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {\n const data = readData()\n const entry = data.entries[key]\n\n if (!entry) return null\n\n if (isExpired(entry)) {\n if (options?.returnExpired) {\n return entry.value\n }\n // Clean up expired entry\n removeFromTagIndex(data, key, entry.tags)\n delete data.entries[key]\n writeData(data)\n return null\n }\n\n return entry.value\n }\n\n const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {\n const data = readData()\n\n // Remove old entry from tag index if it exists\n const oldEntry = data.entries[key]\n if (oldEntry) {\n removeFromTagIndex(data, key, oldEntry.tags)\n }\n\n const ttl = options?.ttl ?? defaultTtl\n const tags = options?.tags || []\n const expiresAt = ttl ? Date.now() + ttl : null\n\n const entry: CacheEntry = {\n key,\n value,\n tags,\n expiresAt,\n createdAt: Date.now(),\n }\n\n data.entries[key] = entry\n addToTagIndex(data, key, tags)\n\n writeData(data)\n }\n\n const has = async (key: string): Promise<boolean> => {\n const data = readData()\n const entry = data.entries[key]\n\n if (!entry) return false\n\n if (isExpired(entry)) {\n removeFromTagIndex(data, key, entry.tags)\n delete data.entries[key]\n writeData(data)\n return false\n }\n\n return true\n }\n\n const deleteKey = async (key: string): Promise<boolean> => {\n const data = readData()\n const entry = data.entries[key]\n\n if (!entry) return false\n\n removeFromTagIndex(data, key, entry.tags)\n delete data.entries[key]\n writeData(data)\n\n return true\n }\n\n const deleteByTags = async (tags: string[]): Promise<number> => {\n const data = readData()\n const keysToDelete = new Set<string>()\n\n // Collect all keys that have any of the specified tags\n for (const tag of tags) {\n const keys = data.tagIndex[tag] || []\n for (const key of keys) {\n keysToDelete.add(key)\n }\n }\n\n // Delete all collected keys\n for (const key of keysToDelete) {\n const entry = data.entries[key]\n if (entry) {\n removeFromTagIndex(data, key, entry.tags)\n delete data.entries[key]\n }\n }\n\n writeData(data)\n return keysToDelete.size\n }\n\n const clear = async (): Promise<number> => {\n const data = readData()\n const size = Object.keys(data.entries).length\n\n writeData({ entries: {}, tagIndex: {} })\n\n return size\n }\n\n const keys = async (pattern?: string): Promise<string[]> => {\n const data = readData()\n const allKeys = Object.keys(data.entries)\n\n if (!pattern) return allKeys\n\n return allKeys.filter((key) => matchCacheKeyPattern(key, pattern))\n }\n\n const stats = async (): Promise<{ size: number; expired: number }> => {\n const data = readData()\n const allEntries = Object.values(data.entries)\n\n let expired = 0\n for (const entry of allEntries) {\n if (isExpired(entry)) {\n expired++\n }\n }\n\n return { size: allEntries.length, expired }\n }\n\n const cleanup = async (): Promise<number> => {\n const data = readData()\n let removed = 0\n\n const keysToRemove: string[] = []\n for (const [key, entry] of Object.entries(data.entries)) {\n if (isExpired(entry)) {\n keysToRemove.push(key)\n }\n }\n\n for (const key of keysToRemove) {\n const entry = data.entries[key]\n removeFromTagIndex(data, key, entry.tags)\n delete data.entries[key]\n removed++\n }\n\n if (removed > 0) {\n writeData(data)\n }\n\n return removed\n }\n\n return {\n get,\n set,\n has,\n delete: deleteKey,\n deleteByTags,\n clear,\n keys,\n stats,\n cleanup,\n }\n}\n"],
5
+ "mappings": "AACA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,oCAAoC;AAC7C,SAAS,4BAA4B;AAO9B,SAAS,uBAAuB,UAAmB,SAAkD;AAC1G,QAAM,aAAa,SAAS;AAC5B,QAAM,YAAY,YAAY,QAAQ,IAAI,wBAAwB;AAClE,QAAM,MAAM,KAAK,QAAQ,SAAS;AAOlC,WAAS,YAAkB;AACzB,QAAI,CAAC,GAAG,WAAW,GAAG,GAAG;AACvB,SAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,IACvC;AAAA,EACF;AAEA,WAAS,WAAwB;AAC/B,cAAU;AACV,QAAI,CAAC,GAAG,WAAW,S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AK,OAAO,QAAQ,KAAK,OAAO,GAAG;AACvD,UAAI,UAAU,KAAK,GAAG;AACpB,qBAAa,KAAK,GAAG;AAAA,MACvB;AAAA,IACF;AAEA,eAAW,OAAO,cAAc;AAC9B,YAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,yBAAmB,MAAM,KAAK,MAAM,IAAI;AACxC,aAAO,KAAK,QAAQ,GAAG;AACvB;AAAA,IACF;AAEA,QAAI,UAAU,GAAG;AACf,gBAAU,IAAI;AAAA,IAChB;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
+ "names": ["options", "keys"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@open-mercato/cache-provider-jsonfile",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.11.1-develop.8687.1.adb16f62b3",
4
+ "description": "Stock jsonfile cache factory for Open Mercato",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "node build.mjs",
16
+ "watch": "node watch.mjs",
17
+ "typecheck": "tsc --noEmit"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "^26.4.0",
21
+ "typescript": "7.0.2"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/open-mercato/open-mercato",
29
+ "directory": "packages/cache-provider-jsonfile"
30
+ },
31
+ "dependencies": {
32
+ "@open-mercato/cache-provider-kit": "0.11.1-develop.8687.1.adb16f62b3"
33
+ },
34
+ "stableVersion": "0.11.0"
6
35
  }
package/src/index.ts ADDED
@@ -0,0 +1,242 @@
1
+ import type { CacheStrategy, CacheEntry, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { DEFAULT_JSON_FILE_CACHE_PATH } from '@open-mercato/cache-provider-kit/defaults'
5
+ import { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'
6
+
7
+ /**
8
+ * JSON file cache strategy with tag support
9
+ * Persistent across process restarts, stored in JSON files
10
+ * Simple and requires no external dependencies, but not suitable for high-performance scenarios
11
+ */
12
+ export function createJsonFileStrategy(filePath?: string, options?: { defaultTtl?: number }): CacheStrategy {
13
+ const defaultTtl = options?.defaultTtl
14
+ const cacheFile = filePath || process.env.CACHE_JSON_FILE_PATH || DEFAULT_JSON_FILE_CACHE_PATH
15
+ const dir = path.dirname(cacheFile)
16
+
17
+ type StorageData = {
18
+ entries: Record<string, CacheEntry>
19
+ tagIndex: Record<string, string[]> // tag -> array of keys
20
+ }
21
+
22
+ function ensureDir(): void {
23
+ if (!fs.existsSync(dir)) {
24
+ fs.mkdirSync(dir, { recursive: true })
25
+ }
26
+ }
27
+
28
+ function readData(): StorageData {
29
+ ensureDir()
30
+ if (!fs.existsSync(cacheFile)) {
31
+ return { entries: {}, tagIndex: {} }
32
+ }
33
+ try {
34
+ const content = fs.readFileSync(cacheFile, 'utf8')
35
+ return JSON.parse(content) as StorageData
36
+ } catch {
37
+ return { entries: {}, tagIndex: {} }
38
+ }
39
+ }
40
+
41
+ function writeData(data: StorageData): void {
42
+ ensureDir()
43
+ fs.writeFileSync(cacheFile, JSON.stringify(data, null, 2), 'utf8')
44
+ }
45
+
46
+ function isExpired(entry: CacheEntry): boolean {
47
+ if (entry.expiresAt === null) return false
48
+ return Date.now() > entry.expiresAt
49
+ }
50
+
51
+ function addToTagIndex(data: StorageData, key: string, tags: string[]): void {
52
+ for (const tag of tags) {
53
+ if (!data.tagIndex[tag]) {
54
+ data.tagIndex[tag] = []
55
+ }
56
+ if (!data.tagIndex[tag].includes(key)) {
57
+ data.tagIndex[tag].push(key)
58
+ }
59
+ }
60
+ }
61
+
62
+ function removeFromTagIndex(data: StorageData, key: string, tags: string[]): void {
63
+ for (const tag of tags) {
64
+ if (data.tagIndex[tag]) {
65
+ data.tagIndex[tag] = data.tagIndex[tag].filter((k) => k !== key)
66
+ if (data.tagIndex[tag].length === 0) {
67
+ delete data.tagIndex[tag]
68
+ }
69
+ }
70
+ }
71
+ }
72
+
73
+ const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {
74
+ const data = readData()
75
+ const entry = data.entries[key]
76
+
77
+ if (!entry) return null
78
+
79
+ if (isExpired(entry)) {
80
+ if (options?.returnExpired) {
81
+ return entry.value
82
+ }
83
+ // Clean up expired entry
84
+ removeFromTagIndex(data, key, entry.tags)
85
+ delete data.entries[key]
86
+ writeData(data)
87
+ return null
88
+ }
89
+
90
+ return entry.value
91
+ }
92
+
93
+ const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {
94
+ const data = readData()
95
+
96
+ // Remove old entry from tag index if it exists
97
+ const oldEntry = data.entries[key]
98
+ if (oldEntry) {
99
+ removeFromTagIndex(data, key, oldEntry.tags)
100
+ }
101
+
102
+ const ttl = options?.ttl ?? defaultTtl
103
+ const tags = options?.tags || []
104
+ const expiresAt = ttl ? Date.now() + ttl : null
105
+
106
+ const entry: CacheEntry = {
107
+ key,
108
+ value,
109
+ tags,
110
+ expiresAt,
111
+ createdAt: Date.now(),
112
+ }
113
+
114
+ data.entries[key] = entry
115
+ addToTagIndex(data, key, tags)
116
+
117
+ writeData(data)
118
+ }
119
+
120
+ const has = async (key: string): Promise<boolean> => {
121
+ const data = readData()
122
+ const entry = data.entries[key]
123
+
124
+ if (!entry) return false
125
+
126
+ if (isExpired(entry)) {
127
+ removeFromTagIndex(data, key, entry.tags)
128
+ delete data.entries[key]
129
+ writeData(data)
130
+ return false
131
+ }
132
+
133
+ return true
134
+ }
135
+
136
+ const deleteKey = async (key: string): Promise<boolean> => {
137
+ const data = readData()
138
+ const entry = data.entries[key]
139
+
140
+ if (!entry) return false
141
+
142
+ removeFromTagIndex(data, key, entry.tags)
143
+ delete data.entries[key]
144
+ writeData(data)
145
+
146
+ return true
147
+ }
148
+
149
+ const deleteByTags = async (tags: string[]): Promise<number> => {
150
+ const data = readData()
151
+ const keysToDelete = new Set<string>()
152
+
153
+ // Collect all keys that have any of the specified tags
154
+ for (const tag of tags) {
155
+ const keys = data.tagIndex[tag] || []
156
+ for (const key of keys) {
157
+ keysToDelete.add(key)
158
+ }
159
+ }
160
+
161
+ // Delete all collected keys
162
+ for (const key of keysToDelete) {
163
+ const entry = data.entries[key]
164
+ if (entry) {
165
+ removeFromTagIndex(data, key, entry.tags)
166
+ delete data.entries[key]
167
+ }
168
+ }
169
+
170
+ writeData(data)
171
+ return keysToDelete.size
172
+ }
173
+
174
+ const clear = async (): Promise<number> => {
175
+ const data = readData()
176
+ const size = Object.keys(data.entries).length
177
+
178
+ writeData({ entries: {}, tagIndex: {} })
179
+
180
+ return size
181
+ }
182
+
183
+ const keys = async (pattern?: string): Promise<string[]> => {
184
+ const data = readData()
185
+ const allKeys = Object.keys(data.entries)
186
+
187
+ if (!pattern) return allKeys
188
+
189
+ return allKeys.filter((key) => matchCacheKeyPattern(key, pattern))
190
+ }
191
+
192
+ const stats = async (): Promise<{ size: number; expired: number }> => {
193
+ const data = readData()
194
+ const allEntries = Object.values(data.entries)
195
+
196
+ let expired = 0
197
+ for (const entry of allEntries) {
198
+ if (isExpired(entry)) {
199
+ expired++
200
+ }
201
+ }
202
+
203
+ return { size: allEntries.length, expired }
204
+ }
205
+
206
+ const cleanup = async (): Promise<number> => {
207
+ const data = readData()
208
+ let removed = 0
209
+
210
+ const keysToRemove: string[] = []
211
+ for (const [key, entry] of Object.entries(data.entries)) {
212
+ if (isExpired(entry)) {
213
+ keysToRemove.push(key)
214
+ }
215
+ }
216
+
217
+ for (const key of keysToRemove) {
218
+ const entry = data.entries[key]
219
+ removeFromTagIndex(data, key, entry.tags)
220
+ delete data.entries[key]
221
+ removed++
222
+ }
223
+
224
+ if (removed > 0) {
225
+ writeData(data)
226
+ }
227
+
228
+ return removed
229
+ }
230
+
231
+ return {
232
+ get,
233
+ set,
234
+ has,
235
+ delete: deleteKey,
236
+ deleteByTags,
237
+ clear,
238
+ keys,
239
+ stats,
240
+ cleanup,
241
+ }
242
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "../../tsconfig.base.json",
4
+ "compilerOptions": {
5
+ "noEmit": true,
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src/**/*"],
9
+ "exclude": ["node_modules", "dist", "**/__tests__/**"]
10
+ }
package/watch.mjs ADDED
@@ -0,0 +1,6 @@
1
+ import { watch } from '../../scripts/watch.mjs'
2
+ import { dirname } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const __dirname = dirname(fileURLToPath(import.meta.url))
6
+ watch(__dirname)
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.