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

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,273 @@
1
+ // A package's commands, as pnpm reads them to link its bins
2
+ // (@pnpm/package-bins; with pnpm 12, its bin_resolver crate), and which of
3
+ // two of one name in a .bin directory pnpm links.
4
+ //
5
+ // A package's bins are its `bin` — a path, or paths by command — or, with
6
+ // none, every file under `directories.bin` that is not a dotfile or in a
7
+ // dot directory, each by its name. A command that is not a name, or a
8
+ // path that leads out of the package, is passed over, as pnpm 11 passes
9
+ // over one named `.` or `..` or nothing. pnpm 12 reads a package.json as it
10
+ // is, and its bins otherwise: see commands12.
11
+ //
12
+ // Of two commands of one name, pnpm links the one the package of that
13
+ // name has (with pnpm 11 and 12, or npm's `npx`, and pnpm's `pn`, `pnpx`,
14
+ // `pnx` and `pnpm`), else the one of the package whose name sorts last (by
15
+ // `localeCompare`, read here as English; with pnpm 12, the one whose name
16
+ // sorts first by its bytes), else of the later version, else the first it
17
+ // came to.
18
+
19
+ import { compareVersions, valid } from '@preventive/upstream/semver.js'
20
+ import { basename, compareNames, join } from '@preventive/vfs/path.js'
21
+ import { DeptreeError, quote } from '../error.js'
22
+
23
+ // A package whose directory has no package.json is still linked by these
24
+ // names by pnpm 10, to the runtime's binary inside it.
25
+ const RUNTIMES = { __proto__: null, node: 'bin/node', deno: 'deno', bun: 'bun' }
26
+
27
+ // The packages pnpm 11 and 12 take to own a command by a name not their own.
28
+ const OWNERS = { __proto__: null, npx: ['npm'], pn: ['pnpm', '@pnpm/exe'], pnpm: ['@pnpm/exe'], pnpx: ['pnpm', '@pnpm/exe'], pnx: ['pnpm', '@pnpm/exe'] }
29
+
30
+ const collator = new Intl.Collator('en')
31
+ const decoder = new TextDecoder('utf-8', { fatal: true })
32
+
33
+ // The path `rel` names in the package at `dir`, as path.join spells it, or
34
+ // undefined where it is not in the package, as is-subdir tells; the
35
+ // package itself is `dir`, which is `.` for the root project.
36
+ function inPackage(dir, rel, where) {
37
+ if (typeof rel !== 'string') throw new DeptreeError(`${quote(String(rel))} is not a path, which pnpm fails on`, where)
38
+ const path = join(dir, rel)
39
+ if (path.endsWith('/')) throw new DeptreeError(`${quote(rel)} ends in a slash, which is not supported`, where)
40
+ const inside = dir === '.' ? path !== '..' && !path.startsWith('../') : path === dir || path.startsWith(`${dir}/`)
41
+ return inside ? path : undefined
42
+ }
43
+
44
+ // A command that stands for those of a directory whose bins are not known
45
+ // here, which may take any name.
46
+ export const UNKNOWN = { unknown: true }
47
+
48
+ // The files of `files` under `dir`, as tinyglobby's `**` finds them: none
49
+ // a dotfile or in a dot directory, unless `dots`, as pnpm 12's walk finds
50
+ // them. `files` holds paths relative to `base`.
51
+ function filesUnder(files, base, dir, { dots = false } = {}) {
52
+ const prefix = dir === base ? '' : `${dir.slice(base.length + 1)}/`
53
+ const found = []
54
+ for (const [path, file] of files) {
55
+ if (file.data === undefined || !path.startsWith(prefix)) continue
56
+ const rest = path.slice(prefix.length)
57
+ if (!dots && rest.split('/').some((name) => name.startsWith('.'))) continue
58
+ found.push(rest)
59
+ }
60
+ return found
61
+ }
62
+
63
+ // The files found under `root`, each a command by its name. Of two of one
64
+ // name, which wins turns on the order they were found in: tinyglobby lists
65
+ // them in the order the directories are read in.
66
+ function filesAsCommands(found, root, common) {
67
+ const names = found.map((path) => basename(path))
68
+ const counts = new Map()
69
+ for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1)
70
+ return found.map((path, i) => ({ ...common, name: names[i], target: `${root}/${path}`, unordered: counts.get(names[i]) > 1 }))
71
+ }
72
+
73
+ // Whether pnpm takes a package to own a command, which wins it the name.
74
+ // pnpm 11 looks a name up among OWNERS as a plain object's key, and fails
75
+ // on one that Object.prototype has.
76
+ function owns({ name, pkgName, own }, major, where) {
77
+ if (own || name === pkgName) return true
78
+ if (major < 11) return false
79
+ if (major === 11 && name in Object.prototype) throw new DeptreeError(`two bins are named ${quote(name)}, which pnpm 11 fails on`, where)
80
+ return OWNERS[name]?.includes(pkgName) === true
81
+ }
82
+
83
+ // pnpm's runtimeHasNodeDownloaded: whether engines.runtime asks for a Node
84
+ // to download, the first runtime of a list named node deciding. pnpm fails
85
+ // on a list with nothing in it where it reads one, before that.
86
+ function downloadsNode(runtime, where) {
87
+ if (!runtime) return false
88
+ if (!Array.isArray(runtime)) return runtime.name === 'node' && runtime.onFail === 'download'
89
+ for (const item of runtime) {
90
+ if (item === null || item === undefined) throw new DeptreeError('its engines.runtime lists nothing where pnpm reads a runtime, which pnpm fails on', where)
91
+ if (item.name === 'node') return item.onFail === 'download'
92
+ }
93
+ return false
94
+ }
95
+
96
+ // What pnpm 12 takes for a command's name: one encodeURIComponent leaves
97
+ // as it is, or `$`, but neither `.` nor `..`.
98
+ const safeName = (name) => name === '$' || (name !== '.' && name !== '..' && /^[\w\-.!~*'()]+$/u.test(name))
99
+
100
+ // A package's commands as pnpm 12 reads them: a string `bin` names one
101
+ // after the package, where it has a name; an object names each of its
102
+ // string values; any other `bin` but '' names none, and only '' or none
103
+ // at all leaves directories.bin, where it is a string, to name each file
104
+ // under it, dotfiles and those in dot directories among them, by its
105
+ // name. A scoped command drops its scope; a name that is not safe, or a
106
+ // target that is absolute or out of the package, is passed over.
107
+ //
108
+ // pnpm 12 reads a package's own bins off what its store holds of its
109
+ // package.json where it has the package already, which leaves out a null
110
+ // `bin`, and off the package.json where it fetches the package, which
111
+ // keeps one: so a null `bin` beside a directories.bin is refused.
112
+ function commands12(dir, manifest, files, base, where) {
113
+ const name = typeof manifest.name === 'string' ? manifest.name : undefined
114
+ const common = { pkgName: name ?? '', pkgVersion: manifest.version, owner: base }
115
+ const { bin } = manifest
116
+ if (bin === null && typeof manifest.directories?.bin === 'string' && files !== undefined && dir === base) {
117
+ throw new DeptreeError('its bin is null beside a directories.bin, which pnpm 12 links as its store has the package or not', where)
118
+ }
119
+ if (bin !== undefined && bin !== '') {
120
+ const entries = typeof bin === 'string' ? (name === undefined ? [] : [[name, bin]])
121
+ : bin !== null && typeof bin === 'object' && !Array.isArray(bin) ? Object.entries(bin).filter(([, rel]) => typeof rel === 'string') : []
122
+ const commands = []
123
+ for (const [command, rel] of entries) {
124
+ const unscoped = command[0] === '@' && command.includes('/') ? command.slice(command.indexOf('/') + 1) : command
125
+ if (!safeName(unscoped) || rel.startsWith('/')) continue
126
+ const target = inPackage(dir, rel, where)
127
+ if (target !== undefined) commands.push({ ...common, name: unscoped, target })
128
+ }
129
+ return commands
130
+ }
131
+ const binDir = manifest.directories?.bin
132
+ if (typeof binDir !== 'string') return []
133
+ const root = inPackage(dir, binDir, where)
134
+ if (root === undefined || binDir.startsWith('/')) return []
135
+ if (files === undefined) return [UNKNOWN]
136
+ return filesAsCommands(filesUnder(files, base, root, { dots: true }).filter((path) => safeName(basename(path))), root, common)
137
+ }
138
+
139
+ // A package's commands: `dir` is where the package is, `manifest` its
140
+ // package.json, `files` the files of the package holding it (itself, or
141
+ // the one that bundles it), by their paths under `base`. Both are
142
+ // undefined for a directory outside the tree, a project or one a `link:`
143
+ // leads to, whose commands are known only where its package.json names
144
+ // them, and whose files are not fixed.
145
+ export function commandsOf(dir, manifest, files, base, where, major) {
146
+ if (major >= 12) return commands12(dir, manifest, files, base, where)
147
+ const common = { pkgName: manifest.name, pkgVersion: manifest.version, owner: base }
148
+ if (typeof manifest.bin === 'string' && !manifest.name) throw new DeptreeError('it has a bin and no name, which pnpm fails on', where)
149
+ // pnpm looks for the Node it would download from where the package is,
150
+ // and fails where there is none.
151
+ if (downloadsNode(manifest.engines?.runtime, where)) {
152
+ throw new DeptreeError('its engines.runtime has pnpm look for a Node to run its bins with, which is not supported', where)
153
+ }
154
+ if (manifest.bin) {
155
+ const entries = typeof manifest.bin === 'string' ? [[manifest.name, manifest.bin]] : Object.entries(manifest.bin)
156
+ const commands = []
157
+ for (const [command, rel] of entries) {
158
+ const name = command[0] === '@' ? command.slice(command.indexOf('/') + 1) : command
159
+ if (name !== encodeURIComponent(name) && name !== '$') continue
160
+ if (name === '' || name === '.' || name === '..') {
161
+ if (major >= 11) continue
162
+ throw new DeptreeError(`a bin named ${quote(name)} is not supported`, where)
163
+ }
164
+ const target = inPackage(dir, rel, where)
165
+ if (target !== undefined) commands.push({ ...common, name, target })
166
+ }
167
+ return commands
168
+ }
169
+ const binDir = manifest.directories?.bin
170
+ if (!binDir) return []
171
+ const root = inPackage(dir, binDir, where)
172
+ if (root === undefined) return []
173
+ if (files === undefined) return [UNKNOWN]
174
+ return filesAsCommands(filesUnder(files, base, root), root, common)
175
+ }
176
+
177
+ // compareCommandsInConflict, which pnpm keeps the greater of; with pnpm 12,
178
+ // pick_winner, whose ties keep the first.
179
+ export function compare(a, b, where, major) {
180
+ const aOwns = owns(a, major, where)
181
+ const bOwns = owns(b, major, where)
182
+ if (aOwns !== bOwns) return aOwns ? 1 : -1
183
+ if (major >= 12) {
184
+ if (a.pkgName !== b.pkgName) return compareNames(b.pkgName, a.pkgName)
185
+ const versions = [a.pkgVersion, b.pkgVersion].map((version) => (typeof version === 'string' ? valid(version) : null))
186
+ return versions.includes(null) ? 0 : compareVersions(versions[0], versions[1])
187
+ }
188
+ if (a.pkgName !== b.pkgName) {
189
+ 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)
190
+ return collator.compare(a.pkgName, b.pkgName)
191
+ }
192
+ 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)
193
+ return compareVersions(a.pkgVersion, b.pkgVersion)
194
+ }
195
+
196
+ // A package.json as normalize-package-data leaves one, or refuses it,
197
+ // where pnpm reads one with readPackageJson: its name trimmed, and each
198
+ // of its name and version one npm takes.
199
+ export function normalized(manifest, where) {
200
+ const name = manifest.name ? manifest.name : ''
201
+ if (typeof name !== 'string') throw new DeptreeError('its package.json\'s name is not a string, which pnpm fails on', where)
202
+ const trimmed = name.trim()
203
+ const scoped = /^@([^/]+)\/([^/]+)$/u.exec(trimmed)
204
+ const encoded = (part) => part === encodeURIComponent(part)
205
+ const validName = trimmed === '' || (!trimmed.startsWith('.') && trimmed.toLowerCase() !== 'node_modules' && trimmed.toLowerCase() !== 'favicon.ico'
206
+ && ((scoped !== null && encoded(scoped[1]) && encoded(scoped[2])) || (!/[/@\s+%:]/u.test(trimmed) && encoded(trimmed))))
207
+ if (!validName) throw new DeptreeError(`its package.json's name, ${quote(trimmed)}, is one pnpm fails on`, where)
208
+ const version = manifest.version ? valid(manifest.version, { loose: true }) : ''
209
+ if (version === null) throw new DeptreeError(`its package.json's version, ${quote(String(manifest.version))}, is one pnpm fails on`, where)
210
+ return { ...manifest, name: trimmed, version }
211
+ }
212
+
213
+ // The packages a package bundles, as pnpm's readModulesDir finds them in
214
+ // its node_modules: each directory there not named with a leading dot,
215
+ // and each in a scope's directory.
216
+ function bundledIn(files) {
217
+ const names = new Set()
218
+ for (const path of files.keys()) {
219
+ const parts = path.split('/')
220
+ if (parts[0] !== 'node_modules' || parts.length < 3 || parts[1].startsWith('.')) continue
221
+ if (!parts[1].startsWith('@')) names.add(parts[1])
222
+ else if (parts.length > 3) names.add(`${parts[1]}/${parts[2]}`)
223
+ }
224
+ return [...names]
225
+ }
226
+
227
+ export function parseManifest(file, where) {
228
+ try {
229
+ const manifest = JSON.parse(decoder.decode(file.data))
230
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('not an object')
231
+ return manifest
232
+ } catch {
233
+ throw new DeptreeError('a package.json pnpm reads for its bins is not JSON, which pnpm fails on', where)
234
+ }
235
+ }
236
+
237
+ // The commands of the packages `node` bundles. For one with no
238
+ // package.json pnpm 11 reads the bins of the package.json of the nearest
239
+ // directory above it whose publishConfig.directory it is, as far up as the
240
+ // filesystem goes, which is refused.
241
+ export function bundledCommands(node, where, major) {
242
+ const commands = []
243
+ for (const name of bundledIn(node.files)) {
244
+ const here = `${where}: node_modules/${name}`
245
+ const file = node.files.get(`node_modules/${name}/package.json`)
246
+ const dir = `${node.dir}/node_modules/${name}`
247
+ if (file !== undefined) {
248
+ const manifest = parseManifest(file, here)
249
+ commands.push(...commandsOf(dir, major >= 12 ? manifest : normalized(manifest, here), node.files, node.dir, here, major))
250
+ } else if (major >= 12) {
251
+ continue
252
+ } else if (major >= 11) {
253
+ throw new DeptreeError('it bundles a package with no package.json, whose bins pnpm 11 looks for above it', here)
254
+ } else if (name in RUNTIMES) {
255
+ commands.push({ name, target: `${dir}/${RUNTIMES[name]}`, owner: node.dir, own: true, pkgName: '', pkgVersion: '' })
256
+ }
257
+ }
258
+ return commands
259
+ }
260
+
261
+ // Every path the package at `node` and those it bundles name as bins,
262
+ // relative to it, whether pnpm links them or not, where its package.json
263
+ // is `manifest` and its files are `files`: each with the commands that
264
+ // name it and the package name and version each is ranked by.
265
+ export function binsOf(node, manifest, files, major) {
266
+ const where = quote(node.key)
267
+ const bins = new Map()
268
+ for (const { target, name, pkgName, pkgVersion } of [...commandsOf(node.dir, manifest, files, node.dir, where, major), ...bundledCommands({ ...node, files }, where, major)]) {
269
+ const path = target.slice(node.dir.length + 1)
270
+ bins.set(path, [...bins.get(path) ?? [], JSON.stringify([name, pkgName, pkgVersion])].sort())
271
+ }
272
+ return bins
273
+ }
@@ -9,11 +9,23 @@
9
9
  // pnpm 11 escapes a trailing dot or space as well, each made `+`, and then
10
10
  // hashes the name whatever its length; a snapshot of the registry never
11
11
  // ends in either. pnpm 9 hashed with MD5 in base32, which is not done here.
12
+ //
13
+ // pnpm 12 measures and cuts the name by its UTF-8 bytes, back to where a
14
+ // character starts, and takes only an ASCII capital for one; a name not
15
+ // all ASCII, as a `file:` path may have, is the only one that tells.
12
16
 
13
17
  import { quote } from '../error.js'
14
18
  import { sha256Hex } from '../hash.js'
15
19
 
16
20
  const HASHED = 33 // `_` and 32 hex characters
21
+ const encoder = new TextEncoder()
22
+
23
+ // The name cut to `length` units: UTF-16 ones, or for pnpm 12 bytes, as
24
+ // many whole characters as fit in them.
25
+ function cut(filename, length, major) {
26
+ if (major < 12) return filename.slice(0, length)
27
+ return filename.slice(0, encoder.encodeInto(filename, new Uint8Array(length)).read)
28
+ }
17
29
 
18
30
  export async function depPathToFilename(depPath, maxLength, major = 10) {
19
31
  let filename = depPath.replace(/[\\/:*?"<>|#]/gu, '+')
@@ -21,6 +33,8 @@ export async function depPathToFilename(depPath, maxLength, major = 10) {
21
33
  const hashed = filename
22
34
  const trailing = major >= 11 ? /[. ]*$/u.exec(filename)[0].length : 0
23
35
  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)}`
36
+ const length = major >= 12 ? encoder.encode(filename).length : filename.length
37
+ const lower = major >= 12 ? filename.replace(/[A-Z]+/gu, (capitals) => capitals.toLowerCase()) : filename.toLowerCase()
38
+ if (trailing === 0 && length <= maxLength && filename === lower) return filename
39
+ return `${cut(filename, Math.max(maxLength - HASHED, 0), major)}_${(await sha256Hex(hashed, quote(depPath))).slice(0, 32)}`
26
40
  }
@@ -91,7 +91,8 @@ const isWorkspacePath = (spec) => /^(?:[./\\]|~[/\\]|[A-Za-z]:)/u.test(spec)
91
91
  // in it.
92
92
  const within = (parent, child) => child === parent || (parent === '.' ? child !== '..' && !child.startsWith('../') : child.startsWith(`${parent}/`))
93
93
 
94
- function targetName(spec, alias) {
94
+ // The name of the package a specifier asks for, under `alias`.
95
+ export function targetName(spec, alias) {
95
96
  if (spec.startsWith('workspace:')) {
96
97
  const raw = spec.slice('workspace:'.length)
97
98
  const at = raw.lastIndexOf('@')
@@ -106,7 +107,8 @@ function targetName(spec, alias) {
106
107
  return alias
107
108
  }
108
109
 
109
- function versionRange(spec) {
110
+ // The range of the version a specifier asks for.
111
+ export function versionRange(spec) {
110
112
  if (spec.startsWith('workspace:')) {
111
113
  const raw = spec.slice('workspace:'.length)
112
114
  const at = raw.lastIndexOf('@')
package/src/pnpm/graph.js CHANGED
@@ -7,48 +7,68 @@
7
7
  // directory it names, which is no node. Paths here are relative to the
8
8
  // lockfile's directory, the root of the tree.
9
9
 
10
+ import { compareNames } from '@preventive/vfs/path.js'
10
11
  import { DeptreeError, quote } from '../error.js'
11
12
  import { depPathToFilename } from './filename.js'
12
13
 
13
14
  const VIRTUAL_STORE = 'node_modules/.pnpm'
14
15
 
15
- // A target as a path: a node's directory, or where a link leads, which
16
- // may climb out of the lockfile's directory.
17
- function childOf(target, nodes, skipped) {
18
- if (target.startsWith('link:')) return target.slice(5)
19
- if (skipped.has(target)) return undefined
20
- return nodes.get(target).dir
21
- }
16
+ // A target as a path: where a link leads, which may climb out of the
17
+ // lockfile's directory, or the directory of its node in `nodes`; none
18
+ // where it has no node, as a snapshot left out of the install has none.
19
+ // The lockfile reader holds every other target to be a snapshot.
20
+ const childOf = (target, nodes) => (target.startsWith('link:') ? target.slice(5) : nodes.get(target)?.dir)
22
21
 
23
- function childrenOf(targets, nodes, skipped) {
22
+ function childrenOf(targets, nodes) {
24
23
  const children = new Map()
25
24
  for (const [alias, target] of Object.entries(targets)) {
26
- const dir = childOf(target, nodes, skipped)
25
+ const dir = childOf(target, nodes)
27
26
  if (dir !== undefined) children.set(alias, dir)
28
27
  }
29
28
  return children
30
29
  }
31
30
 
31
+ // The graph pnpm 12 hoists from: a node for every snapshot, skipped or
32
+ // not, by its directory, its children skipped or not; and each project's
33
+ // direct dependencies but its `link:`s, skipped or not, the projects in
34
+ // the order of their ids' bytes. `all` holds every snapshot's node.
35
+ function hoistingOf(lockfile, all) {
36
+ const nodes = new Map()
37
+ for (const node of all.values()) {
38
+ nodes.set(node.dir, { dir: node.dir, modules: node.modules, children: childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, all) })
39
+ }
40
+ const direct = new Map()
41
+ for (const id of Object.keys(lockfile.importers).sort(compareNames)) {
42
+ const { devDependencies, dependencies, optionalDependencies } = lockfile.importers[id]
43
+ direct.set(id, new Map([...childrenOf({ ...devDependencies, ...dependencies, ...optionalDependencies }, all)].filter(([, dir]) => nodes.has(dir))))
44
+ }
45
+ return { nodes, direct }
46
+ }
47
+
32
48
  // `nodes` by snapshot key, and `direct`, by project, the children each
33
49
  // project links: devDependencies first, as pnpm spreads them, which is
34
- // the order hoisting walks them in.
50
+ // the order hoisting walks them in; and, for pnpm 12, `hoisting`, the
51
+ // graph it hoists from. No two snapshots pnpm places may have one
52
+ // directory: those it installs, and with pnpm 12, which hoists from them
53
+ // too, those it skips.
35
54
  export async function buildGraph(lockfile, skipped, maxLength, major = 10) {
36
- const nodes = new Map()
55
+ const all = new Map()
37
56
  const keyByDir = new Map()
38
57
  for (const [key, pkg] of Object.entries(lockfile.packages)) {
39
- if (skipped.has(key)) continue
58
+ if (major < 12 && skipped.has(key)) continue
40
59
  const store = `${VIRTUAL_STORE}/${await depPathToFilename(key, maxLength, major)}`
41
60
  const dir = `${store}/node_modules/${pkg.name}`
42
61
  if (keyByDir.has(dir)) throw new DeptreeError(`${quote(keyByDir.get(dir))} and ${quote(key)} would be installed in one directory`, quote(dir))
43
62
  keyByDir.set(dir, key)
44
- nodes.set(key, { key, pkg, name: pkg.name, dir, modules: `${store}/node_modules` })
63
+ all.set(key, { key, pkg, name: pkg.name, dir, modules: `${store}/node_modules` })
45
64
  }
65
+ const nodes = new Map([...all].filter(([key]) => !skipped.has(key)))
46
66
  for (const node of nodes.values()) {
47
- node.children = childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, nodes, skipped)
67
+ node.children = childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, nodes)
48
68
  }
49
69
  const direct = new Map()
50
70
  for (const [id, importer] of Object.entries(lockfile.importers)) {
51
- direct.set(id, childrenOf({ ...importer.devDependencies, ...importer.dependencies, ...importer.optionalDependencies }, nodes, skipped))
71
+ direct.set(id, childrenOf({ ...importer.devDependencies, ...importer.dependencies, ...importer.optionalDependencies }, nodes))
52
72
  }
53
- return { nodes, direct }
73
+ return { nodes, direct, hoisting: major >= 12 ? hoistingOf(lockfile, all) : undefined }
54
74
  }
package/src/pnpm/hoist.js CHANGED
@@ -8,6 +8,8 @@
8
8
  // directories. An alias is taken with its case folded, and the root
9
9
  // project's own aliases are taken before anything, as they were spelled.
10
10
 
11
+ import { compareNames } from '@preventive/vfs/path.js'
12
+ import { DeptreeError, quote } from '../error.js'
11
13
  import { createMatcher } from '../matcher.js'
12
14
 
13
15
  // pnpm's graphWalker and getDependencies: one level at a time, but each
@@ -40,29 +42,36 @@ const lexCompare = (a, b) => (a > b ? 1 : a < b ? -1 : 0)
40
42
  // The aliases hoisted from the graph, walked from `starts`: a Map of each
41
43
  // link's path to its target. `taken` holds the names none may be hoisted
42
44
  // by, each alias looked up in it folded: the root project's own aliases,
43
- // and those hoisted, folded. With pnpm 10, `projects` are named among the
44
- // top's, and hoisted last.
45
- function hoistGraph(nodes, starts, taken, typeOf, projects = new Map()) {
46
- const root = new Map([...projects].map(([id, name]) => [name, { project: id }]))
45
+ // and those hoisted, folded. Of `nodes`, those `installed` may be hoisted.
46
+ // With pnpm 10, `projects` are named among the top's, and hoisted last;
47
+ // with pnpm 12, each is hoisted once the top's are, and takes its name.
48
+ function hoistGraph(nodes, starts, taken, typeOf, { projects = new Map(), installed = nodes, major = 10 } = {}) {
49
+ const named = new Map([...projects].map(([id, name]) => [name, { project: id }]))
50
+ const root = new Map(major < 12 ? named : [])
47
51
  const listed = new Set()
48
52
  for (const [alias, dir] of starts) {
49
53
  if (listed.has(alias)) continue
50
54
  listed.add(alias)
51
55
  root.set(alias, dir)
52
56
  }
57
+ // pnpm 12 orders the nodes of one depth by their directories' names.
58
+ const keyOf = major >= 12 ? (node) => node.modules.slice(0, -'/node_modules'.length) : (node) => node.dir
53
59
  const order = [
54
- { children: root, dir: '', depth: -1 },
55
- ...walk(nodes, starts.map(([, dir]) => dir)).map(({ node, depth }) => ({ children: node.children, dir: node.dir, depth })),
60
+ { children: root, key: '', depth: -1 },
61
+ ...major >= 12 ? [{ children: named, key: '', depth: -1 }] : [],
62
+ ...walk(nodes, starts.map(([, dir]) => dir)).map(({ node, depth }) => ({ children: node.children, key: keyOf(node), depth })),
56
63
  ]
57
- order.sort((a, b) => a.depth - b.depth || lexCompare(a.dir, b.dir))
64
+ order.sort((a, b) => a.depth - b.depth || (major >= 12 ? compareNames(a.key, b.key) : lexCompare(a.key, b.key)))
58
65
  const links = new Map()
59
66
  const hoistedProjects = new Map()
60
67
  for (const { children } of order) {
61
68
  for (const [alias, dir] of children) {
62
69
  const where = typeOf(alias)
63
70
  if (where === undefined || taken.has(alias.toLowerCase())) continue
64
- if (typeof dir === 'object') hoistedProjects.set(`${where}/${alias}`, dir.project)
65
- else if (nodes.has(dir)) {
71
+ if (typeof dir === 'object') {
72
+ if (major >= 12) taken.add(alias.toLowerCase())
73
+ hoistedProjects.set(`${where}/${alias}`, dir.project)
74
+ } else if (installed.has(dir)) {
66
75
  taken.add(alias.toLowerCase())
67
76
  links.set(`${where}/${alias}`, dir)
68
77
  }
@@ -93,14 +102,35 @@ function hoistGraph(nodes, starts, taken, typeOf, projects = new Map()) {
93
102
  // by a package hoisted by it. (It holds back two projects of which one's
94
103
  // name is a directory of the other's, which no two names a package can
95
104
  // have are.)
96
- export function hoist(nodes, direct, { hoistPattern, publicHoistPattern }, projects = new Map(), major = 10) {
105
+ //
106
+ // pnpm 12 hoists from `hoisting`, graph.js's graph of every snapshot,
107
+ // skipped or not, which it walks through those skipped, though none of
108
+ // them is hoisted; its projects' direct dependencies are taken in the
109
+ // order of their ids, and those of the root project but its `link:`s,
110
+ // skipped or not, are taken from the start. Of two projects whose names
111
+ // are one folded, both of which its patterns take, which it hoists turns
112
+ // on an order not known here, which is refused.
113
+ export function hoist(nodes, direct, { hoistPattern, publicHoistPattern }, projects = new Map(), major = 10, hoisting = undefined) {
97
114
  if (hoistPattern === undefined && publicHoistPattern === undefined) return new Map()
98
115
  const isPublic = createMatcher(publicHoistPattern ?? [])
99
116
  const isPrivate = createMatcher(hoistPattern ?? [])
100
117
  const typeOf = (alias) => (isPublic(alias) ? 'node_modules' : isPrivate(alias) ? 'node_modules/.pnpm/node_modules' : undefined)
118
+ if (major >= 12) {
119
+ // Only a project a pattern takes is one pnpm 12 would hoist.
120
+ const folded = new Map()
121
+ for (const [id, name] of projects) {
122
+ if (typeOf(name) === undefined) continue
123
+ const key = name.toLowerCase()
124
+ if (folded.has(key)) throw new DeptreeError(`its name and ${quote(folded.get(key))}'s are one with their case folded, of which pnpm 12 hoists one by an order not known here`, `manifests[${quote(id)}].name`)
125
+ folded.set(key, id)
126
+ }
127
+ const starts = [...hoisting.direct.values()].flatMap((children) => [...children])
128
+ const taken = new Set([...hoisting.direct.get('.')?.keys() ?? []].map((alias) => alias.toLowerCase()))
129
+ return hoistGraph(hoisting.nodes, starts, taken, typeOf, { projects, installed: nodes, major })
130
+ }
101
131
  const starts = [...direct.values()].flatMap((children) => [...children].filter(([, dir]) => nodes.has(dir)))
102
132
  const rootAliases = [...direct.get('.')?.keys() ?? []]
103
- if (major < 11) return hoistGraph(nodes, starts, new Set(rootAliases), typeOf, projects)
133
+ if (major < 11) return hoistGraph(nodes, starts, new Set(rootAliases), typeOf, { projects })
104
134
  const takenByDependencies = new Set(starts.map(([alias]) => alias.toLowerCase()))
105
135
  const hoistedProjects = [...projects].filter(([, name]) => typeOf(name) !== undefined && !takenByDependencies.has(name.toLowerCase()))
106
136
  const taken = new Set([...rootAliases, ...hoistedProjects.map(([, name]) => name)].map((alias) => alias.toLowerCase()))