@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/tree.js CHANGED
@@ -1,96 +1,61 @@
1
- // A node_modules tree as pnpm 10 or 11 installs it from a frozen lockfile
2
- // with the isolated linker, held in a Vfs rooted at the lockfile's directory:
3
- // each package's files at node_modules/.pnpm/<its directory>/node_modules/
4
- // <its name>, its dependencies linked beside it, the hoisted aliases in
5
- // node_modules/.pnpm/node_modules and node_modules, and each project's
6
- // direct dependencies in its own node_modules. Every link is relative, as
7
- // pnpm makes them outside Windows, and a `link:` leads where the lockfile
8
- // says whether or not anything is there: the tree holds node_modules and
9
- // nothing else of the projects.
10
- //
11
- // Not written: bins and their shims (node_modules/.bin), though what
12
- // linking them does to the files they run is (bins.js); .modules.yaml,
13
- // .pnpm/lock.yaml and the workspace state, which are pnpm's own; and
14
- // anything a lifecycle script would build. The tree is always the one
15
- // `pnpm install --ignore-scripts` makes: no script is run, a project's or
16
- // a dependency's, whatever the settings allow, and patches are applied all
17
- // the same, as pnpm applies them before any script.
18
- //
19
- // Each package is fetched once, and each snapshot's files composed in
20
- // memory — its package's, patched, bins fixed — before one write of each.
1
+ // The node_modules tree pnpm 9, 10, 11 or 12 installs from a frozen lockfile
2
+ // with the isolated linker and --ignore-scripts, in a Vfs rooted at the
3
+ // lockfile's directory; patched still, as pnpm patches before scripts. Bins are
4
+ // not linked, though what linking does to their files is (bins.js).
21
5
 
22
- import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
23
- import { parseYaml } from '@preventive/lockfile/yaml.js'
24
- import { Vfs, VfsError } from '@preventive/vfs'
6
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
7
+ import { compareVersions } from '@preventive/upstream/semver.js'
8
+ import { Vfs } from '@preventive/vfs'
25
9
  import { dirname, relative } from '@preventive/vfs/path.js'
26
- import { valid } from '@preventive/upstream/semver.js'
27
- import { DeptreeError, quote } from '../error.js'
28
- import { checkNoModules, mount } from '../mount.js'
10
+ import { eachConcurrently } from '../concurrent.js'
11
+ import { DeptreeError, quote, refusalOf } from '../error.js'
12
+ import { checkNoModules, checkWrite, fold, isInside, makeDirs, mount, writeLink } from '../mount.js'
29
13
  import { applyPatch, parsePatch } from '../patch.js'
30
- import { REGISTRY, checkDependencies, checkManifest, fetchPackage, sameBytes, tarballUrl } from '../tarball.js'
31
- import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
14
+ import { checkProject, typeOf } from '../project.js'
15
+ import { NO_ABOUT, REGISTRY, fetchingOf, tarballUrl } from '../tarball.js'
16
+ import { binTargets, checkPatchOfBins, executableMode, fixBin, hoistedBinTargets, requiresBuild } from './bins.js'
32
17
  import { buildGraph } from './graph.js'
33
18
  import { hoist } from './hoist.js'
34
- import { checkLocalOverrides, readDirectoryPackage, readLinked } from './local.js'
19
+ import { hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
20
+ import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
35
21
  import { createPatchedCheck, skippedSnapshots } from './install.js'
36
- import { checkCollisions, checkLinks, checkOptional } from './checks.js'
22
+ import { checkDependencies, fetchPackage } from './package.js'
23
+ import { checkLinks, checkOptional } from './checks.js'
37
24
  import { createHook } from './hook.js'
38
25
  import { listOverrides } from './overrides.js'
39
- import { checkProjects, readManifests, workspaceNames } from './projects.js'
40
- import { readers } from './readers.js'
26
+ import { checkHost, inputsOf, manifestsOf, patchesOf, readLockfile } from './inputs.js'
27
+ import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
41
28
  import { readSettings } from './settings.js'
42
29
  import { checkUpToDate } from './uptodate.js'
43
- import { checkWorkspace, findProjects } from './workspace.js'
30
+ import { checkWorkspace } from './workspace.js'
44
31
 
45
- const CONCURRENCY = 8
46
- const LIBC = new Set(['glibc', 'musl', 'unknown'])
47
-
48
- // The major version of `pnpm`, 10 or 11: what pnpm 11 does differently is
49
- // read by it, where it is.
50
- function majorOf(pnpm) {
51
- const major = Number(valid(pnpm)?.split('.')[0])
52
- if (major !== 10 && major !== 11) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10 and 11 are`, 'host.pnpm')
53
- return major
54
- }
55
-
56
- function checkHost(host) {
57
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with pnpm, node, os, cpu and libc')
58
- for (const key of ['pnpm', 'node', 'os', 'cpu', 'libc']) {
59
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
32
+ // A project inside a node_modules would be inside the tree; on macOS, a
33
+ // node_modules in any case is one.
34
+ function checkProjectsOutside(ids, folded) {
35
+ for (const id of ids) {
36
+ if (id.split('/').some((name) => name === 'node_modules' || (folded && fold(name) === 'node_modules'))) throw new DeptreeError('a project inside node_modules would be inside the tree', `importers[${quote(id)}]`)
60
37
  }
61
- const { pnpm, node, os, libc } = host
62
- const major = majorOf(pnpm)
63
- if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
64
- if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
65
- if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
66
- return { pnpm, major, node, os, cpu: host.cpu, libc }
67
38
  }
68
39
 
69
- // What the lockfile holds that no tree is built for here.
70
- function checkLockfile(lockfile) {
40
+ function checkLockfile(lockfile, folded) {
71
41
  if (lockfile.settings.excludeLinksFromLockfile) throw new DeptreeError('links left out of the lockfile would be left out of the tree', 'settings.excludeLinksFromLockfile')
72
42
  if (lockfile.settings.injectWorkspacePackages) throw new DeptreeError('injected workspace packages are not supported', 'settings.injectWorkspacePackages')
73
43
  if (lockfile.pnpmfileChecksum !== undefined) throw new DeptreeError('a pnpmfile\'s hooks are not run here', 'pnpmfileChecksum')
44
+ checkProjectsOutside(Object.keys(lockfile.importers), folded)
74
45
  for (const [id, importer] of Object.entries(lockfile.importers)) {
75
46
  if (id === '..' || id.startsWith('../')) throw new DeptreeError('a project outside the lockfile\'s directory is not supported', `importers[${quote(id)}]`)
76
- if (id.split('/').includes('node_modules')) throw new DeptreeError('a project inside node_modules would be inside the tree', `importers[${quote(id)}]`)
77
47
  for (const [name, meta] of Object.entries(importer.dependenciesMeta)) {
78
48
  if (meta.injected) throw new DeptreeError('an injected dependency is not supported', `importers[${quote(id)}].dependenciesMeta[${quote(name)}]`)
79
49
  }
80
50
  }
81
51
  }
82
52
 
83
- // A package fetched here comes from the public registry, as upstream
84
- // fetches it: its key is its name and version, and its resolution a
85
- // tarball there with a sha512. One pnpm installs from a directory is one
86
- // a `file:` override names, in `installed`, as local.js reads it, and is
87
- // not patched: pnpm installs its files by hardlinks, so a patch would be
88
- // applied to the directory's own.
53
+ // The lockfile reader holds a directory's key to it.
89
54
  function checkSource(node, installed) {
90
55
  const { key, pkg } = node
91
56
  const { resolution } = pkg
92
57
  if (resolution.type === 'directory') {
93
- if (packageKeyOf(key) !== `${pkg.name}@file:${resolution.directory}` || !installed.has(resolution.directory)) throw new DeptreeError('a dependency on a local directory is supported only where a file: override names it', quote(key))
58
+ if (!installed.has(resolution.directory)) throw new DeptreeError('a dependency on a local directory is supported only where a file: override names it', quote(key))
94
59
  if (pkg.patchHash !== undefined) throw new DeptreeError('a patch to a package pnpm installs from a directory is not supported: it would be applied to the directory\'s own files, which pnpm hardlinks', quote(key))
95
60
  return
96
61
  }
@@ -100,211 +65,196 @@ function checkSource(node, installed) {
100
65
  if (!resolution.integrity?.startsWith('sha512-')) throw new DeptreeError('expected a sha512 integrity', quote(key))
101
66
  }
102
67
 
103
- // What a package's snapshots all have of it, and it is fetched and held to.
104
- const PACKAGE_FIELDS = ['resolution', 'os', 'cpu', 'libc', 'hasBin', 'bundledDependencies']
105
- const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[field]))
106
-
107
- // Each package's files and package.json, by its name and version: a
108
- // package is fetched once however many snapshots it has, a few at a time,
109
- // and the first failure stops the rest from starting. One installed from
110
- // a directory is read from `vfs`, as npm-packlist picks its files.
111
- async function fetchAll(nodes, vfs, major) {
112
- const packages = new Map()
113
- for (const { key, pkg } of nodes.values()) {
114
- const id = packageKeyOf(key)
115
- if (!packages.has(id)) packages.set(id, pkg)
116
- else if (packageFields(packages.get(id)) !== packageFields(pkg)) throw new DeptreeError(`its snapshots differ on what the package is: ${PACKAGE_FIELDS.join(', ')}`, quote(id))
117
- }
118
- const queue = [...packages]
68
+ // By name@version, as the lockfile reader gives a package's snapshots one
69
+ // resolution and manifest.
70
+ async function fetchAll(nodes, project, host, fetching) {
71
+ const packages = new Map([...nodes.values()].map(({ key, pkg }) => [packageKeyOf(key), pkg]))
119
72
  const fetched = new Map()
120
- let failed = false
121
- const worker = async () => {
122
- while (queue.length > 0 && !failed) {
123
- const [id, pkg] = queue.shift()
124
- try {
125
- if (pkg.resolution.type === 'directory') {
126
- const got = readDirectoryPackage(vfs, pkg, quote(id), major)
127
- checkManifest(got.manifest, pkg, quote(id))
128
- fetched.set(id, { ...got, local: true })
129
- } else fetched.set(id, await fetchPackage(pkg, quote(id)))
130
- } catch (error) {
131
- failed = true
132
- throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
133
- }
134
- }
135
- }
136
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
73
+ await eachConcurrently(packages, async ([id, pkg]) => {
74
+ fetched.set(id, pkg.resolution.type === 'directory' ? readDirectoryPackage(project, pkg, quote(id), host) : await fetchPackage(pkg, quote(id), host.major, fetching))
75
+ }, ([id]) => quote(id))
137
76
  return fetched
138
77
  }
139
78
 
140
- // Each node with its package's files and package.json, by its directory:
141
- // its dependencies held to the package.json, as `hook` reads it once for
142
- // each package; and the number of tarballs fetched.
143
- async function fetchNodes(nodes, hook, vfs, major) {
144
- const fetched = await fetchAll(nodes, vfs, major)
79
+ async function fetchNodes(nodes, lockfile, hook, project, host, fetching) {
80
+ const fetched = await fetchAll(nodes, project, host, fetching)
81
+ const fresh = createFreshnessCheck(lockfile, host.major)
145
82
  const byDir = new Map()
146
83
  for (const node of nodes.values()) {
147
84
  const id = packageKeyOf(node.key)
148
85
  const got = fetched.get(id)
149
86
  got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
150
- checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
151
- byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
87
+ checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
88
+ fresh?.(node, got.read)
89
+ byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest, about: got.about ?? NO_ABOUT })
152
90
  }
153
91
  return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
154
92
  }
155
93
 
156
- // A package installed from a directory has one file for each of its
157
- // files, hardlinked into each of its snapshots: fixBin makes it
158
- // executable in all of them, though a CRLF `#!` line it rewrites is
159
- // written as a file of that snapshot's own. By directory, the files a
160
- // snapshot has made executable by another's: `targets` is binTargets's.
161
- function executableElsewhere(byDir, targets) {
162
- const byPackage = new Map()
163
- for (const node of byDir.values()) {
164
- if (node.pkg.resolution.type !== 'directory') continue
165
- const id = packageKeyOf(node.key)
166
- if (!byPackage.has(id)) byPackage.set(id, new Set())
167
- for (const path of targets.get(node.dir) ?? []) byPackage.get(id).add(path)
168
- }
169
- const executable = new Map()
170
- for (const node of byDir.values()) {
171
- if (node.pkg.resolution.type !== 'directory') continue
94
+ // pnpm hardlinks a directory package's files into each of its snapshots, so a
95
+ // file fixBin makes executable in one is so in all (a CRLF `#!` it rewrites
96
+ // stays that snapshot's own), but where pnpm builds the package or, with
97
+ // pnpm 11 and 12, packageImportMethod is neither auto nor hardlink.
98
+ function executableElsewhere(byDir, targets, packageImportMethod, major) {
99
+ if (major >= 11 && packageImportMethod !== 'auto' && packageImportMethod !== 'hardlink') return new Map()
100
+ const shared = [...byDir.values()].filter((node) => node.pkg.resolution.type === 'directory' && !requiresBuild(node.manifest, node.files, major))
101
+ const byPackage = Map.groupBy(shared, (node) => packageKeyOf(node.key))
102
+ return new Map(shared.map((node) => {
172
103
  const own = targets.get(node.dir) ?? new Set()
173
- executable.set(node.dir, new Set([...byPackage.get(packageKeyOf(node.key))].filter((path) => !own.has(path))))
174
- }
175
- return executable
104
+ const all = byPackage.get(packageKeyOf(node.key)).flatMap((other) => [...targets.get(other.dir) ?? []])
105
+ return [node.dir, new Set(all.filter((path) => !own.has(path)))]
106
+ }))
107
+ }
108
+
109
+ // A patch of `patches`, parsed once.
110
+ function parsedPatch(patches, hash) {
111
+ const patch = patches.get(hash)
112
+ patch.parsed ??= parsePatch(patch.text, patch.path)
113
+ return patch
176
114
  }
177
115
 
178
- // A snapshot's files as pnpm leaves them: its package's, the patch the
179
- // snapshot names applied, and what linking bins does to them: fixBin run
180
- // on `targets`, and `executable` made so. `checkPatched` is
181
- // createPatchedCheck's.
182
116
  function compose(node, patches, { targets, executable }, { major, checkPatched }) {
183
117
  const where = quote(node.key)
184
118
  let files = node.files
185
119
  const { patchHash } = node.pkg
186
120
  if (patchHash !== undefined) {
187
- if (!patches.has(patchHash)) throw new DeptreeError(`the patch ${patchHash} is not given`, where)
188
- const patch = patches.get(patchHash)
189
- patch.parsed ??= parsePatch(patch.text, patch.path)
190
- // Once for each package, whatever its snapshots.
121
+ const patch = parsedPatch(patches, patchHash)
191
122
  patch.applied ??= new WeakMap()
192
- if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed))
123
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
193
124
  files = patch.applied.get(files)
194
125
  const manifest = checkPatchOfBins(node, files, targets, where, major)
195
126
  checkPatched?.(manifest, where)
196
127
  }
197
128
  if (targets.size === 0 && executable.size === 0) return files
198
129
  files = new Map(files)
199
- for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
200
- for (const path of executable) files.set(path, { ...files.get(path), mode: 0o755 })
130
+ for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
131
+ for (const path of executable) files.set(path, { ...files.get(path), mode: executableMode(files.get(path).mode, major) })
201
132
  return files
202
133
  }
203
134
 
204
- // Writes a file where nothing is, or the same file is: a write never
205
- // replaces anything else. The tree holds no links yet.
206
- function writeOnce(vfs, path, { data, mode }) {
207
- let there
208
- try {
209
- there = vfs.lstat(path)
210
- } catch (error) {
211
- if (!(error instanceof VfsError)) throw error
212
- vfs.mkdir(dirname(path), { recursive: true })
213
- vfs.writeFile(path, data, { mode })
214
- return true
135
+ function addMade(made, dir) {
136
+ for (let at = dir; !made.has(at) && at !== '/'; at = dirname(at)) made.add(at)
137
+ }
138
+
139
+ // Only this node writes under `dir`, and the tree holds no links yet, so `made`
140
+ // knows every directory there and no write needs a look first, which costs a
141
+ // thrown error where nothing is.
142
+ function writeNode(vfs, dir, files, stats) {
143
+ const root = `/${dir}`
144
+ if (typeOf(vfs, root, false) !== undefined) throw new DeptreeError('would be written over with something else', quote(dir))
145
+ const real = new Set()
146
+ makeDirs(vfs, dir, real)
147
+ const made = new Set([root])
148
+ for (const [path, file] of files) {
149
+ const at = `${root}/${path}`
150
+ if (file.directory) {
151
+ if (!isInside(path)) throw new DeptreeError('is not a path within the package', quote(at.slice(1)))
152
+ makeDirs(vfs, at.slice(1), real)
153
+ addMade(made, at)
154
+ continue
155
+ }
156
+ if (made.has(at)) throw new DeptreeError('would be written over with something else', quote(at.slice(1)))
157
+ const parent = dirname(at)
158
+ if (!made.has(parent)) {
159
+ makeDirs(vfs, parent.slice(1), real)
160
+ addMade(made, parent)
161
+ }
162
+ vfs.writeFile(checkWrite(vfs, dir, path, real), file.data, { mode: file.mode })
163
+ stats.files++
164
+ stats.bytes += file.data.length
215
165
  }
216
- if (there.type === 'file' && there.mode === mode && sameBytes(vfs.readFile(path), data)) return false
217
- throw new DeptreeError('would be written over with something else', quote(path.slice(1)))
218
166
  }
219
167
 
220
- // A link's target spelled from the directory the link is in, as pnpm's
221
- // symlink-dir spells it; a target may climb out of the tree, so both are
222
- // read under as many directories as it climbs.
168
+ // As pnpm's symlink-dir spells it. A target may climb out of the tree, so both
169
+ // are resolved under as many dummy directories as it climbs.
223
170
  function linkTarget(path, target) {
224
- const climbs = target.split('/').filter((segment) => segment === '..').length
225
- const root = '/_'.repeat(climbs)
171
+ const root = '/_'.repeat(target.split('/').filter((segment) => segment === '..').length)
226
172
  return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
227
173
  }
228
174
 
229
- // Every link in the tree, by its path: each node's children beside it and
230
- // itself inside it where it depends on itself, then what is hoisted, then
231
- // each project's direct dependencies, which win over a hoisted alias.
232
- // `byDir` is the graph by directory.
233
- function linksOf(byDir, direct, settings, projects, major) {
175
+ // What no project's dependencies or optionalDependencies reach is dev-only.
176
+ function reachedInProd(importers, nodes, byDir) {
177
+ const reached = new Set(Object.values(importers)
178
+ .flatMap(({ dependencies, optionalDependencies }) => [...Object.values(dependencies), ...Object.values(optionalDependencies)])
179
+ .map((target) => nodes.get(target)?.dir)
180
+ .filter((dir) => byDir.has(dir)))
181
+ for (const dir of reached) {
182
+ for (const child of byDir.get(dir).children.values()) if (byDir.has(child)) reached.add(child)
183
+ }
184
+ return reached
185
+ }
186
+
187
+ function installedOf(node, dev, patches) {
188
+ const { key, name, dir, about, pkg: { version, resolution, optional, patchHash } } = node
189
+ return {
190
+ path: dir,
191
+ key,
192
+ name,
193
+ version,
194
+ integrity: resolution.integrity,
195
+ directory: resolution.directory,
196
+ ...about,
197
+ dev,
198
+ optional,
199
+ patch: patchHash === undefined ? undefined : { hash: patchHash, path: patches.get(patchHash).path },
200
+ }
201
+ }
202
+
203
+ // Later links win: each node's children, then what is hoisted, then each
204
+ // project's direct dependencies.
205
+ function linksOf(byDir, direct, settings, projects, major, hoisting) {
234
206
  const links = new Map()
235
207
  for (const node of byDir.values()) {
236
208
  for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
237
209
  const self = node.children.get(node.name)
238
- if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
210
+ if (major < 12 && byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
239
211
  }
240
- for (const [path, dir] of hoist(byDir, direct, settings, projects, major)) links.set(path, dir)
212
+ for (const [path, dir] of hoist(byDir, direct, settings, projects, major, hoisting)) links.set(path, dir)
241
213
  for (const [id, children] of direct) {
242
214
  for (const [alias, dir] of children) links.set(`${id === '.' ? '' : `${id}/`}node_modules/${alias}`, dir)
243
215
  }
244
216
  return links
245
217
  }
246
218
 
247
- // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
248
- // nothing, as pnpm reads it.
249
- const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : parseYaml(text))
250
-
251
- // The directories of the projects pnpm finds for the workspace at the
252
- // root of `vfs`, which buildPnpmTree takes the package.json of each of.
253
- export function findPnpmProjects(options) {
254
- const { workspace, host, vfs } = options ?? {}
255
- if (workspace !== undefined && typeof workspace !== 'string') throw new TypeError('workspace must be a string, or left out')
256
- if (typeof host?.pnpm !== 'string' || host.pnpm === '') throw new TypeError('host.pnpm must be a non-empty string')
257
- if (['readdir', 'lstat', 'stat'].some((name) => typeof vfs?.[name] !== 'function')) throw new TypeError('vfs must be a Vfs, or have its readdir, lstat and stat')
258
- const major = majorOf(host.pnpm)
259
- const read = readWorkspace(workspace)
260
- if (read !== undefined && (read === null || typeof read !== 'object' || Array.isArray(read))) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
261
- const packages = read?.packages === undefined ? undefined : readers.globs(read.packages, 'pnpm-workspace.yaml: packages')
262
- return findProjects(vfs, packages, major)
263
- }
219
+ // The import methods with which each copy of a package is its own.
220
+ const COPYING = new Set(['copy', 'clone', 'clone-or-copy'])
264
221
 
265
- function readPatchesGiven(patches) {
266
- const entries = patches instanceof Map ? [...patches] : Object.entries(patches ?? {})
267
- for (const [path, text] of entries) {
268
- if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
222
+ // The hoisted layout of pnpm 10 and 11 (hoisted.js): nothing but the packages
223
+ // and links, each copy a parent before what lands in its node_modules, as
224
+ // pnpm keeps only its state in node_modules/.pnpm.
225
+ async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching }) {
226
+ const { major } = host
227
+ const since = (version) => compareVersions(host.pnpm, version) >= 0
228
+ if (!COPYING.has(settings.packageImportMethod)) {
229
+ throw new DeptreeError(`${quote(settings.packageImportMethod)} is not supported with the hoisted layout, which is built only where each copy of a package is its own: with copy, clone or clone-or-copy`, 'packageImportMethod')
269
230
  }
270
- return entries
231
+ const directories = since('11.24.0')
232
+ const { placed, links, projects } = hoistedLayout(lockfile, { autoInstallPeers: settings.autoInstallPeers, skipped, directories, rootLinks: since('11.28.1') })
233
+ if (since('11.28.0')) for (const [path, id] of workspaceHoists(placed, lockfile, settings, names)) links.set(path, id)
234
+ for (const node of placed.values()) checkSource(node, installed)
235
+ const { byDir, tarballs } = await fetchNodes(placed, lockfile, hook, project, host, fetching)
236
+ const linked = readLinked(links, byDir, manifests, project)
237
+ // pnpm builds where any patch is configured, though scripts are ignored.
238
+ const building = Object.keys(settings.patchedDependencies ?? {}).length > 0
239
+ const hardlinks = since('10.21.0')
240
+ const keepsModules = since('11.25.0')
241
+ const idOf = since('11.23.0') ? (key) => packageIdOf(key, lockfile.packages[key], directories) : (key) => key
242
+ const changesOf = (node) => parsedPatch(patched, node.pkg.patchHash).parsed
243
+ const builds = building ? hoistedBuilds(byDir, new Set(projects), (node) => node.pkg.patchHash !== undefined || requiresBuild(node.manifest, node.files, major), { hardlinks, keepsModules, idOf, changesOf, pnpm: host.pnpm }) : []
244
+ const targets = hoistedBinTargets({ nodes: byDir, projects: new Map([...manifests, ...linked]), modules: hoistedModules(byDir, links, projects, manifests, lockfile), builds, hardlinks, keepsModules, idOf, major })
245
+ const prod = prodPackages(lockfile, skipped, directories)
246
+ return { byDir, links, targets, executable: new Map(), tarballs, dev: (node) => !prod.has(packageIdOf(node.key, node.pkg, directories)) }
271
247
  }
272
248
 
273
- export async function buildPnpmTree(options) {
274
- const { lockfile: text, manifests: manifestTexts, workspace, npmrc, patches, host: machine, vfs: into } = options ?? {}
275
- if (typeof text !== 'string') throw new TypeError('lockfile must be the text of pnpm-lock.yaml')
276
- if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
277
- for (const [name, value] of [['workspace', workspace], ['npmrc', npmrc]]) {
278
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
279
- }
280
- const host = checkHost(machine)
281
- const folded = host.os === 'darwin'
282
- // Refused before anything is fetched; mount checks again.
283
- if (into !== undefined) checkNoModules(into, folded)
284
- const { lockfile, env } = parsePnpmLockfile(text)
285
- // pnpm 11 locks config dependencies there, which are refused, and the
286
- // pnpm a project pins, which leaves the tree as it is.
287
- if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
288
- if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
289
- if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
290
- const manifests = readManifests(manifestTexts, lockfile)
291
- const settings = readSettings({ workspace: readWorkspace(workspace), npmrc, manifest: manifests.get('.'), major: host.major })
292
- checkLockfile(lockfile)
293
- checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
294
- const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
295
- const installed = checkLocalOverrides(overrides, into)
296
- const given = await checkUpToDate(lockfile, settings, overrides, readPatchesGiven(patches), host.major)
297
- const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
298
- checkProjects(lockfile, manifests, { hook, host, settings })
299
- checkOptional(lockfile)
300
- const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
301
- const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
302
- const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
249
+ // The isolated layout: each package in node_modules/.pnpm, linked from what
250
+ // needs it and where it is hoisted.
251
+ async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped, fetching }) {
252
+ const { major } = host
253
+ const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
303
254
  for (const node of nodes.values()) checkSource(node, installed)
304
-
305
- const { byDir, tarballs } = await fetchNodes(nodes, hook, into, host.major)
306
- const links = linksOf(byDir, direct, settings, projects, host.major)
307
- const linked = readLinked(links, byDir, manifests, into)
255
+ const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host, fetching)
256
+ const links = linksOf(byDir, direct, settings, names, major, hoisting)
257
+ const linked = readLinked(links, byDir, manifests, project)
308
258
  const targets = binTargets({
309
259
  nodes: byDir,
310
260
  projects: new Map([...manifests, ...linked]),
@@ -313,43 +263,72 @@ export async function buildPnpmTree(options) {
313
263
  publicHoist: settings.publicHoistPattern?.length > 0,
314
264
  building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
315
265
  peers: settings.autoInstallPeers,
316
- major: host.major,
266
+ major,
317
267
  })
318
- const executable = executableElsewhere(byDir, targets)
268
+ const prod = reachedInProd(lockfile.importers, nodes, byDir)
269
+ return { byDir, links, targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major), tarballs, dev: (node) => !prod.has(node.dir) }
270
+ }
271
+
272
+ export async function buildPnpmTree(options) {
273
+ const { project, host: given, vfs: into } = options ?? {}
274
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
275
+ const fetching = fetchingOf(options ?? {})
276
+ if (project !== undefined) checkProject(project)
277
+ const machine = checkHost(given)
278
+ const folded = machine.os === 'darwin'
279
+ // Refused before anything is fetched; mount checks again.
280
+ if (into !== undefined) checkNoModules(into, folded)
281
+ const inputs = inputsOf(options)
282
+ const { lockfile, env } = readLockfile(inputs.lockfile)
283
+ if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
284
+ // Before the project is read for any importer: none leads out of it.
285
+ checkLockfile(lockfile, folded)
286
+ const { manifests, pnpm, major, workspace } = manifestsOf(inputs, lockfile, given.pnpm)
287
+ // Again with the projects given that the lockfile has no importer for.
288
+ checkProjectsOutside(Object.keys(lockfile.importers), folded)
289
+ const host = { pnpm, major, ...machine }
290
+ // The env document locks config dependencies, refused, and the pnpm a project
291
+ // pins, which leaves the tree as it is.
292
+ if (env !== undefined && major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
293
+ if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
294
+ // As pnpm 9, 10 and 11 write the lockfile's own directory.
295
+ const empty = major >= 12 ? Object.keys(lockfile.packages).find((key) => packageKeyOf(key).endsWith('@file:')) : undefined
296
+ if (empty !== undefined) throw new DeptreeError('pnpm 12 refuses as broken a lockfile with `file:` and an empty path', quote(empty))
297
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major, pinned: pinsPnpm(manifests.get('.'), host.pnpm) })
298
+ checkWorkspace(Object.keys(lockfile.importers), settings.packages, major)
299
+ const overrides = listOverrides(settings.overrides, settings.catalogs, major)
300
+ const installed = checkLocalOverrides(overrides, project)
301
+ const patched = await checkUpToDate(lockfile, settings, overrides, patchesOf(inputs, settings.patchedDependencies), major)
302
+ const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major })
303
+ checkProjects(lockfile, manifests, { hook, host, settings, env })
304
+ checkOptional(lockfile)
305
+ const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
306
+ const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
307
+ const hoisted = settings.nodeLinker === 'hoisted'
308
+ const { byDir, links, targets, executable, tarballs, dev } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
319
309
 
320
310
  const vfs = new Vfs()
321
- vfs.mkdir('/node_modules/.pnpm', { recursive: true })
322
- const stats = { projects: manifests.size, snapshots: Object.keys(lockfile.packages).length, installed: nodes.size, skipped: skipped.size, incompatible: incompatible.size, tarballs, patched: 0, files: 0, bytes: 0, links: links.size }
323
- const composing = { major: host.major, checkPatched: createPatchedCheck({ host, settings }) }
311
+ if (!hoisted) makeDirs(vfs, 'node_modules/.pnpm')
312
+ const stats = { projects: manifests.size, snapshots: Object.keys(lockfile.packages).length, installed: byDir.size, skipped: skipped.size, incompatible: incompatible.size, tarballs, patched: [...byDir.values()].filter((node) => node.pkg.patchHash !== undefined).length, files: 0, bytes: 0, links: links.size }
313
+ const listed = []
314
+ const composing = { major, checkPatched: createPatchedCheck({ host, settings }) }
324
315
  // Each node is let go once written, and a package's files with its last.
325
316
  for (const node of byDir.values()) {
326
317
  byDir.delete(node.dir)
327
- if (node.pkg.patchHash !== undefined) stats.patched++
328
318
  try {
329
- vfs.mkdir(`/${node.dir}`, { recursive: true })
330
- for (const [path, file] of compose(node, given, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
331
- if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
332
- else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
333
- stats.files++
334
- stats.bytes += file.data.length
335
- }
336
- }
319
+ writeNode(vfs, node.dir, compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
337
320
  } catch (error) {
338
- if (error instanceof DeptreeError) throw error
339
- throw new DeptreeError(error.message, quote(node.key), { cause: error })
321
+ throw refusalOf(error, quote(node.key))
340
322
  }
323
+ listed.push(installedOf(node, dev(node), patched))
341
324
  }
342
325
  for (const [path, target] of links) {
343
326
  try {
344
- vfs.mkdir(dirname(`/${path}`), { recursive: true })
345
- vfs.symlink(linkTarget(path, target), `/${path}`)
327
+ writeLink(vfs, path, linkTarget(path, target))
346
328
  } catch (error) {
347
329
  throw new DeptreeError(`cannot be linked: ${error.message}`, quote(path), { cause: error })
348
330
  }
349
331
  }
350
332
  checkLinks(vfs, links)
351
- if (folded) checkCollisions(vfs)
352
- if (into === undefined) return { vfs, stats }
353
- mount(vfs, into, folded)
354
- return { vfs: into, stats }
333
+ return { vfs: mount(vfs, into, folded), stats, installed: listed }
355
334
  }