@preventive/deptree 1.0.0-alpha.1 → 1.0.0-alpha.11

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 (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +325 -0
  8. package/npm.js +7 -0
  9. package/package.json +92 -11
  10. package/pnpm.d.ts +401 -81
  11. package/pnpm.js +4 -9
  12. package/soldeer.d.ts +235 -0
  13. package/soldeer.js +6 -0
  14. package/src/cargo/crate.js +183 -0
  15. package/src/cargo/inputs.js +81 -0
  16. package/src/cargo/members.js +90 -0
  17. package/src/cargo/registry.js +65 -0
  18. package/src/cargo/tree.js +125 -0
  19. package/src/cargo/workspace.js +177 -0
  20. package/src/concurrent.js +32 -0
  21. package/src/error.js +8 -10
  22. package/src/glob.js +55 -0
  23. package/src/hash.js +51 -16
  24. package/src/manifest.js +52 -0
  25. package/src/matcher.js +60 -10
  26. package/src/mount.js +124 -42
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +96 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +202 -322
  41. package/src/pnpm/checks.js +8 -35
  42. package/src/pnpm/commands.js +230 -0
  43. package/src/pnpm/filename.js +19 -16
  44. package/src/pnpm/frozen.js +29 -73
  45. package/src/pnpm/gitignore.js +138 -0
  46. package/src/pnpm/glob.js +65 -0
  47. package/src/pnpm/graph.js +26 -34
  48. package/src/pnpm/hoist.js +96 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +26 -31
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +123 -124
  53. package/src/pnpm/local.js +95 -40
  54. package/src/pnpm/minimatch.js +319 -0
  55. package/src/pnpm/nm-hoist-graph.js +299 -0
  56. package/src/pnpm/nm-hoist.js +149 -0
  57. package/src/pnpm/npm-packlist.js +217 -0
  58. package/src/pnpm/overrides.js +11 -51
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +176 -81
  61. package/src/pnpm/patches.js +18 -25
  62. package/src/pnpm/projects.js +132 -89
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +74 -95
  65. package/src/pnpm/tree.js +216 -237
  66. package/src/pnpm/uptodate.js +16 -28
  67. package/src/pnpm/workspace.js +152 -126
  68. package/src/project.js +56 -0
  69. package/src/soldeer/config.js +63 -0
  70. package/src/soldeer/git.js +52 -0
  71. package/src/soldeer/inputs.js +30 -0
  72. package/src/soldeer/tree.js +83 -0
  73. package/src/soldeer/zip.js +121 -0
  74. package/src/tarball.js +123 -131
  75. package/src/yarn1/bins.js +28 -0
  76. package/src/yarn1/compat.js +67 -0
  77. package/src/yarn1/hoist.js +249 -0
  78. package/src/yarn1/inputs.js +83 -0
  79. package/src/yarn1/manifest.js +64 -0
  80. package/src/yarn1/package.js +206 -0
  81. package/src/yarn1/peers.js +51 -0
  82. package/src/yarn1/requests.js +74 -0
  83. package/src/yarn1/resolve.js +289 -0
  84. package/src/yarn1/settings.js +95 -0
  85. package/src/yarn1/tree.js +219 -0
  86. package/yarn1.d.ts +368 -0
  87. package/yarn1.js +7 -0
  88. package/src/pnpm/npmrc.js +0 -31
  89. /package/{LICENSE → LICENSE-MIT} +0 -0
package/src/pnpm/bins.js CHANGED
@@ -1,235 +1,19 @@
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.
1
+ // The files pnpm's bin linking fixes (@pnpm/link-bins, bin-links' fixBin):
2
+ // no .bin is written, but the file of each command it links by a name is
3
+ // made executable and a CRLF ending its `#!` line made LF. pnpm 10 sets
4
+ // 0o755 and pnpm 11 adds 0o111, as pnpm 12 (its cmd-shim crate) does, which
5
+ // rewrites no `#!` line.
6
+ // Where any patch is configured, pnpm 10 and 11 build each package patched
7
+ // or with an install script, which links its own bins beside its children's
8
+ // before the patch; pnpm 12 links them together, with no build pass. pnpm 9
9
+ // links as pnpm 10 does, but fails on a bin that is a directory.
46
10
 
47
- import { compareVersions, valid } from '@preventive/upstream/semver.js'
48
- import { basename, join } from '@preventive/vfs/path.js'
49
11
  import { DeptreeError, quote } from '../error.js'
12
+ import { crlfShebang, fixShebang } from '../tarball.js'
13
+ import { UNKNOWN, binsOf, bundledCommands, commandsOf, compare, normalized, parseManifest } from './commands.js'
14
+ import { reachable } from './nm-hoist.js'
50
15
 
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))
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.
16
+ // The peers whose bins pnpm 11 links into a project's .bin.
233
17
  function peersOf(children, nodes) {
234
18
  const byPath = new Map()
235
19
  for (const dir of children.values()) {
@@ -245,43 +29,18 @@ function peersOf(children, nodes) {
245
29
  return [...byPath.keys()].sort().map((path) => byPath.get(path))
246
30
  }
247
31
 
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, { normalize = 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, normalize ? normalized(manifest, where) : manifest, undefined, undefined, where, major)
275
- }
32
+ // pnpm's pkgRequiresBuild.
33
+ export const requiresBuild = (manifest, files, major) => Boolean((manifest.scripts != null && (manifest.scripts.preinstall || manifest.scripts.install || manifest.scripts.postinstall))
34
+ || (files.has('binding.gyp') && !(major >= 11 && manifest.gypfile === false)) || files.keys().some((path) => /^\.hooks[\\/]/u.test(path)))
276
35
 
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.
36
+ // `contested` holds the files that may be fixed or not, and why; `ordered`
37
+ // is whether pnpm always comes to the commands in this order; `fixNode`
38
+ // whether pnpm 12 links a project's bins again, which fixes a direct
39
+ // dependency's `node` already linked.
40
+ function linker(major) {
279
41
  const fixed = new Map()
280
42
  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. It gives back the names
283
- // linked, and whether others may be.
284
- const link = (commands, { ordered, where }) => {
43
+ const link = (commands, { ordered, where, fixNode = false }) => {
285
44
  const unknown = commands.some((command) => command.unknown)
286
45
  const best = new Map()
287
46
  for (const command of commands) {
@@ -292,6 +51,8 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
292
51
  else if (order === 0) tied.push(command)
293
52
  }
294
53
  for (const tied of best.values()) {
54
+ // pnpm 11 and 12 link `node` with no fix of its file.
55
+ if (major >= 11 && tied[0].name === 'node' && !(fixNode && tied.every((command) => command.direct !== false))) continue
295
56
  const unordered = new Set(tied.map(({ target }) => target)).size > 1 && (!ordered || tied.some((command) => command.unordered))
296
57
  for (const { target, owner } of unknown || unordered ? tied : tied.slice(0, 1)) {
297
58
  if (owner === undefined) continue
@@ -302,15 +63,62 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
302
63
  }
303
64
  return { names: new Set(best.keys()), unknown }
304
65
  }
66
+ return { fixed, contested, link }
67
+ }
68
+
69
+ // The commands of a directory, read once for each package of `nodes`. A
70
+ // project or `link:` target, outside the tree: its bins may take any name
71
+ // where its package.json is not given (local.js).
72
+ function commandReader(nodes, projects, major) {
73
+ const cache = new Map()
74
+ return (dir, { normalize = false } = {}) => {
75
+ const node = nodes.get(dir)
76
+ if (node !== undefined) {
77
+ if (!cache.has(dir)) cache.set(dir, commandsOf(dir, node.manifest, node.files, dir, quote(node.key), major))
78
+ return cache.get(dir)
79
+ }
80
+ const manifest = projects.get(dir)
81
+ if (manifest === undefined) return [UNKNOWN]
82
+ const where = `manifests[${quote(dir)}]`
83
+ return commandsOf(dir, normalize ? normalized(manifest, where) : manifest, undefined, undefined, where, major)
84
+ }
85
+ }
86
+
87
+ // pnpm's preferDirectCmds for a project of `manifest`: of the commands of
88
+ // `entries`, [alias, directory], those of its own dependencies, then of the
89
+ // others those whose names none of them has.
90
+ function preferOwn(entries, manifest, commandsOfDir) {
91
+ const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
92
+ const commands = entries.flatMap(([alias, dir]) => commandsOfDir(dir).map((command) => ({ ...command, direct: own.has(alias) })))
93
+ const names = new Set(commands.filter((command) => command.direct).map(({ name }) => name))
94
+ return [...commands.filter((command) => command.direct), ...commands.filter((command) => !names.has(command.name))]
95
+ }
96
+
97
+ // The files pnpm runs fixBin on, as sets of paths by package directory.
98
+ // `building` is whether any patch is configured, `peers` autoInstallPeers.
99
+ export function binTargets({ nodes, projects, direct, links, publicHoist, building, peers, major }) {
100
+ const commandsOfDir = commandReader(nodes, projects, major)
101
+ // The lockfile has no hasBin for a directory, whose bins pnpm 12 reads.
102
+ const mayHaveBin = (dir) => nodes.get(dir)?.pkg.hasBin === true || nodes.get(dir)?.pkg.resolution.type === 'directory'
103
+
104
+ const { fixed, contested, link } = linker(major)
305
105
 
306
106
  for (const node of nodes.values()) {
307
107
  const where = quote(node.key)
308
108
  const children = [...node.children.values()]
109
+ if (major >= 12) {
110
+ // The order its children come in is a map's, which varies.
111
+ const commands = children.filter(mayHaveBin).flatMap((dir) => commandsOfDir(dir))
112
+ if (node.pkg.bundledDependencies !== undefined) commands.push(...bundledCommands(node, where, major))
113
+ if (mayHaveBin(node.dir)) commands.push(...commandsOfDir(node.dir))
114
+ link(commands, { ordered: false, where })
115
+ continue
116
+ }
309
117
  const withBins = children.filter((dir) => nodes.get(dir)?.pkg.hasBin).flatMap((dir) => commandsOfDir(dir))
310
118
  if (children.every((dir) => nodes.has(dir))) link(withBins, { ordered: true, where })
311
119
  else link(children.flatMap((dir) => commandsOfDir(dir, { normalize: true })), { ordered: false, where })
312
120
  if (node.pkg.bundledDependencies !== undefined) link(bundledCommands(node, where, major), { ordered: false, where })
313
- if (building && (node.pkg.patchHash !== undefined || hasInstallScript(node.manifest, node.files))) {
121
+ if (building && (node.pkg.patchHash !== undefined || requiresBuild(node.manifest, node.files, major))) {
314
122
  link([...withBins, ...commandsOfDir(node.dir)], { ordered: true, where })
315
123
  }
316
124
  }
@@ -319,46 +127,152 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
319
127
  const hoisted = [...links].filter(([path, dir]) => path.startsWith(PRIVATE) && nodes.get(dir)?.pkg.hasBin)
320
128
  link(hoisted.flatMap(([, dir]) => commandsOfDir(dir)), { ordered: true, where: quote(PRIVATE.slice(0, -1)) })
321
129
 
130
+ const patched = [...nodes.values()].some((node) => node.pkg.patchHash !== undefined)
322
131
  for (const [id, children] of direct) {
323
132
  const where = `importers[${quote(id)}]`
133
+ const peerDirs = major >= 11 && peers ? peersOf(children, nodes) : []
134
+ let relink = major >= 12 && (patched || peerDirs.some(mayHaveBin))
324
135
  let linked
325
136
  if (id === '.' && publicHoist) {
326
137
  const manifest = projects.get('.')
327
138
  const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
328
- const entries = [...links].filter(([path]) => /^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u.test(path))
329
- const commands = entries.flatMap(([path, dir]) => commandsOfDir(dir).map((command) => ({ ...command, direct: own.has(path.slice('node_modules/'.length)) })))
330
- const names = new Set(commands.filter((command) => command.direct).map(({ name }) => name))
331
- linked = link([...commands.filter((command) => command.direct), ...commands.filter((command) => !command.direct && !names.has(command.name))], { ordered: false, where })
139
+ const isOwn = (path) => own.has(path.slice('node_modules/'.length))
140
+ // pnpm 12 links what it hoists of the projects apart, before.
141
+ const entries = [...links].filter(([path, dir]) => /^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u.test(path)
142
+ && (major < 12 || isOwn(path) || mayHaveBin(dir)))
143
+ relink ||= major >= 12 && entries.some(([path, dir]) => !isOwn(path) && mayHaveBin(dir))
144
+ linked = link(preferOwn(entries.map(([path, dir]) => [path.slice('node_modules/'.length), dir]), manifest, commandsOfDir), { ordered: false, where, fixNode: relink })
332
145
  } else {
333
- // pnpm 11 reads the bins only of what the lockfile says has some.
334
- const dirs = [...children.values()].filter((dir) => major < 11 || (nodes.get(dir)?.pkg.hasBin ?? true))
335
- linked = link(dirs.flatMap((dir) => commandsOfDir(dir)), { ordered: true, where })
146
+ const dirs = [...children.values()].filter((dir) => major < 11 || !nodes.has(dir) || (major >= 12 ? mayHaveBin(dir) : nodes.get(dir).pkg.hasBin))
147
+ // pnpm 12 comes to them in the order of a map, which varies.
148
+ linked = link(dirs.flatMap((dir) => commandsOfDir(dir)), { ordered: major < 12, where, fixNode: relink })
336
149
  }
337
150
  if (major >= 11 && peers) {
338
151
  // Where the names linked are not all known, neither are those left.
339
- const commands = peersOf(children, nodes).flatMap((dir) => commandsOfDir(dir))
152
+ const commands = peerDirs.flatMap((dir) => commandsOfDir(dir))
340
153
  link([...commands.filter(({ name }) => !linked.names.has(name)), ...linked.unknown ? [UNKNOWN] : []], { ordered: true, where })
341
154
  }
342
155
  }
343
156
 
344
- return fixedFiles(nodes, fixed, contested)
157
+ return fixedFiles(nodes, fixed, contested, major)
158
+ }
159
+
160
+ // The copies of one package pnpm's build pass makes hardlinks of the one it
161
+ // builds (hoisted.js): what is fixed in that one before, as each copy's own
162
+ // bins are where pnpm fills its node_modules, is in all; and so is what is
163
+ // fixed in any after. Where the copies it may build differ in what is fixed
164
+ // before, so may the outcome. A phase's marks are `before` that, or not, or
165
+ // a function of the package's build saying which. pnpm 11 links no file
166
+ // under a node_modules (`keepsModules`), which each copy keeps its own of.
167
+ function linkCopies(builds, phases, fixed, contested, { keepsModules, major }) {
168
+ const ownerOf = new Map()
169
+ for (const build of builds) {
170
+ if (build.copies.length > 1) for (const copy of build.copies) ownerOf.set(copy, build)
171
+ }
172
+ const groups = new Map()
173
+ const mark = (target, owner, before, why) => {
174
+ const build = ownerOf.get(owner)
175
+ if (build === undefined || (keepsModules && target.slice(owner.length + 1).split('/').includes('node_modules'))) {
176
+ if (why === undefined) fixed.set(target, owner)
177
+ else contested.set(target, { owner, why })
178
+ return
179
+ }
180
+ if (!groups.has(build)) groups.set(build, [])
181
+ groups.get(build).push({ rel: target.slice(owner.length + 1), owner, before: typeof before === 'function' ? before(build) : before, why })
182
+ }
183
+ for (const { fixed: phaseFixed, contested: phaseContested, before } of phases) {
184
+ for (const [target, owner] of phaseFixed) mark(target, owner, before, undefined)
185
+ for (const [target, { owner, why }] of phaseContested) mark(target, owner, before, why)
186
+ }
187
+ for (const [build, marks] of groups) {
188
+ for (const rel of new Set(marks.map((item) => item.rel))) {
189
+ const mine = marks.filter((item) => item.rel === rel && (!item.before || build.candidates.includes(item.owner)))
190
+ const after = mine.filter((item) => !item.before)
191
+ const before = mine.filter((item) => item.before)
192
+ const beforeFixed = new Set(before.filter((item) => item.why === undefined).map(({ owner }) => owner))
193
+ let why
194
+ if (!after.some((item) => item.why === undefined)) {
195
+ why = after.find((item) => item.why !== undefined)?.why ?? before.find((item) => item.why !== undefined)?.why
196
+ if (why === undefined && beforeFixed.size === 0) continue
197
+ if (why === undefined && beforeFixed.size < build.candidates.length) why = `which of its copies pnpm ${major} builds, which turns on its build order and is not followed here`
198
+ }
199
+ for (const copy of build.copies) {
200
+ if (why === undefined) fixed.set(`${copy}/${rel}`, copy)
201
+ else contested.set(`${copy}/${rel}`, { owner: copy, why })
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ // pnpm's hoisted linker links the bins of each node_modules it fills, by
208
+ // what it reads there, as it fills it; then each project's again, with its
209
+ // links in, a command of its own dependencies over any other. `modules` are
210
+ // those node_modules, each with its packages by alias, and its project's
211
+ // package.json where it is a project's. Between the two, where any patch is
212
+ // configured, each package of `builds` links its dependencies' bins and its
213
+ // own (hoisted.js), as the isolated linker's build does.
214
+ export function hoistedBinTargets({ nodes, projects, modules, builds = [], hardlinks = true, keepsModules = false, idOf = (key) => key, major }) {
215
+ const commandsOfDir = commandReader(nodes, projects, major)
216
+ const filling = linker(major)
217
+ const projectsAgain = linker(major)
218
+ for (const { dir, entries, manifest } of modules) {
219
+ const where = quote(dir)
220
+ if (manifest === undefined) {
221
+ filling.link(entries.flatMap(([, target]) => commandsOfDir(target)), { ordered: false, where })
222
+ continue
223
+ }
224
+ projectsAgain.link(preferOwn(entries, manifest, commandsOfDir), { ordered: false, where })
225
+ }
226
+ // A package's dependencies are built first, but for those it is built
227
+ // before or after as they depend on each other.
228
+ // What each snapshot reaches through the copies' dependencies, each taken
229
+ // for the copies of its id.
230
+ const pkgs = new Map([...nodes.values()].map((node) => [idOf(node.key), node.pkg]))
231
+ const edges = (id) => Object.values({ ...pkgs.get(id)?.dependencies, ...pkgs.get(id)?.optionalDependencies }).map(idOf)
232
+ const building = builds.map((build) => {
233
+ const where = quote(build.key)
234
+ const node = nodes.get(build.candidates[0])
235
+ const { fixed, contested, link } = linker(major)
236
+ link([...build.children.filter(([, dir]) => nodes.get(dir)?.pkg.hasBin).flatMap(([, dir]) => commandsOfDir(dir)), ...commandsOfDir(node.dir)], { ordered: true, where })
237
+ if (node.pkg.bundledDependencies !== undefined) link(bundledCommands(node, where, major), { ordered: false, where })
238
+ // Not linked to the others, the copy built alone has its own bins fixed.
239
+ if (!hardlinks && build.candidates.length > 1) {
240
+ for (const [target, owner] of fixed) {
241
+ if (owner !== node.dir) continue
242
+ fixed.delete(target)
243
+ for (const copy of build.candidates) contested.set(`${copy}${target.slice(owner.length)}`, { owner: copy, why: 'which of its copies pnpm 10 builds, which turns on its build order and is not followed here' })
244
+ }
245
+ }
246
+ return { fixed, contested, before: (other) => other !== build && reachable(edges(idOf(other.key)), edges).has(idOf(build.key)) }
247
+ })
248
+ const fixed = new Map()
249
+ const contested = new Map()
250
+ linkCopies(hardlinks ? builds : [], [{ ...filling, before: true }, ...building, { ...projectsAgain, before: false }], fixed, contested, { keepsModules, major })
251
+ return fixedFiles(nodes, fixed, contested, major)
345
252
  }
346
253
 
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) {
254
+ function fixedFiles(nodes, fixed, contested, major) {
255
+ // pnpm 9 and 12 read each linked file's `#!` line. '' is the package.
256
+ const checkDirectory = (node, path) => {
257
+ if (major >= 10 && major < 12) return
258
+ const prefix = `${path}/`
259
+ if (path === '' || node.files.keys().some((name) => name.startsWith(prefix))) {
260
+ throw new DeptreeError(`its bin ${quote(path === '' ? '.' : path)} is a directory, which pnpm ${major} fails on`, quote(node.key))
261
+ }
262
+ }
352
263
  for (const [target, { owner, why }] of contested) {
353
264
  const node = nodes.get(owner)
354
265
  const path = target.slice(owner.length + 1)
266
+ checkDirectory(node, path)
355
267
  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
268
+ if (fixed.has(target) || file?.data === undefined) continue
269
+ if (executableMode(file.mode, major) === file.mode && (major >= 12 || (crlfShebang(file.data) === -1 && node.pkg.patchHash === undefined))) continue
357
270
  throw new DeptreeError(`whether pnpm makes ${quote(path)} executable turns on ${why}`, quote(node.key))
358
271
  }
359
272
  const byNode = new Map()
360
273
  for (const [target, owner] of fixed) {
361
274
  const path = target.slice(owner.length + 1)
275
+ checkDirectory(nodes.get(owner), path)
362
276
  if (nodes.get(owner).files.get(path)?.data === undefined) continue
363
277
  if (!byNode.has(owner)) byNode.set(owner, new Set())
364
278
  byNode.get(owner).add(path)
@@ -366,53 +280,18 @@ function fixedFiles(nodes, fixed, contested) {
366
280
  return byNode
367
281
  }
368
282
 
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
- }
283
+ export const executableMode = (mode, major) => (major >= 11 ? mode | 0o111 : 0o755)
382
284
 
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 }
285
+ // pnpm reads and writes the file as UTF-8, which changes one that is not.
286
+ export function fixBin(file, where, major) {
287
+ const mode = executableMode(file.mode, major)
288
+ return { data: major >= 12 ? file.data : fixShebang(file.data, 'a bin with a CRLF `#!` line is not UTF-8, which pnpm would rewrite', where), mode }
406
289
  }
407
290
 
408
291
  const BIN_FIELDS = (manifest) => JSON.stringify([manifest.name, manifest.version, manifest.bin, manifest.directories?.bin])
409
292
 
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.
293
+ // A patch is applied between two links of its package's bins, so it may not
294
+ // change what either does. It gives back the patched package.json.
416
295
  export function checkPatchOfBins(node, patched, targets, where, major) {
417
296
  const file = patched.get('package.json')
418
297
  if (file?.data === undefined) throw new DeptreeError('the patch removes package.json', where)
@@ -427,10 +306,11 @@ export function checkPatchOfBins(node, patched, targets, where, major) {
427
306
  throw new DeptreeError(`the patch makes or removes ${quote(path)}, which a bin names, and which pnpm links before and after it`, where)
428
307
  }
429
308
  }
309
+ if (major >= 12) return manifest
430
310
  for (const path of targets) {
431
311
  const before = node.files.get(path).data
432
312
  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)
313
+ if (before !== after && (crlfShebang(before) !== -1 || crlfShebang(after) !== -1)) throw new DeptreeError(`the patch changes ${quote(path)}, a bin with a CRLF \`#!\` line, which pnpm rewrites before and after it`, where)
434
314
  }
435
315
  return manifest
436
316
  }