-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
51 lines (48 loc) · 1.94 KB
/
cache.ts
File metadata and controls
51 lines (48 loc) · 1.94 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
/** @fileoverview Cache key generation utilities for DLX package installations. */
let _crypto: typeof import('node:crypto') | undefined
/**
* Lazily load the crypto module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getCrypto() {
if (_crypto === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_crypto = /*@__PURE__*/ require('node:crypto')
}
return _crypto as typeof import('node:crypto')
}
/**
* Generate a cache directory name using npm/npx approach.
* Uses first 16 characters of SHA-512 hash (like npm/npx).
*
* Rationale for SHA-512 truncated (vs full SHA-256):
* - Matches npm/npx ecosystem behavior
* - Shorter paths for Windows MAX_PATH compatibility (260 chars)
* - 16 hex chars = 64 bits = acceptable collision risk for local cache
* - Collision probability ~1 in 18 quintillion with 1000 entries
*
* Input strategy (aligned with npx):
* - npx uses package spec strings (e.g., '@scope/pkg@1.0.0', 'prettier@3.0.0')
* - Caller provides complete spec string with version for accurate cache keying
* - For package installs: Use PURL-style spec with version
* Examples: 'npm:prettier@3.0.0', 'pypi:requests@2.31.0', 'gem:rails@7.0.0'
* Note: Socket uses shorthand format without 'pkg:' prefix
* (handled by @socketregistry/packageurl-js)
* - For binary downloads: Use URL:name for uniqueness
*
* Reference: npm/cli v11.6.2 libnpmexec/lib/index.js#L233-L244
* https://github.com/npm/cli/blob/v11.6.2/workspaces/libnpmexec/lib/index.js#L233-L244
* Implementation: packages.map().sort().join('\n') → SHA-512 → slice(0,16)
* npx hashes the package spec (name@version), not just name
*
* @example
* ```typescript
* const key = generateCacheKey('prettier@3.0.0')
* // e.g. 'a1b2c3d4e5f67890'
* ```
*/
export function generateCacheKey(spec: string): string {
const crypto = getCrypto()
return crypto.createHash('sha512').update(spec).digest('hex').substring(0, 16)
}