@preventive/deptree 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/bin/compare.js +5 -2
  2. package/bin/deptree.js +66 -19
  3. package/cocoapods.d.ts +372 -0
  4. package/cocoapods.js +6 -0
  5. package/package.json +24 -6
  6. package/pnpm.d.ts +52 -75
  7. package/soldeer.d.ts +6 -3
  8. package/src/cargo/members.js +3 -2
  9. package/src/cargo/tree.js +2 -2
  10. package/src/cargo/workspace.js +3 -6
  11. package/src/cocoapods/archive.js +223 -0
  12. package/src/cocoapods/clean.js +186 -0
  13. package/src/cocoapods/fnmatch.js +198 -0
  14. package/src/cocoapods/inputs.js +80 -0
  15. package/src/cocoapods/install.js +61 -0
  16. package/src/cocoapods/podspec.js +203 -0
  17. package/src/cocoapods/podtree.js +131 -0
  18. package/src/cocoapods/source.js +90 -0
  19. package/src/cocoapods/tree.js +184 -0
  20. package/src/cocoapods/unicode.js +17 -0
  21. package/src/github.js +92 -0
  22. package/src/glob.js +2 -1
  23. package/src/hash.js +1 -34
  24. package/src/matcher.js +2 -4
  25. package/src/mount.js +3 -6
  26. package/src/npm/compat.js +3 -4
  27. package/src/npm/manifests.js +1 -1
  28. package/src/npm/tree.js +9 -8
  29. package/src/patch.js +9 -5
  30. package/src/pnpm/bins.js +12 -11
  31. package/src/pnpm/commands.js +5 -15
  32. package/src/pnpm/directories.js +250 -0
  33. package/src/pnpm/extensions.js +76 -0
  34. package/src/pnpm/filename.js +4 -4
  35. package/src/pnpm/frozen.js +3 -2
  36. package/src/pnpm/glob.js +1 -1
  37. package/src/pnpm/graph.js +7 -9
  38. package/src/pnpm/hoist.js +0 -36
  39. package/src/pnpm/hoisted.js +3 -3
  40. package/src/pnpm/hook.js +13 -21
  41. package/src/pnpm/inputs.js +7 -16
  42. package/src/pnpm/install.js +3 -4
  43. package/src/pnpm/lazy.js +18 -18
  44. package/src/pnpm/local.js +29 -15
  45. package/src/pnpm/minimatch.js +2 -2
  46. package/src/pnpm/nm-hoist.js +1 -1
  47. package/src/pnpm/npm-packlist.js +1 -1
  48. package/src/pnpm/overrides.js +3 -4
  49. package/src/pnpm/package.js +17 -9
  50. package/src/pnpm/packlist.js +1 -2
  51. package/src/pnpm/patches.js +15 -13
  52. package/src/pnpm/production.js +1 -1
  53. package/src/pnpm/projects.js +14 -40
  54. package/src/pnpm/readers.js +6 -29
  55. package/src/pnpm/settings.js +14 -37
  56. package/src/pnpm/tree.js +34 -24
  57. package/src/pnpm/uptodate.js +12 -13
  58. package/src/pnpm/workspace.js +8 -79
  59. package/src/pnpm/write.js +2 -1
  60. package/src/soldeer/tree.js +2 -2
  61. package/src/soldeer/zip.js +11 -42
  62. package/src/tarball.js +1 -3
  63. package/src/yarn1/hoist.js +4 -2
  64. package/src/yarn1/manifest.js +3 -2
  65. package/src/yarn1/requests.js +1 -1
  66. package/src/yarn1/resolve.js +16 -6
  67. package/src/yarn1/tree.js +12 -8
  68. package/src/soldeer/git.js +0 -67
@@ -0,0 +1,250 @@
1
+ // pnpm 11's check, from 11.28.7, of each directory snapshot a project reaches
2
+ // against the directory's package.json (localDirectoryDepIsUpToDate), and a
3
+ // stricter walk of every path for any pnpm, which each lockfile pnpm writes passes.
4
+
5
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
6
+ import { compareVersions, satisfies, valid, validRange } from '@preventive/upstream/semver.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { own } from '../manifest.js'
9
+ import { KINDS, specPath } from './frozen.js'
10
+ import { manifestAt } from './local.js'
11
+ import { catalogEntry, catalogOf } from './overrides.js'
12
+
13
+ const TARBALL = /\.(?:tgz|tar\.gz|tar|tar\.bz2|tbz2|tbz)$/u
14
+ const BARE_PATH = /^(?:[./]|~\/)/u
15
+ const RUNTIMES = new Set(['node', 'deno', 'bun'])
16
+ const keysOf = (deps) => Object.keys(deps ?? {})
17
+
18
+ function filePathOf(key) {
19
+ const at = packageKeyOf(key).indexOf('@file:', 1)
20
+ return at === -1 ? undefined : packageKeyOf(key).slice(at + '@file:'.length)
21
+ }
22
+ const isDirectoryPath = (path) => path !== undefined && !TARBALL.test(path.toLowerCase())
23
+
24
+ // Undefined where pnpm finds the catalog misconfigured.
25
+ function fromCatalog(catalogs, alias, spec) {
26
+ const catalog = catalogOf(spec)
27
+ if (catalog === undefined) return spec
28
+ const found = catalogEntry(catalogs, catalog, alias)
29
+ if (found === undefined || catalogOf(found) !== undefined || ['link', 'file'].includes(found.split(':')[0])) return undefined
30
+ return found
31
+ }
32
+
33
+ // getPeerSet, leaving out `others` too: an optional peer only in
34
+ // peerDependenciesMeta is one at `*`.
35
+ function peersOf(read, others = []) {
36
+ const peers = new Map()
37
+ const ownDeps = new Set([...(read.name == null ? [] : [read.name]), ...others, ...keysOf(read.optionalDependencies)])
38
+ for (const [name, range] of Object.entries(read.peerDependencies ?? {})) if (!ownDeps.has(name)) peers.set(name, { range, optional: false })
39
+ for (const [name, meta] of Object.entries(read.peerDependenciesMeta ?? {})) {
40
+ if (!ownDeps.has(name) && meta?.optional === true) peers.set(name, { range: peers.get(name)?.range ?? '*', optional: true })
41
+ }
42
+ return peers
43
+ }
44
+
45
+ // recordedPeersMatch.
46
+ function peersDiffer(read, pkg, catalogs) {
47
+ const declared = peersOf(read)
48
+ const unrecorded = [...peersOf(read, keysOf(read.dependencies)).keys()].find((name) => !Object.hasOwn(pkg.peerDependencies, name))
49
+ if (unrecorded !== undefined) return `its peer ${quote(unrecorded)} is not in the lockfile`
50
+ for (const [name, recorded] of Object.entries(pkg.peerDependencies)) {
51
+ const peer = declared.get(name)
52
+ if (peer === undefined) return `the lockfile's peer ${quote(name)} is not one of its peers`
53
+ if (recorded !== peer.range && recorded !== fromCatalog(catalogs, name, peer.range)) return `its peer ${quote(name)} is ${quote(peer.range)}, and ${quote(recorded)} in the lockfile`
54
+ const optional = own(pkg.peerDependenciesMeta, name)?.optional === true
55
+ if (peer.optional !== optional) return `its peer ${quote(name)} is ${peer.optional ? '' : 'not '}optional, and ${optional ? '' : 'not '}optional in the lockfile`
56
+ }
57
+ return undefined
58
+ }
59
+
60
+ // getNonDevWantedDependencies of prepareDependencyManifest: a dependency that
61
+ // is a peer pnpm installs or one above provides is left to the peer.
62
+ function childrenOf(ctx, read, scope, where) {
63
+ let deps = read.dependencies
64
+ if (deps && read.peerDependencies) {
65
+ const shadowed = new Set(keysOf(read.peerDependencies).filter((peer) => (ctx.autoInstallPeers && read.peerDependenciesMeta?.[peer]?.optional !== true) || scope.has(peer)))
66
+ deps = Object.fromEntries(Object.entries(deps).filter(([name]) => !shadowed.has(name)))
67
+ }
68
+ const runtime = [read.engines?.runtime ?? []].flat().find((item) => RUNTIMES.has(item?.name) && item.onFail === 'download' && typeof item.version === 'string' && !own(deps, item.name))
69
+ if (!ctx.strict && runtime !== undefined) throw new DeptreeError(`a ${runtime.name} runtime pnpm 11 would hold it to is not supported`, where)
70
+ const optional = read.optionalDependencies ?? {}
71
+ let bundled = read.bundledDependencies ?? read.bundleDependencies
72
+ if (bundled === true) bundled = keysOf(deps)
73
+ const left = new Set(Array.isArray(bundled) ? bundled : [])
74
+ return Object.entries({ ...optional, ...deps }).filter(([alias]) => !left.has(alias)).map(([alias, spec]) => ({ alias, spec, optional: Boolean(own(optional, alias)) }))
75
+ }
76
+
77
+ // lockedVersionSatisfies, which checks only a range strict semver reads; the
78
+ // strict walk checks a loose one too. pnpm refuses even the link it wrote for a
79
+ // path alone an override gives; pnpm 10 reads that path from the lockfile's.
80
+ function registryChild(ctx, { kind, alias }, spec, to, { dir, where }) {
81
+ if (to.startsWith('link:')) {
82
+ if (!ctx.strict) return `${kind}.${alias} is linked to ${quote(to.slice(5))}, and pnpm 11 holds ${quote(spec)}, which is neither link: nor file:, to a package the lockfile resolves, refusing even the lockfile it writes`
83
+ return BARE_PATH.test(spec) && [dir, '.'].some((base) => specPath(base, spec, where) === to.slice(5)) ? undefined : `${kind}.${alias} is linked to ${quote(to.slice(5))}, which is not where ${quote(spec)} leads`
84
+ }
85
+ let wanted = { name: alias, range: spec }
86
+ if (spec.startsWith('npm:')) {
87
+ const raw = spec.slice('npm:'.length)
88
+ const at = raw.lastIndexOf('@')
89
+ wanted = at <= 0 ? { name: raw, range: '*' } : { name: raw.slice(0, at), range: raw.slice(at + 1) }
90
+ } else if (valid(spec, { loose: true }) === null && validRange(spec, { loose: true }) === null && encodeURIComponent(spec) !== spec) {
91
+ if (ctx.strict) return undefined
92
+ throw new DeptreeError(`${kind}.${alias} is ${quote(spec)}, which is no version, range or tag, and a directory's dependency of another sort that pnpm 11 holds to the lockfile is not supported`, where)
93
+ }
94
+ const locked = ctx.packages[to]
95
+ if (locked.name !== wanted.name) return `${kind}.${alias} resolved to ${quote(to)}, which is not ${quote(wanted.name)}`
96
+ if (validRange(wanted.range, { loose: ctx.strict === true }) === null) return undefined
97
+ return typeof locked.version === 'string' && satisfies(locked.version, wanted.range, { loose: true }) ? undefined : `${kind}.${alias} resolved to ${quote(to)}, which is not in ${quote(wanted.range)}`
98
+ }
99
+
100
+ // localSpecIsUpToDate: the specifier's path is read from the directory.
101
+ function localChild(ctx, { kind, alias }, spec, to, { dir, where }) {
102
+ if (spec.startsWith('workspace:')) {
103
+ if (ctx.strict) return undefined
104
+ throw new DeptreeError(`a workspace: dependency, ${quote(alias)}, of a directory pnpm 11 holds to the lockfile is not supported`, where)
105
+ }
106
+ const path = to.startsWith('link:') ? to.slice(5) : spec.startsWith('file:') ? filePathOf(to) : undefined
107
+ if (path === undefined || specPath(dir, spec.slice(5), where) !== specPath('.', path, where)) return `${kind}.${alias} is ${quote(to)} in the lockfile, which is not where ${quote(spec)} leads`
108
+ return undefined
109
+ }
110
+
111
+ // A frozen install lets an optional one go unresolved, and `ctx.drops` says
112
+ // where pnpm leaves out one that is an optional peer too (package.js).
113
+ function missing(ctx, { kind, alias, optional }, pkg, read) {
114
+ if (optional ? own(pkg.dependencies, alias) === undefined : ctx.drops?.(read, alias)) return undefined
115
+ const other = optional ? 'dependencies' : 'optionalDependencies'
116
+ return own(pkg[other], alias) === undefined ? `${kind}.${alias} is not in the lockfile` : `${kind}.${alias} is among the lockfile's ${other}`
117
+ }
118
+
119
+ function outdated(why, { pnpm, strict }, where) {
120
+ if (strict) return new DeptreeError(`the lockfile is not up to date with its package.json, as no lockfile pnpm writes is, though a frozen install of pnpm ${pnpm} may take it: ${why}`, where)
121
+ return new DeptreeError(`the lockfile is not up to date with its package.json, which a frozen install of pnpm ${pnpm} refuses: ${why}`, where)
122
+ }
123
+
124
+ function walkChildren(ctx, { key, pkg, dir, read }, scope, visited) {
125
+ const where = quote(key)
126
+ const children = childrenOf(ctx, read, scope, where)
127
+ const expected = new Set([...children.map(({ alias }) => alias), ...peersOf(read).keys(), ...keysOf(read.peerDependencies)])
128
+ for (const kind of ['dependencies', 'optionalDependencies']) {
129
+ const unasked = keysOf(pkg[kind]).find((name) => !expected.has(name))
130
+ if (unasked !== undefined) throw outdated(`${kind}.${unasked} is not one it asks for`, ctx, where)
131
+ }
132
+ const inner = new Set([...scope, ...keysOf(pkg.dependencies), ...keysOf(pkg.optionalDependencies)])
133
+ for (const child of children) {
134
+ const dep = { ...child, kind: child.optional ? 'optionalDependencies' : 'dependencies' }
135
+ const to = own(pkg[dep.kind], child.alias)
136
+ const spec = to === undefined ? undefined : fromCatalog(ctx.catalogs, child.alias, child.spec)
137
+ const local = spec !== undefined && /^(?:link|file|workspace):/u.test(spec)
138
+ const why = to === undefined ? missing(ctx, dep, pkg, read)
139
+ : spec === undefined ? `${dep.kind}.${child.alias}, ${quote(child.spec)}, names no catalog entry pnpm takes`
140
+ : (local ? localChild : registryChild)(ctx, dep, spec, to, { dir, where })
141
+ if (why !== undefined) throw outdated(why, ctx, where)
142
+ if (local && !to.startsWith('link:')) walk(ctx, to, inner, visited)
143
+ }
144
+ }
145
+
146
+ // Hooked with the directory as `dir`, so a path an override gives is read
147
+ // from it; `plain`, as for any package.
148
+ function readOf(ctx, key, dir, plain = false) {
149
+ const reads = plain ? ctx.plain : ctx.reads
150
+ if (!reads.has(dir)) reads.set(dir, ctx.hook(manifestAt(ctx.project, dir, quote(key)), `${quote(packageKeyOf(key))}: package.json`, plain ? {} : { dir }))
151
+ return reads.get(dir)
152
+ }
153
+
154
+ // `scope` is the aliases above the snapshot; it is passed when reached again
155
+ // with the same `ctx.keyOf` of them.
156
+ function walk(ctx, key, scope, visited) {
157
+ const pkg = ctx.packages[key]
158
+ if (pkg.resolution.type !== 'directory') return
159
+ const dir = pkg.resolution.directory
160
+ if (!ctx.installed.has(dir)) throw new DeptreeError('a dependency on a local directory is supported only where a file: override names it', quote(key))
161
+ const read = readOf(ctx, key, dir)
162
+ const taken = ctx.keyOf(read, scope)
163
+ const scopes = visited.get(key) ?? new Set()
164
+ if (scopes.has(taken)) return
165
+ visited.set(key, scopes.add(taken))
166
+ const why = peersDiffer(read, pkg, ctx.catalogs)
167
+ if (why !== undefined) throw outdated(why, ctx, quote(key))
168
+ walkChildren(ctx, { key, pkg, dir, read }, scope, visited)
169
+ }
170
+
171
+ // pnpm keys a visit by the aliases above that are its peers or any recorded;
172
+ // keying by those that are any directory's peers holds every path it may take.
173
+ const among = (scope, names) => [...new Set(names)].filter((name) => scope.has(name)).sort().join('\0')
174
+
175
+ // findNestedDirectoryPackages: each directory a package not from a directory
176
+ // depends on, with the packages above it and the aliases they depend by.
177
+ function nestedOf(packages) {
178
+ const isDirectory = (key) => packages[key].resolution.type === 'directory'
179
+ const edges = (pkg) => [...Object.entries(pkg.dependencies), ...Object.entries(pkg.optionalDependencies)].filter(([, to]) => !to.startsWith('link:'))
180
+ const nested = new Set()
181
+ const parents = new Map()
182
+ for (const [key, pkg] of Object.entries(packages)) {
183
+ for (const [, to] of edges(pkg)) {
184
+ if (!isDirectory(key) && to.includes('file:') && isDirectory(to)) nested.add(to)
185
+ if (!parents.has(to)) parents.set(to, [])
186
+ parents.get(to).push(key)
187
+ }
188
+ }
189
+ return [...nested].map((key) => {
190
+ const above = new Set()
191
+ const queue = [key]
192
+ while (queue.length > 0) {
193
+ for (const parent of parents.get(queue.pop()) ?? []) {
194
+ if (parent === key || above.has(parent)) continue
195
+ above.add(parent)
196
+ queue.push(parent)
197
+ }
198
+ }
199
+ return { key, above, aliases: [...above].flatMap((parent) => edges(packages[parent]).map(([alias]) => alias)) }
200
+ })
201
+ }
202
+
203
+ // Each directory a project depends on by `file:`, then each a dependency
204
+ // reaches through a package not from a directory.
205
+ function startsOf(manifest, importer, nested) {
206
+ const scope = new Set(KINDS.flatMap((kind) => keysOf(manifest[kind])))
207
+ const starts = []
208
+ for (const kind of KINDS) {
209
+ for (const [alias, to] of Object.entries(importer[kind])) {
210
+ const spec = importer.specifiers[alias] ?? ''
211
+ const direct = (spec.startsWith('file:') && isDirectoryPath(spec)) || isDirectoryPath(filePathOf(to))
212
+ if (own(manifest[kind], alias) && !to.startsWith('link:') && direct) starts.push({ key: to, scope, direct: true })
213
+ }
214
+ }
215
+ const reached = new Set(KINDS.flatMap((kind) => Object.values(importer[kind])))
216
+ for (const { key, above, aliases } of nested) {
217
+ if (reached.has(key) || [...above].some((parent) => reached.has(parent))) starts.push({ key, scope: new Set([...aliases, ...scope]), direct: false })
218
+ }
219
+ return starts
220
+ }
221
+
222
+ // `fresh` is pnpm 12's own check (local.js), run first for its message.
223
+ export function createDirectoryCheck(lockfile, { host, hook, project, installed, settings, fresh, drops }) {
224
+ const since = (version) => compareVersions(host.pnpm, version) >= 0
225
+ const { packages } = lockfile
226
+ const ctx = { packages, hook, project, installed, drops, pnpm: host.pnpm, autoInstallPeers: settings.autoInstallPeers, catalogs: settings.catalogs ?? {}, reads: new Map(), plain: new Map() }
227
+ const recorded = Object.values(packages).flatMap((pkg) => keysOf(pkg.peerDependencies))
228
+ const directories = Object.entries(packages).filter(([, pkg]) => pkg.resolution.type === 'directory' && installed.has(pkg.resolution.directory))
229
+ let everyPeer, nested
230
+ const everyPeerOf = () => (everyPeer ??= [...recorded, ...directories.flatMap(([key, pkg]) => keysOf(readOf(ctx, key, pkg.resolution.directory).peerDependencies))])
231
+ const pnpmWalk = { ...ctx, keyOf: (read, scope) => among(scope, [...keysOf(read.peerDependencies), ...recorded]) }
232
+ const strictWalk = { ...ctx, strict: true, keyOf: (read, scope) => among(scope, everyPeerOf()) }
233
+ return (manifest, importer) => {
234
+ nested ??= nestedOf(packages)
235
+ const starts = startsOf(manifest, importer, nested)
236
+ if (host.major === 11 && since('11.28.7')) {
237
+ // Before 11.28.9 each dependency of a project has a walk of its own.
238
+ const shared = new Map()
239
+ for (const { key, scope, direct } of starts) {
240
+ if (direct || since('11.28.10')) walk(pnpmWalk, key, scope, direct && !since('11.28.9') ? new Map() : shared)
241
+ }
242
+ }
243
+ for (const { key, direct } of fresh === undefined ? [] : starts) {
244
+ const { resolution } = packages[key]
245
+ if (direct && resolution.type === 'directory' && installed.has(resolution.directory)) fresh({ key }, readOf(ctx, key, resolution.directory, true))
246
+ }
247
+ const every = new Map()
248
+ for (const { key, scope } of starts) walk(strictWalk, key, scope, every)
249
+ }
250
+ }
@@ -0,0 +1,76 @@
1
+ // pnpm's package extensions (createPackageExtender), and the checksum a frozen
2
+ // install holds the lockfile to. Only what pnpm 10, 11 and 12 hash alike is
3
+ // read: pnpm 12 hashes an extension as it parses it, less what it does not know.
4
+
5
+ import { satisfies, validRange } from '@preventive/upstream/semver.js'
6
+ import { compareNames } from '@preventive/vfs/path.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { sha256Base64 } from '../hash.js'
9
+ import { parseWanted } from './overrides.js'
10
+ import { readers } from './readers.js'
11
+
12
+ const META = 'peerDependenciesMeta'
13
+ const FIELDS = ['dependencies', 'optionalDependencies', 'peerDependencies', META]
14
+ const onlyOptional = (meta) => Object.entries(meta).every(([key, flag]) => key === 'optional' && typeof flag === 'boolean')
15
+
16
+ function checkExtension(extension, where) {
17
+ for (const [field, value] of Object.entries(readers.mapping(extension, where))) {
18
+ if (!FIELDS.includes(field)) throw new DeptreeError(`${quote(field)} is not supported: pnpm extends only ${FIELDS.join(', ')}`, where)
19
+ for (const [name, entry] of Object.entries(readers.mapping(value, `${where}.${field}`))) {
20
+ const here = `${where}.${field}[${quote(name)}]`
21
+ if (field !== META) readers.text(entry, here)
22
+ else if (!onlyOptional(readers.mapping(entry, here))) throw new DeptreeError('expected nothing but `optional`, true or false', here)
23
+ }
24
+ }
25
+ }
26
+
27
+ // The ranges pnpm 12 is seen to read as npm's semver does. It fails on `~=7`
28
+ // and an empty one, which npm's reads, and takes `07`, which npm's does not.
29
+ const COMPARATOR = /^(?:[<>]=?|[=^~])?(?:\d+|[Xx*])(?:\.(?:\d+|[Xx*])){0,2}(?:-[\dA-Za-z.-]+)?$/u
30
+ const plain = (range) => validRange(range) !== null && range.split('||').every((set) => set.trim().split(/ +/u).every((part) => COMPARATOR.test(part)))
31
+
32
+ export function listExtensions(packageExtensions, major = 10) {
33
+ return Object.entries(packageExtensions ?? {}).map(([selector, extension]) => {
34
+ const where = `packageExtensions[${quote(selector)}]`
35
+ const parsed = selector.isWellFormed() ? parseWanted(selector) : undefined
36
+ if (parsed === undefined) throw new DeptreeError('the selector names no package, which is not supported', where)
37
+ // pnpm 12 applies them in the order written, and a mapping lists digits first.
38
+ if (major >= 12 && /^\d+$/u.test(selector)) throw new DeptreeError('a name of digits alone is not supported for pnpm 12', where)
39
+ if (major >= 12 && parsed.range !== undefined && !plain(parsed.range)) throw new DeptreeError(`pnpm 12 fails on the range ${quote(parsed.range)}, or may read it otherwise than npm's semver, which is not supported`, where)
40
+ checkExtension(extension, where)
41
+ return { selector, ...parsed, extension }
42
+ })
43
+ }
44
+
45
+ // object-hash's text of a value: a string by its length in UTF-16 units, keys
46
+ // sorted by those units for pnpm 10 and 11 and by code point for pnpm 12.
47
+ function hashed(value, compare) {
48
+ if (typeof value === 'string') return `string:${value.length}:${value}`
49
+ if (typeof value === 'boolean') return `bool:${value}`
50
+ const keys = Object.keys(value).sort(compare)
51
+ return `object:${keys.length}:${keys.map((key) => `${hashed(key, compare)}:${hashed(value[key], compare)},`).join('')}`
52
+ }
53
+
54
+ export async function extensionsChecksum(extensions, major = 10) {
55
+ if (extensions.length === 0) return undefined
56
+ const setting = Object.fromEntries(extensions.map(({ selector, extension }) => [selector, extension]))
57
+ return `sha256-${await sha256Base64(hashed(setting, major >= 12 ? compareNames : undefined), 'packageExtensions')}`
58
+ }
59
+
60
+ // semver's satisfies throws a TypeError on a version that is neither a
61
+ // string nor falsy, as pnpm then fails.
62
+ export function inRange(version, range, where, named) {
63
+ if (version && typeof version !== 'string') throw new DeptreeError(`not a string, which pnpm fails on where ${named} names this package with a range`, `${where}.version`)
64
+ return satisfies(version, range)
65
+ }
66
+
67
+ export function extensionsOf(extensions, manifest, where) {
68
+ return extensions.filter(({ name, range }) => name === manifest.name && (range === undefined || inRange(manifest.version, range, where, 'an extension')))
69
+ }
70
+
71
+ // A package.json's own entry wins, and of two extensions the first.
72
+ export function extend(copy, extensions) {
73
+ for (const { extension } of extensions) {
74
+ for (const field of FIELDS) if (Object.hasOwn(extension, field)) copy[field] = { ...extension[field], ...copy[field] }
75
+ }
76
+ }
@@ -4,7 +4,7 @@
4
4
  // capital is cut short and hashed.
5
5
 
6
6
  import { quote } from '../error.js'
7
- import { md5Base32, sha256Hex } from '../hash.js'
7
+ import { sha256Hex } from '../hash.js'
8
8
 
9
9
  const encoder = new TextEncoder()
10
10
 
@@ -15,7 +15,7 @@ function cut(filename, length, major) {
15
15
  }
16
16
 
17
17
  export async function depPathToFilename(depPath, maxLength, major = 10) {
18
- let filename = depPath.replace(major < 10 ? /[\\/:*?"<>|]/gu : /[\\/:*?"<>|#]/gu, '+')
18
+ let filename = depPath.replace(/[\\/:*?"<>|#]/gu, '+')
19
19
  if (filename.includes('(')) filename = filename.replace(/\)$/u, '').replace(/\)\(|\(|\)/gu, '_')
20
20
  const hashed = filename
21
21
  const trailing = major >= 11 ? /[. ]*$/u.exec(filename)[0].length : 0
@@ -23,7 +23,7 @@ export async function depPathToFilename(depPath, maxLength, major = 10) {
23
23
  const length = major >= 12 ? encoder.encode(filename).length : filename.length
24
24
  const lower = major >= 12 ? filename.replace(/[A-Z]+/gu, (capitals) => capitals.toLowerCase()) : filename.toLowerCase()
25
25
  if (trailing === 0 && length <= maxLength && filename === lower) return filename
26
- // By pnpm's createBase32Hash, or createShortHash.
27
- const hash = `_${major < 10 ? md5Base32(hashed, quote(depPath)) : (await sha256Hex(hashed, quote(depPath))).slice(0, 32)}`
26
+ // By pnpm's createShortHash.
27
+ const hash = `_${(await sha256Hex(hashed, quote(depPath))).slice(0, 32)}`
28
28
  return `${cut(filename, Math.max(maxLength - hash.length, 0), major)}${hash}`
29
29
  }
@@ -70,7 +70,7 @@ export function checkCatalogResolutions(importer, catalogs, where) {
70
70
  }
71
71
 
72
72
  // Relative to the lockfile's directory, as the lockfile's links are.
73
- function specPath(dir, path, where) {
73
+ export function specPath(dir, path, where) {
74
74
  const clean = path.startsWith('./') ? path.slice(2) : path
75
75
  if (/^(?:~[/\\]|[/\\]|[A-Za-z]:)/u.test(clean) || clean.includes('\\')) throw new DeptreeError(`${quote(path)} is not a path from the project, which is not supported`, where)
76
76
  return join(dir, clean.replace(/\/+$/u, ''))
@@ -153,7 +153,8 @@ export function checkLinkedPackages({ manifest, importer, index: { projects, byN
153
153
  if (!spec) continue
154
154
  const workspaceRange = spec.startsWith('workspace:') && !isWorkspacePath(spec.slice('workspace:'.length))
155
155
  const linked = target.startsWith('link:')
156
- // pnpm 11's frozen install skips a local directory or tarball.
156
+ // A local directory pnpm 11 holds to its package.json otherwise, and
157
+ // only from 11.28.7 (directories.js); a tarball is refused elsewhere.
157
158
  if (importer.specifiers[alias].startsWith('file:') || packageKeyOf(target).includes('@file:')) continue
158
159
  if (linked && pathOf(spec) !== undefined) continue
159
160
  const { name, range } = parseSpec(spec, alias)
package/src/pnpm/glob.js CHANGED
@@ -1,4 +1,4 @@
1
- // glob 8 as npm-packlist 5 globs a `files` pattern for pnpm 9 and 10: dot
1
+ // glob 8 as npm-packlist 5 globs a `files` pattern for pnpm 10: dot
2
2
  // and nocase, a leading `!` or `#` taken as it is. Each path found is spelled
3
3
  // as glob spells it, a directory's with the trailing slash a pattern gave
4
4
  // it, and a file named by a pattern with no part to match against names
package/src/pnpm/graph.js CHANGED
@@ -1,4 +1,4 @@
1
- // The graph a pnpm 9 or 10 install links, as @pnpm/deps.graph-builder builds
1
+ // The graph a pnpm install links, as @pnpm/deps.graph-builder builds
2
2
  // it from a frozen lockfile. A child left out of the install is left out of its
3
3
  // parent's children; a `link:` child is the directory it names.
4
4
 
@@ -9,13 +9,11 @@ import { depPathToFilename } from './filename.js'
9
9
  const VIRTUAL_STORE = 'node_modules/.pnpm'
10
10
 
11
11
  // Every target but a `link:` is a snapshot, as the lockfile reader ensures.
12
- const childOf = (target, nodes) => (target.startsWith('link:') ? target.slice(5) : nodes.get(target)?.dir)
13
-
14
- const childrenOf = (targets, nodes) => new Map(Object.entries(targets).map(([alias, target]) => [alias, childOf(target, nodes)]).filter(([, dir]) => dir !== undefined))
12
+ const childrenOf = (targets, nodes) => new Map(Object.entries(targets).map(([alias, target]) => [alias, target.startsWith('link:') ? target.slice(5) : nodes.get(target)?.dir]).filter(([, dir]) => dir !== undefined))
15
13
 
16
14
  // The graph pnpm 12 hoists from, of every snapshot, skipped or not.
17
15
  function hoistingOf(lockfile, all) {
18
- const nodes = new Map([...all.values()].map((node) => [node.dir, { modules: node.modules, children: childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, all) }]))
16
+ const nodes = new Map(all.values().map((node) => [node.dir, { modules: node.modules, children: childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, all) }]))
19
17
  const direct = new Map(Object.keys(lockfile.importers).sort(compareNames).map((id) => {
20
18
  const { devDependencies, dependencies, optionalDependencies } = lockfile.importers[id]
21
19
  return [id, new Map([...childrenOf({ ...devDependencies, ...dependencies, ...optionalDependencies }, all)].filter(([, dir]) => nodes.has(dir)))]
@@ -24,8 +22,8 @@ function hoistingOf(lockfile, all) {
24
22
  }
25
23
 
26
24
  // `direct` has devDependencies first, as pnpm spreads them, for hoisting to
27
- // walk. pnpm 9 hoists from the lockfile instead, and pnpm 12 from the
28
- // snapshots, where skipped ones hold directories too.
25
+ // walk. pnpm 12 hoists from the snapshots instead, where skipped ones hold
26
+ // directories too.
29
27
  export async function buildGraph(lockfile, skipped, maxLength, major = 10) {
30
28
  const all = new Map()
31
29
  const keyByDir = new Map()
@@ -37,10 +35,10 @@ export async function buildGraph(lockfile, skipped, maxLength, major = 10) {
37
35
  keyByDir.set(dir, key)
38
36
  all.set(key, { key, pkg, name: pkg.name, dir, modules: `${store}/node_modules` })
39
37
  }
40
- const nodes = new Map([...all].filter(([key]) => !skipped.has(key)))
38
+ const nodes = new Map(all.entries().filter(([key]) => !skipped.has(key)))
41
39
  for (const node of nodes.values()) {
42
40
  node.children = childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, nodes)
43
41
  }
44
42
  const direct = new Map(Object.entries(lockfile.importers).map(([id, importer]) => [id, childrenOf({ ...importer.devDependencies, ...importer.dependencies, ...importer.optionalDependencies }, nodes)]))
45
- return { nodes, direct, hoisting: major >= 12 ? hoistingOf(lockfile, all) : major < 10 ? { lockfile, nodes } : undefined }
43
+ return { nodes, direct, hoisting: major >= 12 ? hoistingOf(lockfile, all) : undefined }
46
44
  }
package/src/pnpm/hoist.js CHANGED
@@ -74,41 +74,6 @@ function hoistGraph(nodes, starts, taken, typeOf, { projects = new Map(), instal
74
74
  return links
75
75
  }
76
76
 
77
- // pnpm 9's hoistGraph walks the lockfile from every project's direct
78
- // dependencies, the first project to list an alias keeping it. A `link:` or
79
- // skipped child takes its alias though nothing is linked by it, as does a
80
- // project, and the root's specifiers are taken from the start. Snapshots of
81
- // one depth are taken in the order of their keys.
82
- function hoist9({ lockfile, nodes }, typeOf, projects) {
83
- const root = Object.create(null)
84
- for (const [id, name] of projects) root[name] = { project: id }
85
- const direct = Object.create(null)
86
- const starts = []
87
- for (const importer of Object.values(lockfile.importers)) {
88
- for (const [alias, target] of Object.entries({ ...importer.devDependencies, ...importer.dependencies, ...importer.optionalDependencies })) {
89
- if (target.startsWith('link:')) continue
90
- starts.push(target)
91
- if (!(alias in direct)) direct[alias] = target
92
- }
93
- }
94
- Object.assign(root, direct)
95
- const graph = new Map([...nodes].map(([key, { pkg }]) => [key, { key, children: new Map(Object.entries({ ...pkg.dependencies, ...pkg.optionalDependencies })) }]))
96
- const order = [{ children: Object.entries(root), key: '', depth: -1 }, ...walk(graph, starts).map(({ node, depth }) => ({ children: node.children, key: node.key, depth }))]
97
- order.sort((a, b) => a.depth - b.depth || lexCompare(a.key, b.key))
98
- const taken = new Set(Object.keys(lockfile.importers['.']?.specifiers ?? {}))
99
- const links = new Map()
100
- for (const { children } of order) {
101
- for (const [alias, target] of children) {
102
- const where = typeOf(alias)
103
- if (where === undefined || taken.has(alias.toLowerCase())) continue
104
- taken.add(alias.toLowerCase())
105
- if (target?.project !== undefined) links.set(`${where}/${alias}`, target.project)
106
- else if (nodes.has(target)) links.set(`${where}/${alias}`, nodes.get(target).dir)
107
- }
108
- }
109
- return links
110
- }
111
-
112
77
  // `projects` are the named projects by directory, which hoistWorkspacePackages
113
78
  // hoists by name too. pnpm 10 lists their names first among the root's aliases,
114
79
  // a direct dependency of the same name replacing one; a hoisted project takes
@@ -122,7 +87,6 @@ export function hoist(nodes, direct, { hoistPattern, publicHoistPattern }, proje
122
87
  const isPublic = createMatcher(publicHoistPattern ?? [])
123
88
  const isPrivate = createMatcher(hoistPattern ?? [])
124
89
  const typeOf = (alias) => (isPublic(alias) ? 'node_modules' : isPrivate(alias) ? 'node_modules/.pnpm/node_modules' : undefined)
125
- if (major < 10) return hoist9(hoisting, typeOf, projects)
126
90
  if (major >= 12) {
127
91
  const folded = new Map()
128
92
  for (const [id, name] of projects) {
@@ -169,7 +169,7 @@ export function hoistedBuilds(byDir, projects, builds, { hardlinks, keepsModules
169
169
  for (const node of byDir.values()) if (!first.has(idOf(node.key))) first.set(idOf(node.key), node.dir)
170
170
  const dropping = mayDrop(byDir)
171
171
  const childrenOf = (node) => Object.entries({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }).map(([alias, key]) => [alias, first.get(idOf(key))]).filter(([, dir]) => dir !== undefined)
172
- const tops = [...byDir.values()].filter((node) => projects.has(node.modules)).map((node) => node.dir)
172
+ const tops = byDir.values().filter((node) => projects.has(node.modules)).map((node) => node.dir)
173
173
  const reached = reachable(tops, (dir) => childrenOf(byDir.get(dir)).map(([, child]) => child))
174
174
  const built = []
175
175
  for (const [key, copies] of Map.groupBy(byDir.values(), (node) => node.key)) {
@@ -234,7 +234,7 @@ export function hoistedModules(byDir, links, projects, manifests, lockfile) {
234
234
  placedIn.get(modules).push([alias, dir])
235
235
  }
236
236
  for (const { dir, modules, alias } of byDir.values()) add(modules, alias, dir)
237
- const filled = [...projects, ...[...byDir.keys()].map((dir) => `${dir}/node_modules`)]
237
+ const filled = [...projects, ...byDir.keys().map((dir) => `${dir}/node_modules`)]
238
238
  const all = filled.filter((dir) => placedIn.has(dir)).map((dir) => ({ dir, entries: placedIn.get(dir) }))
239
239
  for (const [path, target] of links) {
240
240
  const end = path.lastIndexOf('/node_modules/') + '/node_modules'.length
@@ -251,6 +251,6 @@ export function hoistedModules(byDir, links, projects, manifests, lockfile) {
251
251
  export function prodPackages(lockfile, skipped, directories) {
252
252
  const edges = ({ dependencies, optionalDependencies }) => [...Object.values(dependencies), ...Object.values(optionalDependencies)]
253
253
  const reached = reachable(Object.values(lockfile.importers).flatMap(edges), (key) => edges(lockfile.packages[key]), (key) => key.startsWith('link:') || skipped.has(key))
254
- return new Set([...reached].map((key) => packageIdOf(key, lockfile.packages[key], directories)))
254
+ return new Set(reached.values().map((key) => packageIdOf(key, lockfile.packages[key], directories)))
255
255
  }
256
256
 
package/src/pnpm/hook.js CHANGED
@@ -1,13 +1,14 @@
1
- // pnpm's read-package hook (@pnpm/hooks.read-package-hook), less package
2
- // extensions and a pnpmfile's readPackage, refused elsewhere, and Yarn's
3
- // compatibility database, not reproduced. pnpm runs it on every package and on
4
- // each project's package.json before holding it to its importer.
1
+ // pnpm's read-package hook (@pnpm/hooks.read-package-hook), less a pnpmfile's
2
+ // readPackage, refused elsewhere, and Yarn's compatibility database, not
3
+ // reproduced. pnpm runs it on every package and on each project's
4
+ // package.json before holding it to its importer.
5
5
 
6
6
  import { intersects, satisfies, validRange } from '@preventive/upstream/semver.js'
7
7
  import { relative } from '@preventive/vfs/path.js'
8
8
  import { DeptreeError } from '../error.js'
9
9
  import { checkNesting } from '../manifest.js'
10
10
  import { createMatcher } from '../matcher.js'
11
+ import { extend, extensionsOf, inRange } from './extensions.js'
11
12
 
12
13
  const KINDS = ['dependencies', 'optionalDependencies', 'devDependencies']
13
14
 
@@ -35,16 +36,9 @@ function checkFields(manifest, where) {
35
36
  }
36
37
  }
37
38
 
38
- // semver's satisfies, which throws a TypeError on a version that is neither
39
- // a string nor falsy, as pnpm then fails.
40
- function inParentRange(version, range, where) {
41
- if (version && typeof version !== 'string') throw new DeptreeError('not a string, which pnpm fails on where an override names this package with a range', `${where}.version`)
42
- return satisfies(version, range)
43
- }
44
-
45
39
  // The hook's `dir` is a project's directory, which directory overrides are
46
40
  // written relative to; undefined for a package.
47
- export function createHook({ overrides, ignored, major = 10 }) {
41
+ export function createHook({ overrides, extensions = [], ignored, major = 10 }) {
48
42
  const byName = (list) => Map.groupBy(list, ({ target }) => target.name)
49
43
  const withParent = overrides.filter(({ parent }) => parent !== undefined)
50
44
  const generic = byName(overrides.filter(({ parent, converge }) => parent === undefined && !converge))
@@ -53,19 +47,21 @@ export function createHook({ overrides, ignored, major = 10 }) {
53
47
  return (manifest, where, { dir } = {}) => {
54
48
  checkFields(manifest, where)
55
49
  const copy = structuredClone(checkNesting(manifest, where))
50
+ extend(copy, extensionsOf(extensions, copy, where))
56
51
  if (overrides.length > 0) {
57
- const scoped = byName(withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || inParentRange(copy.version, parent.range, where))))
52
+ const scoped = byName(withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || inRange(copy.version, parent.range, where, 'an override'))))
58
53
  const pick = (list, spec) => mostSpecific((list ?? []).filter(({ target }) => meets(target.range, spec)))
59
54
  const override = (deps, peers) => {
60
- for (const [name, spec] of Object.entries(peers ?? deps)) {
55
+ const given = peers ?? deps
56
+ for (const [name, spec] of Object.entries(given)) {
61
57
  const chosen = pick(scoped.get(name), spec) ?? pick(generic.get(name), spec)
62
58
  const version = converging.get(name)
63
59
  if (chosen === undefined) {
64
- if (version !== undefined && validRange(spec, { loose: true }) !== null && satisfies(version, spec, { loose: true })) (peers ?? deps)[name] = version
60
+ if (version !== undefined && validRange(spec, { loose: true }) !== null && satisfies(version, spec, { loose: true })) given[name] = version
65
61
  continue
66
62
  }
67
63
  if (chosen.spec === '-') {
68
- delete (peers ?? deps)[name]
64
+ delete given[name]
69
65
  if (peers !== undefined && major >= 11) delete copy.peerDependenciesMeta?.[name]
70
66
  continue
71
67
  }
@@ -76,11 +72,7 @@ export function createHook({ overrides, ignored, major = 10 }) {
76
72
  }
77
73
  }
78
74
  for (const kind of KINDS) if (copy[kind] !== undefined) override(copy[kind])
79
- if (copy.peerDependencies !== undefined) {
80
- // pnpm 9 overrides a peer in place whatever the override is.
81
- if (major < 10) override(copy.peerDependencies)
82
- else override(copy.dependencies ??= {}, copy.peerDependencies)
83
- }
75
+ if (copy.peerDependencies !== undefined) override(copy.dependencies ??= {}, copy.peerDependencies)
84
76
  }
85
77
  for (const name of Object.keys(copy.optionalDependencies ?? {})) {
86
78
  if (!isIgnored(name)) continue
@@ -15,10 +15,9 @@ import { checkWorkspace, findProjects, linkedManifest } from './workspace.js'
15
15
  const LIBC = new Set(['glibc', 'musl', 'unknown'])
16
16
 
17
17
  const MISNAMED = ['pnpm-workspaces.yaml', 'pnpm-workspaces.yml', 'pnpm-workspace.yml', '.pnpm-workspace.yaml', '.pnpm-workspace.yml', '.pnpm-workspaces.yaml', '.pnpm-workspaces.yml']
18
- const MISNAMED_9 = ['pnpm-workspace.yml']
19
- function readWorkspaceText(project, major) {
18
+ function readWorkspaceText(project) {
20
19
  const text = readText(project, '/pnpm-workspace.yaml')
21
- const misnamed = text === undefined ? (major < 10 ? MISNAMED_9 : MISNAMED).find((name) => typeOf(project, `/${name}`) === 'file') : undefined
20
+ const misnamed = text === undefined ? MISNAMED.find((name) => typeOf(project, `/${name}`) === 'file') : undefined
22
21
  if (misnamed !== undefined) throw new DeptreeError('pnpm refuses a workspace manifest not named pnpm-workspace.yaml', quote(misnamed))
23
22
  return text
24
23
  }
@@ -37,12 +36,11 @@ function readPatches(project, configured) {
37
36
  return texts
38
37
  }
39
38
 
40
- // pnpm 9 before 9.15.0, and pnpm 12 before 12.8.1, install otherwise in
41
- // places, and are refused.
42
- const SINCE = { 9: '9.15.0', 12: '12.8.1' }
39
+ // pnpm 12 before 12.8.1 installs otherwise in places, and is refused.
40
+ const SINCE = { 12: '12.8.1' }
43
41
  function majorOf(pnpm) {
44
42
  const major = Number(valid(pnpm)?.split('.')[0])
45
- if (major < 9 || major > 12 || !Number.isInteger(major)) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 9, 10, 11 and 12 are`, 'host.pnpm')
43
+ if (major < 10 || major > 12 || !Number.isInteger(major)) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10, 11 and 12 are`, 'host.pnpm')
46
44
  if (major in SINCE && compareVersions(pnpm, SINCE[major]) < 0) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: pnpm ${major} is from ${SINCE[major]} on`, 'host.pnpm')
47
45
  return major
48
46
  }
@@ -93,15 +91,8 @@ function readRoot(project) {
93
91
  }
94
92
 
95
93
  // Where there is no pnpm-workspace.yaml, pnpm 12 writes one whose packages are
96
- // the root package.json's non-empty `workspaces` strings. pnpm 9 takes one that
97
- // sets nothing for `**`.
94
+ // the root package.json's non-empty `workspaces` strings.
98
95
  function workspaceOf(workspace, text, major, root) {
99
- if (major < 10) {
100
- const mapping = workspace !== null && typeof workspace === 'object' && !Array.isArray(workspace)
101
- if (text !== undefined && (workspace == null || (mapping && Object.keys(workspace).length === 0))) return { packages: ['**'] }
102
- if (mapping && !workspace.packages) throw new DeptreeError('pnpm 9 fails on a workspace manifest that sets anything and no packages', 'pnpm-workspace.yaml: packages')
103
- return workspace
104
- }
105
96
  if (major < 12 || text !== undefined) return workspace
106
97
  const listed = root()?.workspaces
107
98
  const packages = Array.isArray(listed) ? listed.filter((pattern) => typeof pattern === 'string' && pattern !== '') : []
@@ -120,7 +111,7 @@ function readInstalls(project, pnpm) {
120
111
  let read
121
112
  const root = () => (read ??= readRoot(project))
122
113
  const installs = pnpmOf(pnpm, root)
123
- const text = readWorkspaceText(project, installs.major)
114
+ const text = readWorkspaceText(project)
124
115
  const workspace = workspaceOf(readWorkspace(text), text, installs.major, root)
125
116
  return { ...installs, workspace, packages: packagesOf(workspace) }
126
117
  }