-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacache.ts
More file actions
300 lines (278 loc) · 8.18 KB
/
cacache.ts
File metadata and controls
300 lines (278 loc) · 8.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/** @fileoverview Cacache utilities for Socket ecosystem shared content-addressable cache. */
import cacache from './external/cacache'
import { getSocketCacacheDir } from './paths/socket'
import {
RegExpCtor,
RegExpPrototypeTest,
StringPrototypeIncludes,
StringPrototypeReplaceAll,
StringPrototypeStartsWith,
TypeErrorCtor,
} from './primordials'
export interface GetOptions {
integrity?: string | undefined
size?: number | undefined
memoize?: boolean | undefined
}
export interface PutOptions {
integrity?: string | undefined
size?: number | undefined
metadata?: unknown | undefined
memoize?: boolean | undefined
}
export interface CacheEntry {
data: Buffer
integrity: string
key: string
metadata?: unknown | undefined
path: string
size: number
time: number
}
export interface RemoveOptions {
/**
* Optional key prefix to filter removals.
* If provided, only keys starting with this prefix will be removed.
* Can include wildcards (*) for pattern matching.
*
* @example
* { prefix: 'socket-sdk' } // Simple prefix
* { prefix: 'socket-sdk:scans:abc*' } // With wildcard
*/
prefix?: string | undefined
}
/**
* Build a key→boolean matcher for `pattern`. For non-wildcard patterns
* this returns a prefix-startsWith predicate (no regex allocation); for
* wildcard patterns it compiles the regex *once* and closes over it so
* the caller can apply the same matcher across N keys in O(1)-per-key.
*
* Anchors both ends — `foo*bar` matches exactly `foo<anything>bar`,
* not `foo<anything>bar<more>`.
*/
function createPatternMatcher(pattern: string): (key: string) => boolean {
if (!pattern.includes('*')) {
return (key: string) => StringPrototypeStartsWith(key, pattern)
}
// Escape regex special characters except `*`, then convert `*` to `.*`.
const escaped = StringPrototypeReplaceAll(
pattern,
/[.+?^${}()|[\]\\]/g,
'\\$&',
)
const regexPattern = StringPrototypeReplaceAll(escaped, '*', '.*')
const regex = new RegExpCtor(`^${regexPattern}$`)
return (key: string) => RegExpPrototypeTest(regex, key)
}
/**
* Clear entries from the Socket shared cache.
*
* Supports wildcard patterns (*) in prefix for flexible matching.
* For simple prefixes without wildcards, uses efficient streaming.
* For wildcard patterns, iterates and matches each entry.
*
* @param options - Optional configuration for selective clearing
* @param options.prefix - Prefix or pattern to match (supports * wildcards)
* @returns Number of entries removed (only when prefix is specified)
*
* @example
* // Clear all entries
* await clear()
*
* @example
* // Clear entries with simple prefix
* const removed = await clear({ prefix: 'socket-sdk:scans' })
* console.log(`Removed ${removed} scan cache entries`)
*
* @example
* // Clear entries with wildcard pattern
* await clear({ prefix: 'socket-sdk:scans:abc*' })
* await clear({ prefix: 'socket-sdk:npm/lodash/*' })
*/
export async function clear(
options?: RemoveOptions | undefined,
): Promise<number | undefined> {
const opts = { __proto__: null, ...options } as RemoveOptions
const cacache = getCacache()
const cacheDir = getSocketCacacheDir()
// If no prefix specified, clear everything.
if (!opts.prefix) {
try {
/* c8 ignore next - External cacache call */
await cacache.rm.all(cacheDir)
return
} catch (e) {
// Ignore ENOTEMPTY errors - can occur when multiple processes
// are cleaning up concurrently (e.g., in CI test environments).
if ((e as NodeJS.ErrnoException)?.code !== 'ENOTEMPTY') {
throw e
}
return
}
}
const hasWildcard = opts.prefix.includes('*')
// For simple prefix (no wildcards), use faster iteration.
if (!hasWildcard) {
let removed = 0
/* c8 ignore next - External cacache call */
const stream = cacache.ls.stream(cacheDir)
for await (const entry of stream) {
if (entry.key.startsWith(opts.prefix)) {
try {
/* c8 ignore next - External cacache call */
await cacache.rm.entry(cacheDir, entry.key)
removed++
} catch {
// Ignore individual removal errors (e.g., already removed by another process).
}
}
}
return removed
}
// For wildcard patterns, need to match each entry. Compile the
// matcher once outside the stream loop so wildcard scans are
// O(1)-per-key instead of re-compiling the regex on every entry.
let removed = 0
const matches = createPatternMatcher(opts.prefix)
/* c8 ignore next - External cacache call */
const stream = cacache.ls.stream(cacheDir)
for await (const entry of stream) {
if (matches(entry.key)) {
try {
/* c8 ignore next - External cacache call */
await cacache.rm.entry(cacheDir, entry.key)
removed++
} catch {
// Ignore individual removal errors.
}
}
}
return removed
}
/**
* Get data from the Socket shared cache by key.
* @throws {Error} When cache entry is not found.
* @throws {TypeError} If key contains wildcards (*)
*
* @example
* ```typescript
* const entry = await get('socket-sdk:scans:abc123')
* console.log(entry.data.toString('utf8'))
* ```
*/
export async function get(
key: string,
options?: GetOptions | undefined,
): Promise<CacheEntry> {
if (StringPrototypeIncludes(key, '*')) {
throw new TypeErrorCtor(
'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: "pattern*" }).',
)
}
const cacache = getCacache() as any
/* c8 ignore next - External cacache call */
return await cacache.get(getSocketCacacheDir(), key, options)
}
/**
* Get the cacache module for cache operations.
*
* @example
* ```typescript
* const cacache = getCacache()
* const entries = await cacache.ls(cacheDir)
* ```
*/
export function getCacache() {
// cacache is imported at the top
return cacache
}
/**
* Put data into the Socket shared cache with a key.
*
* @throws {TypeError} If key contains wildcards (*)
*
* @example
* ```typescript
* await put('socket-sdk:scans:abc123', Buffer.from('result data'))
* ```
*/
export async function put(
key: string,
data: string | Buffer,
options?: PutOptions | undefined,
) {
if (StringPrototypeIncludes(key, '*')) {
throw new TypeErrorCtor(
'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: "pattern*" }).',
)
}
const cacache = getCacache()
/* c8 ignore next - External cacache call */
return await cacache.put(getSocketCacacheDir(), key, data, options)
}
/**
* Remove an entry from the Socket shared cache by key.
*
* @throws {TypeError} If key contains wildcards (*)
*
* @example
* ```typescript
* await remove('socket-sdk:scans:abc123')
* ```
*/
export async function remove(key: string): Promise<unknown> {
if (StringPrototypeIncludes(key, '*')) {
throw new TypeErrorCtor(
'Cache key cannot contain wildcards (*). Use clear({ prefix: "pattern*" }) to remove multiple entries.',
)
}
const cacache = getCacache() as any
/* c8 ignore next - External cacache call */
return await cacache.rm.entry(getSocketCacacheDir(), key)
}
/**
* Get data from the Socket shared cache by key without throwing.
*
* @example
* ```typescript
* const entry = await safeGet('socket-sdk:scans:abc123')
* if (entry) {
* console.log(entry.data.toString('utf8'))
* }
* ```
*/
export async function safeGet(
key: string,
options?: GetOptions | undefined,
): Promise<CacheEntry | undefined> {
try {
return await get(key, options)
} catch {
return undefined
}
}
/**
* Execute a callback with a temporary directory for cache operations.
*
* @example
* ```typescript
* const result = await withTmp(async (tmpDir) => {
* // Use tmpDir for temporary cache work
* return 'done'
* })
* ```
*/
export async function withTmp<T>(
callback: (tmpDirPath: string) => Promise<T>,
): Promise<T> {
const cacache = getCacache()
// The DefinitelyTyped types for cacache.tmp.withTmp are incorrect.
// It actually returns the callback's return value, not void.
/* c8 ignore start - External cacache call */
return (await cacache.tmp.withTmp(
getSocketCacacheDir(),
{},
callback as any,
)) as T
/* c8 ignore stop */
}