@preventive/deptree 1.0.0-alpha.0 → 1.0.0-alpha.2

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,97 @@
1
+ // The project a tree is built for: a view of the lockfile's directory, by
2
+ // paths from `/` — a Vfs, or anything with its readdir, lstat, stat and
3
+ // readFile, such as one of a directory on disk. It is only read, and only
4
+ // where these say: the files pnpm reads at the root for an install, the
5
+ // package.json of each project and the patches the settings name, where
6
+ // buildPnpmTree is not handed them; the directories findProjects walks;
7
+ // and those a `link:` or `file:` leads to (local.js).
8
+
9
+ import { normalize } from '@preventive/vfs/path.js'
10
+ import { DeptreeError, quote } from '../error.js'
11
+
12
+ export function checkProject(project) {
13
+ if (['readdir', 'lstat', 'stat', 'readFile'].some((name) => typeof project?.[name] !== 'function')) {
14
+ throw new TypeError('project must be a Vfs, or have its readdir, lstat, stat and readFile')
15
+ }
16
+ }
17
+
18
+ // What `path` leads to, links followed, or where `follow` is false, what
19
+ // it is; nothing, where it leads nowhere: to no entry, through a file, or
20
+ // round a loop of links. Any other failure is thrown.
21
+ const NOWHERE = new Set(['ENOENT', 'ENOTDIR', 'ELOOP'])
22
+ export function typeOf(project, path, follow = true) {
23
+ try {
24
+ return (follow ? project.stat(path) : project.lstat(path)).type
25
+ } catch (error) {
26
+ if (NOWHERE.has(error?.code)) return undefined
27
+ throw error
28
+ }
29
+ }
30
+
31
+ // As text handed in would be: a byte order mark kept, for what reads it
32
+ // to drop as pnpm does.
33
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
34
+
35
+ // The bytes of the file at `path`, as a Vfs gives them back.
36
+ export function readBytes(project, path) {
37
+ const bytes = project.readFile(path)
38
+ if (!(bytes instanceof Uint8Array)) throw new TypeError('project.readFile must give back bytes')
39
+ return bytes
40
+ }
41
+
42
+ // The text of the file at `path`, or undefined where nothing is.
43
+ export function readText(project, path, where) {
44
+ const type = typeOf(project, path)
45
+ if (type === undefined) return undefined
46
+ if (type !== 'file') throw new DeptreeError(`${quote(path.slice(1))} is a ${type}, not a file`, where)
47
+ const bytes = readBytes(project, path)
48
+ try {
49
+ return decoder.decode(bytes)
50
+ } catch {
51
+ throw new DeptreeError(`${quote(path.slice(1))} is not UTF-8`, where)
52
+ }
53
+ }
54
+
55
+ // pnpm-workspace.yaml, where it is. pnpm looks for it under other names
56
+ // too, and refuses one it finds so.
57
+ const MISNAMED = ['pnpm-workspaces.yaml', 'pnpm-workspaces.yml', 'pnpm-workspace.yml', '.pnpm-workspace.yaml', '.pnpm-workspace.yml', '.pnpm-workspaces.yaml', '.pnpm-workspaces.yml']
58
+ export function readWorkspaceText(project) {
59
+ const text = readText(project, '/pnpm-workspace.yaml')
60
+ const misnamed = text === undefined ? MISNAMED.find((name) => typeOf(project, `/${name}`) === 'file') : undefined
61
+ if (misnamed !== undefined) throw new DeptreeError('pnpm refuses a workspace manifest not named pnpm-workspace.yaml', quote(misnamed))
62
+ return text
63
+ }
64
+
65
+ // What pnpm reads at the root for an install besides the package.json:
66
+ // pnpm-lock.yaml, which a frozen install cannot do without, and
67
+ // pnpm-workspace.yaml and the .npmrc, where they are.
68
+ export function readRootFiles(project) {
69
+ const lockfile = readText(project, '/pnpm-lock.yaml')
70
+ if (lockfile === undefined) throw new DeptreeError('the project has no pnpm-lock.yaml, which a frozen install cannot do without')
71
+ return { lockfile, workspace: readWorkspaceText(project), npmrc: readText(project, '/.npmrc') }
72
+ }
73
+
74
+ // The text of the package.json of each of `ids`, the projects'
75
+ // directories, by directory.
76
+ export function readManifestTexts(project, ids) {
77
+ const texts = new Map()
78
+ for (const id of ids) {
79
+ texts.set(id, readText(project, id === '.' ? '/package.json' : `/${id}/package.json`, `manifests[${quote(id)}]`))
80
+ }
81
+ return texts
82
+ }
83
+
84
+ // The text of each patch `configured`, patchedDependencies, names, by its
85
+ // path from the lockfile's directory; one that is not there left out.
86
+ // One outside that directory, or absolute, is not in the project, and is
87
+ // refused.
88
+ export function readPatches(project, configured) {
89
+ const texts = new Map()
90
+ for (const [selector, spec] of Object.entries(configured ?? {})) {
91
+ const path = normalize(spec)
92
+ if (path === '..' || path.startsWith('../') || path.startsWith('/')) throw new DeptreeError(`the patch ${quote(spec)} is not in the project: it is outside the lockfile's directory`, `patchedDependencies[${quote(selector)}]`)
93
+ const text = readText(project, `/${path}`, `patches[${quote(path)}]`)
94
+ if (text !== undefined) texts.set(path, text)
95
+ }
96
+ return texts
97
+ }
@@ -3,9 +3,10 @@
3
3
  // (@pnpm/lockfile.verification's satisfiesPackageManifest): where one is
4
4
  // not, pnpm refuses the lockfile as not up to date with that package.json,
5
5
  // and resolves anew without --frozen-lockfile, so it is refused here too.
6
- // Every project has to have an importer and every importer a project: the
7
- // projects pnpm finds are what it installs, and an importer none of them
8
- // is would be left out.
6
+ // Every importer has to be a project: the projects pnpm finds are what it
7
+ // installs, and an importer none of them is would be left out. A project
8
+ // the lockfile has no importer for pnpm gives an empty one, which it is
9
+ // then held to: one with dependencies is refused as not up to date.
9
10
  //
10
11
  // A project's specifiers are its dependencies, devDependencies and
11
12
  // optionalDependencies, and, with autoInstallPeers, the peerDependencies
@@ -30,14 +31,12 @@
30
31
  // --frozen-lockfile, that workspace packages are linked exactly where
31
32
  // their version is in range, are not made; pnpm 11 makes them frozen too.
32
33
 
33
- import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
34
- import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
34
+ import { isExactVersion, satisfies, valid, validRange } from '@preventive/upstream/semver.js'
35
35
  import { DeptreeError, difference, quote } from '../error.js'
36
- import { checkCatalogResolutions, checkLinkTargets, checkLinkedPackages, refOf, sameSpecifier } from './frozen.js'
36
+ import { KINDS, checkCatalogResolutions, checkLinkTargets, checkLinkedPackages, indexProjects, resolvedOf, sameSpecifier } from './frozen.js'
37
37
  import { checkProject } from './install.js'
38
38
  import { validForOldPackages } from './overrides.js'
39
-
40
- const KINDS = ['optionalDependencies', 'dependencies', 'devDependencies']
39
+ import { checkProjectId } from './workspace.js'
41
40
 
42
41
  // A package.json as parsed, as pnpm reads one: a byte order mark dropped,
43
42
  // and an object.
@@ -60,7 +59,10 @@ export function readManifests(manifests, lockfile) {
60
59
  const read = new Map()
61
60
  for (const [id, text] of manifests instanceof Map ? manifests : Object.entries(manifests)) {
62
61
  const where = `manifests[${quote(id)}]`
63
- if (!(id in lockfile.importers)) throw new DeptreeError('the lockfile has no importer for this project, which pnpm refuses a frozen install for', where)
62
+ if (!(id in lockfile.importers)) {
63
+ checkProjectId(id, where)
64
+ lockfile.importers[id] = { specifiers: {}, dependencies: {}, devDependencies: {}, optionalDependencies: {}, dependenciesMeta: {}, linkDirectory: true }
65
+ }
64
66
  read.set(id, readManifest(text, where))
65
67
  }
66
68
  for (const id of Object.keys(lockfile.importers)) {
@@ -102,7 +104,7 @@ function checkKind(importer, kinds, kind, unresolved, major) {
102
104
  if (!locked[name] || !sameSpecifier(importer.specifiers[name], wanted[name], major)) return `${kind}.${name} is not what package.json asks for`
103
105
  const spec = importer.specifiers[name]
104
106
  if (validRange(spec) === null) continue
105
- const version = packageKeyOf(refOf(name, locked[name]))
107
+ const version = resolvedOf(name, locked[name])
106
108
  if (valid(version) !== null && !satisfies(version, spec)) return `${kind}.${name} resolved to ${quote(version)}, which is not in ${quote(spec)}`
107
109
  }
108
110
  return undefined
@@ -148,6 +150,13 @@ function devEnginesPackageManager(devEngines, where) {
148
150
  return { name: engine.name, onFail }
149
151
  }
150
152
 
153
+ // The version of pnpm packageManager names, as pnpm's parsePackageManager
154
+ // reads it, where it names pnpm at an exact version.
155
+ export function pinnedPnpm(packageManager) {
156
+ const version = typeof packageManager === 'string' ? /^pnpm@([^+:@]+)(?:\+.*)?$/u.exec(packageManager)?.[1] : undefined
157
+ return isExactVersion(version) ? version : undefined
158
+ }
159
+
151
160
  // packageManager as pnpm's parsePackageManager reads it, held to be this
152
161
  // pnpm, exactly: pnpm switches to the version it names, and one it cannot
153
162
  // switch to, or another package manager, is refused rather than run over.
@@ -165,8 +174,8 @@ function checkPackageManager(manifest, host, pmOnFail) {
165
174
  }
166
175
  if (packageManager === undefined) return
167
176
  const where = 'manifests["."].packageManager'
168
- const version = typeof packageManager === 'string' ? /^pnpm@([^+:@]+)(?:\+.*)?$/u.exec(packageManager)?.[1] : undefined
169
- if (version === undefined || valid(version) !== version) throw new DeptreeError(`${quote(String(packageManager))} is not pnpm at an exact version`, where)
177
+ const version = pinnedPnpm(packageManager)
178
+ if (version === undefined) throw new DeptreeError(`${quote(String(packageManager))} is not pnpm at an exact version`, where)
170
179
  if (version !== host.pnpm) throw new DeptreeError(`the project is installed by pnpm ${version}, which pnpm switches to, not ${host.pnpm}`, where)
171
180
  }
172
181
 
@@ -175,22 +184,23 @@ function checkPackageManager(manifest, host, pmOnFail) {
175
184
  // project, pnpm 11 takes runtimeOnFail for each one's onFail, and checks a
176
185
  // runtime whose onFail is `error` against the host's before it installs.
177
186
  const RUNTIMES = [['devEngines', 'devDependencies'], ['engines', 'dependencies']]
178
- function checkRuntimes(manifest, where, { host, onFail }) {
187
+ const RUNTIME_NAMES = ['node', 'deno', 'bun']
188
+ function checkRuntimes(manifest, where, { host, root, onFail }) {
179
189
  const checked = new Set()
180
190
  for (const [field, kind] of RUNTIMES) {
181
191
  const runtime = manifest[field]?.runtime
182
192
  if (runtime === undefined || runtime === null) continue
183
193
  const here = `${where}.${field}.runtime`
184
194
  const runtimes = Array.isArray(runtime) ? runtime : [runtime]
185
- for (const name of ['node', 'deno', 'bun']) {
195
+ for (const name of RUNTIME_NAMES) {
186
196
  if (manifest[kind]?.[name]) continue
187
197
  const item = runtimes.find((each) => each?.name === name)
188
198
  if (item !== undefined && (onFail ?? item.onFail) === 'download') throw new DeptreeError(`a ${name} runtime to download is not supported`, here)
189
199
  }
190
- if (host.major < 11 || where !== 'manifests["."]') continue
200
+ if (host.major < 11 || !root) continue
191
201
  if (runtimes.some((item) => item === null || typeof item !== 'object')) throw new DeptreeError('expected a mapping or a list of mappings, which pnpm 11 fails on otherwise', here)
192
202
  for (const item of runtimes) {
193
- if (!['node', 'deno', 'bun'].includes(item.name) || checked.has(item.name)) continue
203
+ if (!RUNTIME_NAMES.includes(item.name) || checked.has(item.name)) continue
194
204
  checked.add(item.name)
195
205
  if ((onFail ?? item.onFail) !== 'error') continue
196
206
  if (item.name !== 'node') throw new DeptreeError(`the ${item.name} it runs on is checked by pnpm 11, and is not known here`, here)
@@ -204,10 +214,12 @@ function checkRuntimes(manifest, where, { host, onFail }) {
204
214
  // and `settings` what its engines are held to.
205
215
  export function checkProjects(lockfile, manifests, { hook, host, settings }) {
206
216
  checkPackageManager(manifests.get('.'), host, settings.pmOnFail)
217
+ let index
207
218
  for (const [id, manifest] of manifests) {
208
219
  const where = `manifests[${quote(id)}]`
220
+ const root = id === '.'
209
221
  checkProject(manifest, where, { host, settings })
210
- checkRuntimes(manifest, where, { host, onFail: id === '.' ? settings.runtimeOnFail : undefined })
222
+ checkRuntimes(manifest, where, { host, root, onFail: root ? settings.runtimeOnFail : undefined })
211
223
  const hooked = hook(manifest, where, { dir: id })
212
224
  const importer = lockfile.importers[id]
213
225
  const reason = mismatch(importer, hooked, settings.autoInstallPeers, host.major, where)
@@ -215,7 +227,8 @@ export function checkProjects(lockfile, manifests, { hook, host, settings }) {
215
227
  checkLinkTargets({ id, manifest: hooked, importer }, where)
216
228
  if (host.major < 11) continue
217
229
  checkCatalogResolutions(importer, lockfile.catalogs, where)
218
- checkLinkedPackages({ manifest: hooked, importer, projects: manifests, linkWorkspacePackages: settings.linkWorkspacePackages }, where)
230
+ index ??= indexProjects(manifests)
231
+ checkLinkedPackages({ manifest: hooked, importer, index, linkWorkspacePackages: settings.linkWorkspacePackages }, where)
219
232
  }
220
233
  }
221
234
 
@@ -61,20 +61,25 @@ function noEnvironment(value, where) {
61
61
  const KEBAB = /^[a-z][\da-z]*(?:-[\da-z]+)*$/u
62
62
  const camelCase = (key) => key.replace(/-+([a-z\d])/gu, (_, char) => char.toUpperCase())
63
63
 
64
+ // pnpm 11 reads an .npmrc for credentials and registries alone: each
65
+ // registry has to be the public one, but one of a project's .npmrc that
66
+ // names a variable is passed over.
67
+ function checkNpmrcRegistries(text) {
68
+ for (const { key, value, line } of parseNpmrc(text)) {
69
+ if ((key !== 'registry' && !/^@[^:]+:registry$/u.test(key)) || fromEnvironment(value)) continue
70
+ const where = `.npmrc:${line}: ${key}`
71
+ checkRegistry(plain(value, where), where)
72
+ }
73
+ }
74
+
64
75
  // An .npmrc's settings by name, each written once, or once with `[]` each
65
76
  // time, and whether any line takes something from the environment. A
66
77
  // registry for a scope has to be the public one.
67
- // pnpm 11 reads an .npmrc for credentials and registries alone, and passes
68
- // over a registry of a project's .npmrc that names a variable.
69
- function fromNpmrc(text, major) {
78
+ function fromNpmrc(text) {
70
79
  const settings = new Map()
71
80
  let environment = false
72
81
  for (const { key, value, list, line } of parseNpmrc(text)) {
73
82
  const where = `.npmrc:${line}: ${key}`
74
- if (major >= 11) {
75
- if ((key === 'registry' || /^@[^:]+:registry$/u.test(key)) && !fromEnvironment(value)) checkRegistry(plain(value, where), where)
76
- continue
77
- }
78
83
  if (/^@[^:]+:registry$/u.test(key)) {
79
84
  checkRegistry(plain(noEnvironment(value, where), where), where)
80
85
  continue
@@ -136,14 +141,15 @@ function fromWorkspace(workspace, major) {
136
141
  // The settings as pnpm 10 derives what it installs by: `hoist: false`
137
142
  // drops the private pattern, `shamefullyHoist` sets or drops the public
138
143
  // one, and an empty public pattern is none. A pattern left undefined is
139
- // not hoisted to at all.
140
- function derive(get, os) {
144
+ // not hoisted to at all. virtualStoreDirMaxLength is 60 by default on
145
+ // Windows alone, which is refused (tree.js's checkHost).
146
+ function derive(get) {
141
147
  const shamefullyHoist = get('shamefullyHoist')
142
148
  let publicHoistPattern = get('publicHoistPattern') ?? []
143
149
  if (shamefullyHoist === true) publicHoistPattern = ['*']
144
150
  else if (shamefullyHoist === false || (publicHoistPattern.length === 1 && publicHoistPattern[0] === '')) publicHoistPattern = undefined
145
151
  return {
146
- virtualStoreDirMaxLength: get('virtualStoreDirMaxLength') ?? (os === 'win32' ? 60 : 120),
152
+ virtualStoreDirMaxLength: get('virtualStoreDirMaxLength') ?? 120,
147
153
  hoistPattern: get('hoist') === false ? undefined : get('hoistPattern') ?? ['*'],
148
154
  publicHoistPattern,
149
155
  hoistWorkspacePackages: get('hoistWorkspacePackages') ?? true,
@@ -175,7 +181,7 @@ function catalogsOf(catalog, catalogs = {}) {
175
181
  }
176
182
 
177
183
  // Each layer over the one before, as `derive` has them.
178
- function settle(layers, manifest, os) {
184
+ function settle(layers, manifest) {
179
185
  const values = new Map()
180
186
  for (const layer of layers) {
181
187
  for (const [name, { value, where, read: { kind, check } }] of layer) {
@@ -188,22 +194,29 @@ function settle(layers, manifest, os) {
188
194
  values.set(name, read)
189
195
  }
190
196
  }
191
- return derive((name) => values.get(name), os)
197
+ return derive((name) => values.get(name))
192
198
  }
193
199
 
194
200
  // `workspace` is pnpm-workspace.yaml as parsed and `npmrc` the text of the
195
201
  // .npmrc, either of which may be undefined; `manifest` the root
196
- // package.json as parsed. `os` is the host's, which one default depends
197
- // on. Overrides that name nothing are none, and leave those below them.
198
- export function readSettings({ workspace, npmrc, manifest, os, major = 10 }) {
199
- const rc = npmrc === undefined ? { settings: new Map(), environment: false } : fromNpmrc(npmrc, major)
200
- // pnpm 11 reads no setting from the package.json, its `resolutions` none.
201
- const rest = [workspace === undefined ? new Map() : fromWorkspace(workspace, major), major >= 11 ? new Map() : fromManifest(manifest)]
202
- const settings = settle([rc.settings, ...rest], manifest, os)
203
- if (rc.environment && JSON.stringify(settings) !== JSON.stringify(settle(rest, manifest, os))) {
202
+ // package.json as parsed. Overrides that name nothing are none, and leave
203
+ // those below them.
204
+ export function readSettings({ workspace, npmrc, manifest, major = 10 }) {
205
+ const fromYaml = () => (workspace === undefined ? new Map() : fromWorkspace(workspace, major))
206
+ // pnpm 11 reads its settings from pnpm-workspace.yaml alone, and none
207
+ // from the package.json, its `resolutions` none.
208
+ if (major >= 11) {
209
+ if (npmrc !== undefined) checkNpmrcRegistries(npmrc)
210
+ const settings = settle([fromYaml()], manifest)
211
+ settings.nodeVersion ??= runtimeNode(manifest, settings.runtimeOnFail)
212
+ return settings
213
+ }
214
+ const rc = npmrc === undefined ? { settings: new Map(), environment: false } : fromNpmrc(npmrc)
215
+ const rest = [fromYaml(), fromManifest(manifest)]
216
+ const settings = settle([rc.settings, ...rest], manifest)
217
+ if (rc.environment && JSON.stringify(settings) !== JSON.stringify(settle(rest, manifest))) {
204
218
  throw new DeptreeError('a line takes a value from the environment, which pnpm drops the whole file for where it is unset, and the file sets what would change the tree', '.npmrc')
205
219
  }
206
- if (major >= 11) settings.nodeVersion ??= runtimeNode(manifest, settings.runtimeOnFail)
207
220
  return settings
208
221
  }
209
222
 
package/src/pnpm/tree.js CHANGED
@@ -20,44 +20,28 @@
20
20
  // memory — its package's, patched, bins fixed — before one write of each.
21
21
 
22
22
  import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
23
- import { parseYaml } from '@preventive/lockfile/yaml.js'
24
- import { Vfs } from '@preventive/vfs'
23
+ import { Vfs, VfsError } from '@preventive/vfs'
25
24
  import { dirname, relative } from '@preventive/vfs/path.js'
26
- import { valid } from '@preventive/upstream/semver.js'
27
25
  import { DeptreeError, quote } from '../error.js'
28
26
  import { checkNoModules, mount } from '../mount.js'
29
27
  import { applyPatch, parsePatch } from '../patch.js'
30
- import { REGISTRY, checkDependencies, fetchPackage, tarballUrl } from '../tarball.js'
28
+ import { REGISTRY, checkDependencies, checkManifest, fetchPackage, sameBytes, tarballUrl } from '../tarball.js'
31
29
  import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
32
30
  import { buildGraph } from './graph.js'
33
31
  import { hoist } from './hoist.js'
34
- import { checkLocalOverrides, readLinked } from './local.js'
35
- import { checkPatchedEngines, createCheck, skippedSnapshots } from './install.js'
32
+ import { checkLocalOverrides, readDirectoryPackage, readLinked } from './local.js'
33
+ import { createPatchedCheck, skippedSnapshots } from './install.js'
36
34
  import { checkCollisions, checkLinks, checkOptional } from './checks.js'
37
35
  import { createHook } from './hook.js'
38
36
  import { listOverrides } from './overrides.js'
39
- import { checkProjects, readManifests, workspaceNames } from './projects.js'
37
+ import { checkHost, inputsOf, manifestsOf, patchesOf, readWorkspace } from './inputs.js'
38
+ import { checkProject } from './project.js'
39
+ import { checkProjects, workspaceNames } from './projects.js'
40
40
  import { readSettings } from './settings.js'
41
41
  import { checkUpToDate } from './uptodate.js'
42
42
  import { checkWorkspace } from './workspace.js'
43
43
 
44
44
  const CONCURRENCY = 8
45
- const LIBC = new Set(['glibc', 'musl', 'unknown'])
46
-
47
- function checkHost(host) {
48
- if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with pnpm, node, os, cpu and libc')
49
- for (const key of ['pnpm', 'node', 'os', 'cpu', 'libc']) {
50
- if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
51
- }
52
- const { pnpm, node, os, libc } = host
53
- const major = Number(valid(pnpm)?.split('.')[0])
54
- // What pnpm 11 does differently is read below, by `major`, where it is.
55
- if (major !== 10 && major !== 11) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10 and 11 are`, 'host.pnpm')
56
- if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
57
- if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
58
- if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
59
- return { pnpm, major, node, os, cpu: host.cpu, libc }
60
- }
61
45
 
62
46
  // What the lockfile holds that no tree is built for here.
63
47
  function checkLockfile(lockfile) {
@@ -75,10 +59,18 @@ function checkLockfile(lockfile) {
75
59
 
76
60
  // A package fetched here comes from the public registry, as upstream
77
61
  // fetches it: its key is its name and version, and its resolution a
78
- // tarball there with a sha512.
79
- function checkRegistry(node) {
62
+ // tarball there with a sha512. One pnpm installs from a directory is one
63
+ // a `file:` override names, in `installed`, as local.js reads it, and is
64
+ // not patched: pnpm installs its files by hardlinks, so a patch would be
65
+ // applied to the directory's own.
66
+ function checkSource(node, installed) {
80
67
  const { key, pkg } = node
81
68
  const { resolution } = pkg
69
+ if (resolution.type === 'directory') {
70
+ 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))
71
+ 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))
72
+ return
73
+ }
82
74
  const fromRegistry = pkg.version !== undefined && packageKeyOf(key) === `${pkg.name}@${pkg.version}` && resolution.type === 'tarball'
83
75
  && resolution.path === undefined && !resolution.gitHosted && (resolution.tarball ?? tarballUrl(pkg.name, pkg.version)) === tarballUrl(pkg.name, pkg.version)
84
76
  if (!fromRegistry) throw new DeptreeError(`only packages from ${REGISTRY} are supported`, quote(key))
@@ -91,8 +83,9 @@ const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[
91
83
 
92
84
  // Each package's files and package.json, by its name and version: a
93
85
  // package is fetched once however many snapshots it has, a few at a time,
94
- // and the first failure stops the rest from starting.
95
- async function fetchAll(nodes) {
86
+ // and the first failure stops the rest from starting. One installed from
87
+ // a directory is read from `project`, as npm-packlist picks its files.
88
+ async function fetchAll(nodes, project, major) {
96
89
  const packages = new Map()
97
90
  for (const { key, pkg } of nodes.values()) {
98
91
  const id = packageKeyOf(key)
@@ -106,7 +99,11 @@ async function fetchAll(nodes) {
106
99
  while (queue.length > 0 && !failed) {
107
100
  const [id, pkg] = queue.shift()
108
101
  try {
109
- fetched.set(id, await fetchPackage(pkg, quote(id)))
102
+ if (pkg.resolution.type === 'directory') {
103
+ const got = readDirectoryPackage(project, pkg, quote(id), major)
104
+ checkManifest(got.manifest, pkg, quote(id))
105
+ fetched.set(id, { ...got, local: true })
106
+ } else fetched.set(id, await fetchPackage(pkg, quote(id)))
110
107
  } catch (error) {
111
108
  failed = true
112
109
  throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
@@ -119,9 +116,9 @@ async function fetchAll(nodes) {
119
116
 
120
117
  // Each node with its package's files and package.json, by its directory:
121
118
  // its dependencies held to the package.json, as `hook` reads it once for
122
- // each package.
123
- async function fetchNodes(nodes, hook) {
124
- const fetched = await fetchAll(nodes)
119
+ // each package; and the number of tarballs fetched.
120
+ async function fetchNodes(nodes, hook, project, major) {
121
+ const fetched = await fetchAll(nodes, project, major)
125
122
  const byDir = new Map()
126
123
  for (const node of nodes.values()) {
127
124
  const id = packageKeyOf(node.key)
@@ -130,13 +127,36 @@ async function fetchNodes(nodes, hook) {
130
127
  checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
131
128
  byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
132
129
  }
133
- return { byDir, tarballs: fetched.size }
130
+ return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
131
+ }
132
+
133
+ // A package installed from a directory has one file for each of its
134
+ // files, hardlinked into each of its snapshots: fixBin makes it
135
+ // executable in all of them, though a CRLF `#!` line it rewrites is
136
+ // written as a file of that snapshot's own. By directory, the files a
137
+ // snapshot has made executable by another's: `targets` is binTargets's.
138
+ function executableElsewhere(byDir, targets) {
139
+ const byPackage = new Map()
140
+ for (const node of byDir.values()) {
141
+ if (node.pkg.resolution.type !== 'directory') continue
142
+ const id = packageKeyOf(node.key)
143
+ if (!byPackage.has(id)) byPackage.set(id, new Set())
144
+ for (const path of targets.get(node.dir) ?? []) byPackage.get(id).add(path)
145
+ }
146
+ const executable = new Map()
147
+ for (const node of byDir.values()) {
148
+ if (node.pkg.resolution.type !== 'directory') continue
149
+ const own = targets.get(node.dir) ?? new Set()
150
+ executable.set(node.dir, new Set([...byPackage.get(packageKeyOf(node.key))].filter((path) => !own.has(path))))
151
+ }
152
+ return executable
134
153
  }
135
154
 
136
155
  // A snapshot's files as pnpm leaves them: its package's, the patch the
137
- // snapshot names applied, and what linking bins does to them. `context`
138
- // is the host and settings.
139
- function compose(node, patches, targets, context) {
156
+ // snapshot names applied, and what linking bins does to them: fixBin run
157
+ // on `targets`, and `executable` made so. `checkPatched` is
158
+ // createPatchedCheck's.
159
+ function compose(node, patches, { targets, executable }, { major, checkPatched }) {
140
160
  const where = quote(node.key)
141
161
  let files = node.files
142
162
  const { patchHash } = node.pkg
@@ -144,27 +164,33 @@ function compose(node, patches, targets, context) {
144
164
  if (!patches.has(patchHash)) throw new DeptreeError(`the patch ${patchHash} is not given`, where)
145
165
  const patch = patches.get(patchHash)
146
166
  patch.parsed ??= parsePatch(patch.text, patch.path)
147
- files = applyPatch(files, patch.parsed)
148
- checkPatchedEngines(checkPatchOfBins(node, files, targets, where, context.host.major), where, context)
167
+ // Once for each package, whatever its snapshots.
168
+ patch.applied ??= new WeakMap()
169
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed))
170
+ files = patch.applied.get(files)
171
+ const manifest = checkPatchOfBins(node, files, targets, where, major)
172
+ checkPatched?.(manifest, where)
149
173
  }
150
- if (targets.size === 0) return files
174
+ if (targets.size === 0 && executable.size === 0) return files
151
175
  files = new Map(files)
152
176
  for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
177
+ for (const path of executable) files.set(path, { ...files.get(path), mode: 0o755 })
153
178
  return files
154
179
  }
155
180
 
156
- const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
157
-
158
181
  // Writes a file where nothing is, or the same file is: a write never
159
- // replaces anything else.
182
+ // replaces anything else. The tree holds no links yet.
160
183
  function writeOnce(vfs, path, { data, mode }) {
161
- if (vfs.isFile(path)) {
162
- if (vfs.lstat(path).mode === mode && sameBytes(vfs.readFile(path), data)) return false
163
- } else if (!vfs.isSymlink(path) && !vfs.isDirectory(path)) {
184
+ let there
185
+ try {
186
+ there = vfs.lstat(path)
187
+ } catch (error) {
188
+ if (!(error instanceof VfsError)) throw error
164
189
  vfs.mkdir(dirname(path), { recursive: true })
165
190
  vfs.writeFile(path, data, { mode })
166
191
  return true
167
192
  }
193
+ if (there.type === 'file' && there.mode === mode && sameBytes(vfs.readFile(path), data)) return false
168
194
  throw new DeptreeError('would be written over with something else', quote(path.slice(1)))
169
195
  }
170
196
 
@@ -180,10 +206,10 @@ function linkTarget(path, target) {
180
206
  // Every link in the tree, by its path: each node's children beside it and
181
207
  // itself inside it where it depends on itself, then what is hoisted, then
182
208
  // each project's direct dependencies, which win over a hoisted alias.
183
- function linksOf(nodes, direct, settings, projects, major) {
184
- const byDir = new Map([...nodes.values()].map((node) => [node.dir, node]))
209
+ // `byDir` is the graph by directory.
210
+ function linksOf(byDir, direct, settings, projects, major) {
185
211
  const links = new Map()
186
- for (const node of nodes.values()) {
212
+ for (const node of byDir.values()) {
187
213
  for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
188
214
  const self = node.children.get(node.name)
189
215
  if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
@@ -195,56 +221,46 @@ function linksOf(nodes, direct, settings, projects, major) {
195
221
  return links
196
222
  }
197
223
 
198
- // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
199
- // nothing, as pnpm reads it.
200
- const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : parseYaml(text))
201
-
202
- function readPatchesGiven(patches) {
203
- const entries = patches instanceof Map ? [...patches] : Object.entries(patches ?? {})
204
- for (const [path, text] of entries) {
205
- if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
206
- }
207
- return entries
208
- }
209
-
210
224
  export async function buildPnpmTree(options) {
211
- const { lockfile: text, manifests: manifestTexts, workspace, npmrc, patches, host: machine, vfs: into } = options ?? {}
212
- if (typeof text !== 'string') throw new TypeError('lockfile must be the text of pnpm-lock.yaml')
225
+ const { project, host: given, vfs: into } = options ?? {}
213
226
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
214
- for (const [name, value] of [['workspace', workspace], ['npmrc', npmrc]]) {
215
- if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
216
- }
217
- const host = checkHost(machine)
227
+ if (project !== undefined) checkProject(project)
228
+ const machine = checkHost(given)
229
+ const folded = machine.os === 'darwin'
218
230
  // Refused before anything is fetched; mount checks again.
219
- if (into !== undefined) checkNoModules(into, host.os === 'darwin')
220
- const { lockfile, env } = parsePnpmLockfile(text)
231
+ if (into !== undefined) checkNoModules(into, folded)
232
+ const inputs = inputsOf(options)
233
+ const { lockfile, env } = parsePnpmLockfile(inputs.lockfile)
234
+ if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
235
+ // Before the project is read for any importer: none leads out of it.
236
+ checkLockfile(lockfile)
237
+ const workspace = readWorkspace(inputs.workspace)
238
+ const { manifests, pnpm, major } = manifestsOf(inputs, workspace, lockfile, given.pnpm)
239
+ const host = { pnpm, major, ...machine }
221
240
  // pnpm 11 locks config dependencies there, which are refused, and the
222
241
  // pnpm a project pins, which leaves the tree as it is.
223
242
  if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
224
243
  if (env !== undefined && Object.keys(env.importers['.'].configDependencies).length > 0) throw new DeptreeError('config dependencies are not supported', 'env.importers["."].configDependencies')
225
- if (!('.' in lockfile.importers)) throw new DeptreeError('expected the root project, whose package.json holds settings', 'importers')
226
- const manifests = readManifests(manifestTexts, lockfile)
227
- const settings = readSettings({ workspace: readWorkspace(workspace), npmrc, manifest: manifests.get('.'), os: host.os, major: host.major })
228
- checkLockfile(lockfile)
244
+ const settings = readSettings({ workspace, npmrc: inputs.npmrc, manifest: manifests.get('.'), major: host.major })
229
245
  checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
230
246
  const overrides = listOverrides(settings.overrides, settings.catalogs, host.major)
231
- checkLocalOverrides(overrides, into)
232
- const given = await checkUpToDate(lockfile, settings, overrides, readPatchesGiven(patches), host.major)
247
+ const installed = checkLocalOverrides(overrides, project)
248
+ const patches = patchesOf(inputs, settings.patchedDependencies)
249
+ const patched = await checkUpToDate(lockfile, settings, overrides, patches, host.major)
233
250
  const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
234
251
  checkProjects(lockfile, manifests, { hook, host, settings })
235
252
  checkOptional(lockfile)
236
253
  const projects = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
237
- const check = createCheck({ host, settings })
238
- const { skipped, incompatible } = skippedSnapshots(lockfile, check, { major: host.major, engineStrict: settings.engineStrict })
254
+ const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
239
255
  const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
240
- for (const node of nodes.values()) checkRegistry(node)
256
+ for (const node of nodes.values()) checkSource(node, installed)
241
257
 
242
- const { byDir, tarballs } = await fetchNodes(nodes, hook)
243
- const links = linksOf(nodes, direct, settings, projects, host.major)
244
- const linked = readLinked(links, byDir, manifests, into)
258
+ const { byDir, tarballs } = await fetchNodes(nodes, hook, project, host.major)
259
+ const links = linksOf(byDir, direct, settings, projects, host.major)
260
+ const linked = readLinked(links, byDir, manifests, project)
245
261
  const targets = binTargets({
246
262
  nodes: byDir,
247
- projects: linked.size === 0 ? manifests : new Map([...manifests, ...linked]),
263
+ projects: new Map([...manifests, ...linked]),
248
264
  direct,
249
265
  links,
250
266
  publicHoist: settings.publicHoistPattern?.length > 0,
@@ -252,15 +268,19 @@ export async function buildPnpmTree(options) {
252
268
  peers: settings.autoInstallPeers,
253
269
  major: host.major,
254
270
  })
271
+ const executable = executableElsewhere(byDir, targets)
255
272
 
256
273
  const vfs = new Vfs()
257
274
  vfs.mkdir('/node_modules/.pnpm', { recursive: true })
258
275
  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 }
276
+ const composing = { major: host.major, checkPatched: createPatchedCheck({ host, settings }) }
277
+ // Each node is let go once written, and a package's files with its last.
259
278
  for (const node of byDir.values()) {
279
+ byDir.delete(node.dir)
260
280
  if (node.pkg.patchHash !== undefined) stats.patched++
261
281
  try {
262
282
  vfs.mkdir(`/${node.dir}`, { recursive: true })
263
- for (const [path, file] of compose(node, given, targets.get(node.dir) ?? new Set(), { host, settings })) {
283
+ for (const [path, file] of compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing)) {
264
284
  if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
265
285
  else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
266
286
  stats.files++
@@ -281,8 +301,8 @@ export async function buildPnpmTree(options) {
281
301
  }
282
302
  }
283
303
  checkLinks(vfs, links)
284
- if (host.os === 'darwin') checkCollisions(vfs)
304
+ if (folded) checkCollisions(vfs)
285
305
  if (into === undefined) return { vfs, stats }
286
- mount(vfs, into, host.os === 'darwin')
306
+ mount(vfs, into, folded)
287
307
  return { vfs: into, stats }
288
308
  }