@preventive/deptree 1.0.0-alpha.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.
@@ -0,0 +1,436 @@
1
+ // What pnpm does to the files its bins run (@pnpm/link-bins, and
2
+ // bin-links' fixBin): no .bin directory is written here, but each file a
3
+ // bin pnpm links runs is left as linking leaves it, executable and, where
4
+ // it starts with a `#!` line that ends in CRLF, with that line ending in
5
+ // LF instead. pnpm 10 gives it mode 0o755, and pnpm 11 adds 0o111 to its
6
+ // mode where that lacks any of it, which for the 0o644 and 0o755 a
7
+ // package's files have here is the same.
8
+ //
9
+ // A package's bins are its `bin` — a path, or paths by command — or, with
10
+ // none, every file under `directories.bin` that is not a dotfile or in a
11
+ // dot directory, each by its name. A command that is not a name, or a
12
+ // path that leads out of the package, is passed over, as pnpm 11 passes
13
+ // over one named `.` or `..` or nothing. pnpm links bins into many .bin
14
+ // directories, and runs fixBin on a file only where its command is the
15
+ // one linked by that name there and the file is there:
16
+ //
17
+ // - each package's own node_modules/.bin, for its children's bins (or,
18
+ // where a child is a `link:`, for whatever is beside it), and for those
19
+ // of the packages it bundles;
20
+ // - node_modules/.pnpm/node_modules/.bin, for what is privately hoisted;
21
+ // - each project's node_modules/.bin, for its direct dependencies' bins,
22
+ // and at the root, where anything is publicly hoisted, for all it holds,
23
+ // a direct dependency's command over a hoisted one's; with pnpm 11 and
24
+ // autoInstallPeers, then for the bins of each peer a direct dependency
25
+ // requires, by names not linked there yet;
26
+ // - where any patch is configured, each package that is patched or has
27
+ // an install script is built, scripts or not, which links its own bins
28
+ // beside its children's in its own .bin before its patch is applied.
29
+ //
30
+ // Of two commands of one name in a directory, pnpm links the one the
31
+ // package of that name has (with pnpm 11, or npm's `npx`, and pnpm's
32
+ // `pn`, `pnpx`, `pnx` and `pnpm`), else the one of the package whose name
33
+ // sorts last (by `localeCompare`, read here as English), else of the
34
+ // later version, else the first it came to. Where that first is by the
35
+ // order a directory is read in, which varies, and a file's mode or text
36
+ // would turn on it, the tree is refused; so it is where that would turn
37
+ // on the commands of a directory outside the tree that are not known
38
+ // here, which may take any name: those of one a `link:` leads to whose
39
+ // package.json is not given (local.js), or of a project or such a
40
+ // directory by the files of its directories.bin. So is a patch that
41
+ // would be applied between two links of a file whose fix it would
42
+ // change: one that makes or removes a file a bin names, or one under a
43
+ // directories.bin, changes a bin file with a CRLF `#!` line, or changes
44
+ // the bins a package.json names, its own or a bundled package's, or the
45
+ // name or version they are ranked by.
46
+
47
+ import { compareVersions, valid } from '@preventive/upstream/semver.js'
48
+ import { basename, join } from '@preventive/vfs/path.js'
49
+ import { DeptreeError, quote } from '../error.js'
50
+
51
+ // A package whose directory has no package.json is still linked by these
52
+ // names by pnpm 10, to the runtime's binary inside it.
53
+ const RUNTIMES = { __proto__: null, node: 'bin/node', deno: 'deno', bun: 'bun' }
54
+
55
+ // The packages pnpm 11 takes to own a command by a name not their own.
56
+ const OWNERS = { __proto__: null, npx: ['npm'], pn: ['pnpm', '@pnpm/exe'], pnpm: ['@pnpm/exe'], pnpx: ['pnpm', '@pnpm/exe'], pnx: ['pnpm', '@pnpm/exe'] }
57
+
58
+ const collator = new Intl.Collator('en')
59
+ const decoder = new TextDecoder('utf-8', { fatal: true })
60
+
61
+ // The path `rel` names in the package at `dir`, as path.join spells it, or
62
+ // undefined where it is not in the package, as is-subdir tells; the
63
+ // package itself is `dir`, which is `.` for the root project.
64
+ function inPackage(dir, rel, where) {
65
+ if (typeof rel !== 'string') throw new DeptreeError(`${quote(String(rel))} is not a path, which pnpm fails on`, where)
66
+ const path = join(dir, rel)
67
+ if (path.endsWith('/')) throw new DeptreeError(`${quote(rel)} ends in a slash, which is not supported`, where)
68
+ const inside = dir === '.' ? path !== '..' && !path.startsWith('../') : path === dir || path.startsWith(`${dir}/`)
69
+ return inside ? path : undefined
70
+ }
71
+
72
+ // A command that stands for those of a directory whose bins are not known
73
+ // here, which may take any name.
74
+ const UNKNOWN = { unknown: true }
75
+
76
+ // The files of `files` under `dir`, as tinyglobby's `**` finds them: none
77
+ // a dotfile or in a dot directory. `files` holds paths relative to `base`.
78
+ function filesUnder(files, base, dir) {
79
+ const prefix = dir === base ? '' : `${dir.slice(base.length + 1)}/`
80
+ const found = []
81
+ for (const [path, file] of files) {
82
+ if (file.data === undefined || !path.startsWith(prefix)) continue
83
+ const rest = path.slice(prefix.length)
84
+ if (rest.split('/').some((name) => name.startsWith('.'))) continue
85
+ found.push(rest)
86
+ }
87
+ return found
88
+ }
89
+
90
+ // Whether pnpm takes a package to own a command, which wins it the name.
91
+ // pnpm 11 looks a name up among OWNERS as a plain object's key, and fails
92
+ // on one that Object.prototype has.
93
+ function owns({ name, pkgName, own }, major, where) {
94
+ if (own || name === pkgName) return true
95
+ if (major < 11) return false
96
+ if (name in Object.prototype) throw new DeptreeError(`two bins are named ${quote(name)}, which pnpm 11 fails on`, where)
97
+ return OWNERS[name]?.includes(pkgName) === true
98
+ }
99
+
100
+ // pnpm's runtimeHasNodeDownloaded: whether engines.runtime asks for a Node
101
+ // to download, the first runtime of a list named node deciding. pnpm fails
102
+ // on a list with nothing in it where it reads one, before that.
103
+ function downloadsNode(runtime, where) {
104
+ if (!runtime) return false
105
+ if (!Array.isArray(runtime)) return runtime.name === 'node' && runtime.onFail === 'download'
106
+ for (const item of runtime) {
107
+ if (item === null || item === undefined) throw new DeptreeError('its engines.runtime lists nothing where pnpm reads a runtime, which pnpm fails on', where)
108
+ if (item.name === 'node') return item.onFail === 'download'
109
+ }
110
+ return false
111
+ }
112
+
113
+ // A package's commands: `dir` is where the package is, `manifest` its
114
+ // package.json, `files` the files of the package holding it (itself, or
115
+ // the one that bundles it), by their paths under `base`. Both are
116
+ // undefined for a directory outside the tree, a project or one a `link:`
117
+ // leads to, whose commands are known only where its package.json names
118
+ // them, and whose files are not fixed.
119
+ function commandsOf(dir, manifest, files, base, where, major) {
120
+ const common = { pkgName: manifest.name, pkgVersion: manifest.version, owner: base }
121
+ if (typeof manifest.bin === 'string' && !manifest.name) throw new DeptreeError('it has a bin and no name, which pnpm fails on', where)
122
+ // pnpm looks for the Node it would download from where the package is,
123
+ // and fails where there is none.
124
+ if (downloadsNode(manifest.engines?.runtime, where)) {
125
+ throw new DeptreeError('its engines.runtime has pnpm look for a Node to run its bins with, which is not supported', where)
126
+ }
127
+ if (manifest.bin) {
128
+ const entries = typeof manifest.bin === 'string' ? [[manifest.name, manifest.bin]] : Object.entries(manifest.bin)
129
+ const commands = []
130
+ for (const [command, rel] of entries) {
131
+ const name = command[0] === '@' ? command.slice(command.indexOf('/') + 1) : command
132
+ if (name !== encodeURIComponent(name) && name !== '$') continue
133
+ if (name === '' || name === '.' || name === '..') {
134
+ if (major >= 11) continue
135
+ throw new DeptreeError(`a bin named ${quote(name)} is not supported`, where)
136
+ }
137
+ const target = inPackage(dir, rel, where)
138
+ if (target !== undefined) commands.push({ ...common, name, target })
139
+ }
140
+ return commands
141
+ }
142
+ const binDir = manifest.directories?.bin
143
+ if (!binDir) return []
144
+ const root = inPackage(dir, binDir, where)
145
+ if (root === undefined) return []
146
+ if (files === undefined) return [UNKNOWN]
147
+ const found = filesUnder(files, base, root)
148
+ // tinyglobby lists them in the order the directories are read in,
149
+ // which decides between two of one name.
150
+ const names = found.map((path) => basename(path))
151
+ return found.map((path, i) => ({ ...common, name: names[i], target: `${root}/${path}`, unordered: names.indexOf(names[i]) !== names.lastIndexOf(names[i]) }))
152
+ }
153
+
154
+ // compareCommandsInConflict, which pnpm keeps the greater of.
155
+ function compare(a, b, where, major) {
156
+ const aOwns = owns(a, major, where)
157
+ const bOwns = owns(b, major, where)
158
+ if (aOwns !== bOwns) return aOwns ? 1 : -1
159
+ if (a.pkgName !== b.pkgName) {
160
+ if (typeof a.pkgName !== 'string' || typeof b.pkgName !== 'string') throw new DeptreeError(`two bins named ${quote(a.name)} are of packages not both named, which pnpm fails on`, where)
161
+ return collator.compare(a.pkgName, b.pkgName)
162
+ }
163
+ if (valid(a.pkgVersion) === null || valid(b.pkgVersion) === null) throw new DeptreeError(`two bins named ${quote(a.name)} are of ${quote(a.pkgName)} at versions pnpm cannot compare, which it fails on`, where)
164
+ return compareVersions(a.pkgVersion, b.pkgVersion)
165
+ }
166
+
167
+ // A package.json as normalize-package-data leaves one, or refuses it,
168
+ // where pnpm reads one with readPackageJson: its name trimmed, and each
169
+ // of its name and version one npm takes.
170
+ function normalized(manifest, where) {
171
+ const name = manifest.name ? manifest.name : ''
172
+ if (typeof name !== 'string') throw new DeptreeError('its package.json\'s name is not a string, which pnpm fails on', where)
173
+ const trimmed = name.trim()
174
+ const scoped = /^@([^/]+)\/([^/]+)$/u.exec(trimmed)
175
+ const encoded = (part) => part === encodeURIComponent(part)
176
+ const validName = trimmed === '' || (!trimmed.startsWith('.') && trimmed.toLowerCase() !== 'node_modules' && trimmed.toLowerCase() !== 'favicon.ico'
177
+ && ((scoped !== null && encoded(scoped[1]) && encoded(scoped[2])) || (!/[/@\s+%:]/u.test(trimmed) && encoded(trimmed))))
178
+ if (!validName) throw new DeptreeError(`its package.json's name, ${quote(trimmed)}, is one pnpm fails on`, where)
179
+ const version = manifest.version ? valid(manifest.version, { loose: true }) : ''
180
+ if (version === null) throw new DeptreeError(`its package.json's version, ${quote(String(manifest.version))}, is one pnpm fails on`, where)
181
+ return { ...manifest, name: trimmed, version }
182
+ }
183
+
184
+ // The packages a package bundles, as pnpm's readModulesDir finds them in
185
+ // its node_modules: each directory there not named with a leading dot,
186
+ // and each in a scope's directory.
187
+ function bundledIn(files) {
188
+ const names = new Set()
189
+ for (const path of files.keys()) {
190
+ const parts = path.split('/')
191
+ if (parts[0] !== 'node_modules' || parts.length < 3 || parts[1].startsWith('.')) continue
192
+ if (!parts[1].startsWith('@')) names.add(parts[1])
193
+ else if (parts.length > 3) names.add(`${parts[1]}/${parts[2]}`)
194
+ }
195
+ return [...names]
196
+ }
197
+
198
+ function parseManifest(file, where) {
199
+ try {
200
+ const manifest = JSON.parse(decoder.decode(file.data).replace(/^/u, ''))
201
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('not an object')
202
+ return manifest
203
+ } catch {
204
+ throw new DeptreeError('a package.json pnpm reads for its bins is not JSON, which pnpm fails on', where)
205
+ }
206
+ }
207
+
208
+ // The commands of the packages `node` bundles. For one with no
209
+ // package.json pnpm 11 reads the bins of the package.json of the nearest
210
+ // directory above it whose publishConfig.directory it is, as far up as the
211
+ // filesystem goes, which is refused.
212
+ function bundledCommands(node, where, major) {
213
+ const commands = []
214
+ for (const name of bundledIn(node.files)) {
215
+ const here = `${where}: node_modules/${name}`
216
+ const file = node.files.get(`node_modules/${name}/package.json`)
217
+ const dir = `${node.dir}/node_modules/${name}`
218
+ if (file !== undefined) {
219
+ commands.push(...commandsOf(dir, normalized(parseManifest(file, here), here), node.files, node.dir, here, major))
220
+ } else if (major >= 11) {
221
+ throw new DeptreeError('it bundles a package with no package.json, whose bins pnpm 11 looks for above it', here)
222
+ } else if (name in RUNTIMES) {
223
+ commands.push({ name, target: `${dir}/${RUNTIMES[name]}`, owner: node.dir, own: true, pkgName: '', pkgVersion: '' })
224
+ }
225
+ }
226
+ return commands
227
+ }
228
+
229
+ // Where the peers pnpm 11 links the bins of into a project's .bin lead:
230
+ // each peer a direct dependency has that is not optional and that its
231
+ // snapshot resolves, by the path of its link beside the dependency, in
232
+ // the order of those paths.
233
+ function peersOf(children, nodes) {
234
+ const byPath = new Map()
235
+ for (const dir of children.values()) {
236
+ const node = nodes.get(dir)
237
+ if (node === undefined) continue
238
+ const { peerDependencies, peerDependenciesMeta, dependencies, optionalDependencies } = node.pkg
239
+ for (const name of Object.keys(peerDependencies)) {
240
+ if (peerDependenciesMeta[name]?.optional || (dependencies[name] === undefined && optionalDependencies[name] === undefined)) continue
241
+ const peer = name === node.name ? node.dir : node.children.get(name)
242
+ if (peer !== undefined) byPath.set(`${node.modules}/${name}`, peer)
243
+ }
244
+ }
245
+ return [...byPath.keys()].sort().map((path) => byPath.get(path))
246
+ }
247
+
248
+ // Whether pnpm builds a package, as its pkgRequiresBuild tells: an
249
+ // install script, a binding.gyp or a .hooks directory.
250
+ const hasInstallScript = (manifest, files) => Boolean((manifest.scripts != null && (manifest.scripts.preinstall || manifest.scripts.install || manifest.scripts.postinstall))
251
+ || files.has('binding.gyp') || [...files.keys()].some((path) => /^\.hooks[\\/]/u.test(path)))
252
+
253
+ // The files pnpm runs fixBin on, by the directory of the package they
254
+ // are in: `nodes` is the graph by directory, each node with its package's
255
+ // `files` and `manifest`; `projects` each project's package.json by its
256
+ // directory, `direct` each project's direct dependencies, `links` every
257
+ // link in the tree, `publicHoist` whether anything is publicly hoisted,
258
+ // `building` whether any patch is configured, `peers` whether peers are
259
+ // installed automatically, and `major` pnpm's major version.
260
+ export function binTargets({ nodes, projects, direct, links, publicHoist, building, peers, major }) {
261
+ const commandCache = new Map()
262
+ const commandsOfDir = (dir, { raw = false } = {}) => {
263
+ const node = nodes.get(dir)
264
+ if (node !== undefined) {
265
+ if (!commandCache.has(dir)) commandCache.set(dir, commandsOf(dir, node.manifest, node.files, dir, quote(node.key), major))
266
+ return commandCache.get(dir)
267
+ }
268
+ // A project, or a directory a `link:` leads to, whose bins are outside
269
+ // the tree but may take a name; one whose package.json is not given
270
+ // (local.js) may take any.
271
+ const manifest = projects.get(dir)
272
+ if (manifest === undefined) return [UNKNOWN]
273
+ const where = `manifests[${quote(dir)}]`
274
+ return commandsOf(dir, raw ? manifest : normalized(manifest, where), undefined, undefined, where, major)
275
+ }
276
+
277
+ // By each file's path in the tree, the package it is in; and of those
278
+ // that may be fixed or not, why.
279
+ const fixed = new Map()
280
+ const contested = new Map()
281
+ // One linking of commands into a directory: `ordered` says whether the
282
+ // order they come in is one pnpm always has, and `blind` whether a
283
+ // command not known here may be among them. It gives back the names
284
+ // linked, and whether others may be.
285
+ const link = (commands, { ordered, blind = false, where }) => {
286
+ const unknown = blind || commands.some((command) => command.unknown)
287
+ const best = new Map()
288
+ for (const command of commands) {
289
+ if (command.unknown) continue
290
+ const tied = best.get(command.name)
291
+ const order = tied === undefined ? 1 : compare(command, tied[0], where, major)
292
+ if (order > 0) best.set(command.name, [command])
293
+ else if (order === 0) tied.push(command)
294
+ }
295
+ for (const tied of best.values()) {
296
+ const unordered = new Set(tied.map(({ target }) => target)).size > 1 && (!ordered || tied.some((command) => command.unordered))
297
+ for (const { target, owner } of unknown || unordered ? tied : tied.slice(0, 1)) {
298
+ if (owner === undefined) continue
299
+ if (unknown) contested.set(target, { owner, why: 'the bins of a directory outside the tree, which are not known here' })
300
+ else if (unordered) contested.set(target, { owner, why: 'the order it reads a directory in, which varies' })
301
+ else fixed.set(target, owner)
302
+ }
303
+ }
304
+ return { names: new Set(best.keys()), unknown }
305
+ }
306
+
307
+ for (const node of nodes.values()) {
308
+ const where = quote(node.key)
309
+ const children = [...node.children.values()]
310
+ const withBins = children.filter((dir) => nodes.get(dir)?.pkg.hasBin).flatMap((dir) => commandsOfDir(dir))
311
+ if (children.every((dir) => nodes.has(dir))) link(withBins, { ordered: true, where })
312
+ else link(children.flatMap((dir) => commandsOfDir(dir)), { ordered: false, where })
313
+ if (node.pkg.bundledDependencies !== undefined) link(bundledCommands(node, where, major), { ordered: false, where })
314
+ if (building && (node.pkg.patchHash !== undefined || hasInstallScript(node.manifest, node.files))) {
315
+ link([...withBins, ...commandsOfDir(node.dir)], { ordered: true, where })
316
+ }
317
+ }
318
+
319
+ const PRIVATE = 'node_modules/.pnpm/node_modules/'
320
+ const hoisted = [...links].filter(([path, dir]) => path.startsWith(PRIVATE) && nodes.get(dir)?.pkg.hasBin)
321
+ link(hoisted.flatMap(([, dir]) => commandsOfDir(dir, { raw: true })), { ordered: true, where: quote(PRIVATE.slice(0, -1)) })
322
+
323
+ for (const [id, children] of direct) {
324
+ const where = `importers[${quote(id)}]`
325
+ let linked
326
+ if (id === '.' && publicHoist) {
327
+ const manifest = projects.get('.')
328
+ const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
329
+ const entries = [...links].filter(([path]) => /^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u.test(path))
330
+ const commands = entries.flatMap(([path, dir]) => commandsOfDir(dir, { raw: true }).map((command) => ({ ...command, direct: own.has(path.slice('node_modules/'.length)) })))
331
+ const names = new Set(commands.filter((command) => command.direct).map(({ name }) => name))
332
+ linked = link([...commands.filter((command) => command.direct), ...commands.filter((command) => !command.direct && !names.has(command.name))], { ordered: false, where })
333
+ } else {
334
+ // pnpm 11 reads the bins only of what the lockfile says has some.
335
+ const dirs = [...children.values()].filter((dir) => major < 11 || (nodes.get(dir)?.pkg.hasBin ?? true))
336
+ linked = link(dirs.flatMap((dir) => commandsOfDir(dir, { raw: true })), { ordered: true, where })
337
+ }
338
+ if (major >= 11 && peers) {
339
+ const commands = peersOf(children, nodes).flatMap((dir) => commandsOfDir(dir, { raw: true }))
340
+ link(commands.filter(({ name }) => !linked.names.has(name)), { ordered: true, blind: linked.unknown, where })
341
+ }
342
+ }
343
+
344
+ return fixedFiles(nodes, fixed, contested)
345
+ }
346
+
347
+ // The files `fixed` has fixBin run on, by the directory of their package.
348
+ // One `contested` may be or not, which is refused, unless it is fixed
349
+ // anyway, is not there, or is one fixBin leaves as it is: executable, with
350
+ // no CRLF `#!` line, and not patched.
351
+ function fixedFiles(nodes, fixed, contested) {
352
+ for (const [target, { owner, why }] of contested) {
353
+ const node = nodes.get(owner)
354
+ const path = target.slice(owner.length + 1)
355
+ const file = node.files.get(path)
356
+ if (fixed.has(target) || file?.data === undefined || (file.mode === 0o755 && !hasCrlfShebang(file.data) && node.pkg.patchHash === undefined)) continue
357
+ throw new DeptreeError(`whether pnpm makes ${quote(path)} executable turns on ${why}`, quote(node.key))
358
+ }
359
+ const byNode = new Map()
360
+ for (const [target, owner] of fixed) {
361
+ const path = target.slice(owner.length + 1)
362
+ if (nodes.get(owner).files.get(path)?.data === undefined) continue
363
+ if (!byNode.has(owner)) byNode.set(owner, new Set())
364
+ byNode.get(owner).add(path)
365
+ }
366
+ return byNode
367
+ }
368
+
369
+ // Every path the package at `node` and those it bundles name as bins,
370
+ // relative to it, whether pnpm links them or not, where its package.json
371
+ // is `manifest` and its files are `files`: each with the commands that
372
+ // name it and the package name and version each is ranked by.
373
+ function binsOf(node, manifest, files, major) {
374
+ const where = quote(node.key)
375
+ const bins = new Map()
376
+ for (const { target, name, pkgName, pkgVersion } of [...commandsOf(node.dir, manifest, files, node.dir, where, major), ...bundledCommands({ ...node, files }, where, major)]) {
377
+ const path = target.slice(node.dir.length + 1)
378
+ bins.set(path, [...bins.get(path) ?? [], JSON.stringify([name, pkgName, pkgVersion])].sort())
379
+ }
380
+ return bins
381
+ }
382
+
383
+ // Whether a file starts with a `#!` line ending in CRLF, as fixBin reads
384
+ // its first 2048 bytes to tell.
385
+ function hasCrlfShebang(data) {
386
+ if (data[0] !== 0x23 || data[1] !== 0x21) return false
387
+ const newline = data.subarray(0, 2048).indexOf(0x0a)
388
+ return newline >= 4 && data[newline - 1] === 0x0d
389
+ }
390
+
391
+ // fixBin on a file: mode 0o755, and a CRLF ending the `#!` line made LF.
392
+ // pnpm reads and writes the file as UTF-8 to do that, which would change
393
+ // one that is not; that is refused.
394
+ export function fixBin(file, where) {
395
+ if (!hasCrlfShebang(file.data)) return { data: file.data, mode: 0o755 }
396
+ try {
397
+ decoder.decode(file.data)
398
+ } catch {
399
+ throw new DeptreeError('a bin with a CRLF `#!` line is not UTF-8, which pnpm would rewrite', where)
400
+ }
401
+ const newline = file.data.indexOf(0x0a)
402
+ const data = new Uint8Array(file.data.length - 1)
403
+ data.set(file.data.subarray(0, newline - 1))
404
+ data.set(file.data.subarray(newline), newline - 1)
405
+ return { data, mode: 0o755 }
406
+ }
407
+
408
+ const BIN_FIELDS = (manifest) => JSON.stringify([manifest.name, manifest.version, manifest.bin, manifest.directories?.bin])
409
+
410
+ // A patch is applied between two times its package's bins are linked,
411
+ // so it may not change what either does: `patched` is the package's files
412
+ // with the patch applied, `targets` those that fixBin is run on. pnpm
413
+ // reads package.json again after it, for the name and version a command
414
+ // is taken by as well as the bins. It gives back the package's
415
+ // package.json, patched, as parsed.
416
+ export function checkPatchOfBins(node, patched, targets, where, major) {
417
+ const file = patched.get('package.json')
418
+ if (file?.data === undefined) throw new DeptreeError('the patch removes package.json', where)
419
+ const manifest = file.data === node.files.get('package.json').data ? node.manifest : parseManifest(file, where)
420
+ if (BIN_FIELDS(manifest) !== BIN_FIELDS(node.manifest)) throw new DeptreeError('the patch changes the name, version or bins package.json gives, which pnpm reads both before and after it', where)
421
+ const was = binsOf(node, node.manifest, node.files, major)
422
+ const is = binsOf(node, manifest, patched, major)
423
+ for (const path of new Set([...was.keys(), ...is.keys()])) {
424
+ if (was.has(path) !== is.has(path)) throw new DeptreeError(`the patch changes whether ${quote(path)} is a bin, which pnpm reads both before and after it`, where)
425
+ if (JSON.stringify(was.get(path)) !== JSON.stringify(is.get(path))) throw new DeptreeError(`the patch changes the commands that name ${quote(path)}, or the name or version they are ranked by, which pnpm reads both before and after it`, where)
426
+ if ((node.files.get(path)?.data !== undefined) !== (patched.get(path)?.data !== undefined)) {
427
+ throw new DeptreeError(`the patch makes or removes ${quote(path)}, which a bin names, and which pnpm links before and after it`, where)
428
+ }
429
+ }
430
+ for (const path of targets) {
431
+ const before = node.files.get(path).data
432
+ const after = patched.get(path).data
433
+ if (before !== after && (hasCrlfShebang(before) || hasCrlfShebang(after))) throw new DeptreeError(`the patch changes ${quote(path)}, a bin with a CRLF \`#!\` line, which pnpm rewrites before and after it`, where)
434
+ }
435
+ return manifest
436
+ }
@@ -0,0 +1,59 @@
1
+ // Checks of a lockfile and of the tree built from it that pnpm does not
2
+ // make, each of something a lockfile pnpm writes always holds to, or a
3
+ // tree it installs always is: where one fails, the lockfile was not
4
+ // written by pnpm as it stands, or the tree would not be one tree
5
+ // everywhere it is installed.
6
+
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { fold } from '../mount.js'
9
+
10
+ // A snapshot is optional exactly where no importer reaches it through
11
+ // dependencies alone, its devDependencies counted among them, as pnpm
12
+ // marks it: one marked otherwise would be left out, or kept, where it
13
+ // should not be.
14
+ export function checkOptional(lockfile) {
15
+ const required = new Set()
16
+ const queue = []
17
+ const reach = (targets) => {
18
+ for (const target of Object.values(targets)) {
19
+ if (target.startsWith('link:') || required.has(target)) continue
20
+ required.add(target)
21
+ queue.push(target)
22
+ }
23
+ }
24
+ for (const importer of Object.values(lockfile.importers)) {
25
+ reach(importer.dependencies)
26
+ reach(importer.devDependencies)
27
+ }
28
+ while (queue.length > 0) reach(lockfile.packages[queue.pop()].dependencies)
29
+ for (const [key, pkg] of Object.entries(lockfile.packages)) {
30
+ if (pkg.optional === required.has(key)) {
31
+ throw new DeptreeError(`marked ${pkg.optional ? 'optional where an importer requires it' : 'required where only optional dependencies reach it'}, which pnpm never writes`, `snapshots[${quote(key)}]`)
32
+ }
33
+ }
34
+ }
35
+
36
+ // macOS's filesystems take a name whatever its case and normalization, so
37
+ // two names that differ only in those are one there, and one would be
38
+ // lost: such a tree is refused where the host is macOS.
39
+ export function checkCollisions(vfs) {
40
+ for (const { path, type } of vfs.walk('/')) {
41
+ if (type !== 'directory') continue
42
+ const folded = new Map()
43
+ for (const name of vfs.readdir(path)) {
44
+ const key = fold(name)
45
+ if (folded.has(key)) throw new DeptreeError(`${quote(folded.get(key))} and ${quote(name)} are one name on macOS`, quote(path))
46
+ folded.set(key, name)
47
+ }
48
+ }
49
+ }
50
+
51
+ // Every link into node_modules leads to a directory in the tree; a link
52
+ // out of it leads to a project or a `link:` directory, which the tree
53
+ // does not hold.
54
+ export function checkLinks(vfs, links) {
55
+ for (const [path, target] of links) {
56
+ if (!target.startsWith('node_modules/') && !target.includes('/node_modules/')) continue
57
+ if (!vfs.isDirectory(`/${path}`)) throw new DeptreeError(`leads to ${quote(target)}, which the tree does not hold`, quote(path))
58
+ }
59
+ }
@@ -0,0 +1,26 @@
1
+ // The directory pnpm 10 gives a snapshot under node_modules/.pnpm, as its
2
+ // depPathToFilename (@pnpm/dependency-path) spells it: the snapshot key
3
+ // with each character a filesystem may refuse made `+`, the parentheses of
4
+ // the peers and the patch made `_` and the last one dropped, and, where
5
+ // that runs past `virtualStoreDirMaxLength` or has a capital in it, cut
6
+ // short and ended with `_` and 32 hex characters of its SHA-256.
7
+ // `a@1.0.0(b@2.0.0)` is `a@1.0.0_b@2.0.0`, `@s/a@1.0.0` `@s+a@1.0.0`.
8
+ //
9
+ // pnpm 11 escapes a trailing dot or space as well, each made `+`, and then
10
+ // hashes the name whatever its length; a snapshot of the registry never
11
+ // ends in either. pnpm 9 hashed with MD5 in base32, which is not done here.
12
+
13
+ import { quote } from '../error.js'
14
+ import { sha256Hex } from '../hash.js'
15
+
16
+ const HASHED = 33 // `_` and 32 hex characters
17
+
18
+ export async function depPathToFilename(depPath, maxLength, major = 10) {
19
+ let filename = depPath.replace(/[\\/:*?"<>|#]/gu, '+')
20
+ if (filename.includes('(')) filename = filename.replace(/\)$/u, '').replace(/\)\(|\(|\)/gu, '_')
21
+ const hashed = filename
22
+ const trailing = major >= 11 ? /[. ]*$/u.exec(filename)[0].length : 0
23
+ if (trailing > 0) filename = `${filename.slice(0, -trailing)}${'+'.repeat(trailing)}`
24
+ if (trailing === 0 && filename.length <= maxLength && filename === filename.toLowerCase()) return filename
25
+ return `${filename.slice(0, Math.max(maxLength - HASHED, 0))}_${(await sha256Hex(hashed, quote(depPath))).slice(0, 32)}`
26
+ }