@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,160 @@
1
+ // What buildPnpmTree and findPnpmProjects take, checked: the host pnpm
2
+ // would install on, and the files an install reads — given as text, or
3
+ // read from the project (project.js) as pnpm reads them from disk.
4
+
5
+ import { LockfileError, YamlError, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
6
+ import { parseYaml } from '@preventive/lockfile/yaml.js'
7
+ import { compareVersions, valid } from '@preventive/upstream/semver.js'
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { checkProject, readManifestTexts, readPatches, readRootFiles, readText, readWorkspaceText, typeOf } from './project.js'
10
+ import { pinnedPnpm, readManifest, readManifests } from './projects.js'
11
+ import { readers } from './readers.js'
12
+ import { checkWorkspace, findProjects, linkedManifest } from './workspace.js'
13
+
14
+ const LIBC = new Set(['glibc', 'musl', 'unknown'])
15
+
16
+ // The major version of `pnpm`, 10, 11 or 12: what pnpm 11 and 12 do
17
+ // differently is read by it, where it is. pnpm 12 before 12.8.1 installs
18
+ // otherwise in places, and is refused.
19
+ function majorOf(pnpm) {
20
+ const major = Number(valid(pnpm)?.split('.')[0])
21
+ if (major !== 10 && major !== 11 && major !== 12) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: only pnpm 10, 11 and 12 are`, 'host.pnpm')
22
+ if (major === 12 && compareVersions(pnpm, '12.8.1') < 0) throw new DeptreeError(`pnpm ${quote(pnpm)} is not supported: pnpm 12 is from 12.8.1 on`, 'host.pnpm')
23
+ return major
24
+ }
25
+
26
+ // The pnpm that installs, and its major version: `pnpm`, host.pnpm, or
27
+ // where that is left out, the one the root package.json pins by its
28
+ // packageManager, which is the only one it takes; `root` gives that
29
+ // package.json as parsed, and is called only then.
30
+ function pnpmOf(pnpm, root) {
31
+ if (pnpm !== undefined && (typeof pnpm !== 'string' || pnpm === '')) throw new TypeError('host.pnpm must be a non-empty string, or left out')
32
+ const version = pnpm ?? pinnedPnpm(root()?.packageManager)
33
+ if (version === undefined) throw new TypeError('host.pnpm must be given where the root package.json\'s packageManager pins no pnpm')
34
+ return { pnpm: version, major: majorOf(version) }
35
+ }
36
+
37
+ // All of host but its pnpm, which pnpmOf reads.
38
+ export function checkHost(host) {
39
+ if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with node, os, cpu and libc, and pnpm where it is not pinned')
40
+ for (const key of ['node', 'os', 'cpu', 'libc']) {
41
+ if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
42
+ }
43
+ const { node, os, libc } = host
44
+ if (valid(node) === null) throw new DeptreeError(`${quote(node)} is not an exact version`, 'host.node')
45
+ if (os === 'win32') throw new DeptreeError('Windows is not supported: pnpm links there with junctions to absolute paths', 'host.os')
46
+ if (!LIBC.has(libc)) throw new DeptreeError(`expected "glibc", "musl" or "unknown", found ${quote(libc)}`, 'host.libc')
47
+ return { node, os, cpu: host.cpu, libc }
48
+ }
49
+
50
+ // Both files are YAML: unnamed, a refusal of one reads as one of the other.
51
+ function readNamed(file, read, text) {
52
+ try {
53
+ return read(text)
54
+ } catch (error) {
55
+ if (error instanceof LockfileError || error instanceof YamlError) throw new DeptreeError(error.message, file, { cause: error })
56
+ throw error
57
+ }
58
+ }
59
+
60
+ // Before any install, pnpm 11 may write the env document alone, with no lockfile to install from.
61
+ export function readLockfile(text) {
62
+ const read = readNamed('pnpm-lock.yaml', parsePnpmLockfile, text)
63
+ if (read.lockfile === undefined) throw new DeptreeError('it holds the env document pnpm 11 writes alone, not the project\'s lockfile, which a frozen install cannot do without', 'pnpm-lock.yaml')
64
+ return read
65
+ }
66
+
67
+ // pnpm-workspace.yaml as parsed; one of comments alone, or nothing, sets
68
+ // nothing, as pnpm reads it.
69
+ const readWorkspace = (text) => (text === undefined || /^(?:[\t ]*(?:#.*)?(?:\r?\n|$))*$/u.test(text) ? undefined : readNamed('pnpm-workspace.yaml', parseYaml, text))
70
+
71
+ // The root package.json in `project`, as parsed, where there is one; one
72
+ // that is a link is refused unread, as findProjects refuses it.
73
+ const ROOT = 'manifests["."]'
74
+ function readRoot(project) {
75
+ if (typeOf(project, '/package.json', false) === 'symlink') throw linkedManifest('package.json')
76
+ const text = readText(project, '/package.json', ROOT)
77
+ return text === undefined ? undefined : readManifest(text, ROOT)
78
+ }
79
+
80
+ // pnpm-workspace.yaml as pnpm 12 has it where there is none: of the root
81
+ // package.json's `workspaces` list, its strings but empty ones are the
82
+ // packages, as pnpm 12 writes a pnpm-workspace.yaml of them. `text` is
83
+ // pnpm-workspace.yaml's, and `workspace` as parsed.
84
+ function workspaceOf(workspace, text, major, root) {
85
+ if (major < 12 || text !== undefined) return workspace
86
+ const listed = root()?.workspaces
87
+ const packages = Array.isArray(listed) ? listed.filter((pattern) => typeof pattern === 'string' && pattern !== '') : []
88
+ return packages.length === 0 ? workspace : { packages }
89
+ }
90
+
91
+ // The packages of `workspace`, pnpm-workspace.yaml as parsed, read here
92
+ // before the rest of it is, to find the projects by.
93
+ function packagesOf(workspace) {
94
+ if (workspace !== undefined && (workspace === null || typeof workspace !== 'object' || Array.isArray(workspace))) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
95
+ return workspace?.packages === undefined ? undefined : readers.globs(workspace.packages, 'pnpm-workspace.yaml: packages')
96
+ }
97
+
98
+ // The directories of the projects pnpm finds in `project`, which
99
+ // buildPnpmTree takes the package.json of each of.
100
+ export function findPnpmProjects(options) {
101
+ const { project, host } = options ?? {}
102
+ checkProject(project)
103
+ if (host !== undefined && (host === null || typeof host !== 'object')) throw new TypeError('host must be an object, or left out')
104
+ const { major } = pnpmOf(host?.pnpm, () => readRoot(project))
105
+ const text = readWorkspaceText(project)
106
+ return findProjects(project, packagesOf(workspaceOf(readWorkspace(text), text, major, () => readRoot(project))), major)
107
+ }
108
+
109
+ const LOCKFILE = 'lockfile must be the text of pnpm-lock.yaml, or left out with a project given to read it from'
110
+
111
+ // The files an install reads but the package.json and the patches: given,
112
+ // with `lockfile`, or read from `project` without it.
113
+ export function inputsOf(options) {
114
+ const { lockfile, manifests, workspace, npmrc, patches, project } = options
115
+ if (lockfile === undefined) {
116
+ if (project === undefined) throw new TypeError(LOCKFILE)
117
+ for (const [name, value] of Object.entries({ manifests, workspace, npmrc, patches })) {
118
+ if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: both are read from project`)
119
+ }
120
+ return { reading: true, project, ...readRootFiles(project) }
121
+ }
122
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
123
+ for (const [name, value] of Object.entries({ workspace, npmrc })) {
124
+ if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
125
+ }
126
+ return { reading: false, lockfile, manifests, workspace, npmrc, patches }
127
+ }
128
+
129
+ // The package.json of every project, the pnpm that installs as pnpmOf
130
+ // reads it from the root one, and pnpm-workspace.yaml as workspaceOf has
131
+ // it: as given, or read from the project for each project pnpm finds
132
+ // there, and no other, as pnpm reads them: an importer the globs do not
133
+ // take is refused first, and one they take that pnpm does not find has
134
+ // none. `pnpm` is host.pnpm.
135
+ export function manifestsOf(inputs, lockfile, pnpm) {
136
+ const workspace = readWorkspace(inputs.workspace)
137
+ if (!inputs.reading) {
138
+ const manifests = readManifests(inputs.manifests, lockfile)
139
+ const installs = pnpmOf(pnpm, () => manifests.get('.'))
140
+ return { manifests, ...installs, workspace: workspaceOf(workspace, inputs.workspace, installs.major, () => manifests.get('.')) }
141
+ }
142
+ const { project } = inputs
143
+ const installs = pnpmOf(pnpm, () => readRoot(project))
144
+ const effective = workspaceOf(workspace, inputs.workspace, installs.major, () => readRoot(project))
145
+ const packages = packagesOf(effective)
146
+ checkWorkspace(Object.keys(lockfile.importers), packages, installs.major)
147
+ const ids = findProjects(project, packages, installs.major)
148
+ return { manifests: readManifests(readManifestTexts(project, ids), lockfile), ...installs, workspace: effective }
149
+ }
150
+
151
+ // The patch files, by path: as given, or read from the project, each that
152
+ // `configured`, patchedDependencies, names.
153
+ export function patchesOf(inputs, configured) {
154
+ if (inputs.reading) return readPatches(inputs.project, configured)
155
+ const entries = inputs.patches instanceof Map ? [...inputs.patches] : Object.entries(inputs.patches ?? {})
156
+ for (const [path, text] of entries) {
157
+ if (typeof text !== 'string') throw new TypeError(`patches[${quote(path)}] must be a string`)
158
+ }
159
+ return entries
160
+ }
@@ -19,15 +19,23 @@
19
19
  // or not, with a warning; each reachable snapshot not taken is left out.
20
20
  // Where a package of an optional edge names no os, cpu or libc, pnpm 11
21
21
  // infers them from its name, as `@nx/nx-win32-arm64-msvc` names win32.
22
+ //
23
+ // pnpm 12 leaves out the same, but refuses with engineStrict whatever it
24
+ // installs that the host cannot run, the lockfile's optional mark or not,
25
+ // and holds a patched package's published engines to the host as it walks
26
+ // it. Of a project it checks only the root's engines.node, and only with
27
+ // engineStrict. It reads an engines.node npm's semver does not, or a
28
+ // range of a `-` with an `x`, otherwise than npm's semver, which is
29
+ // refused where it would decide what is installed.
22
30
 
23
- import { satisfies } from '@preventive/upstream/semver.js'
31
+ import { satisfies, validRange } from '@preventive/upstream/semver.js'
24
32
  import { DeptreeError, quote } from '../error.js'
25
33
 
26
34
  // pnpm's checkList: `any` alone is anything, `!x` excludes, and a list of
27
35
  // exclusions alone takes what none of them names. pnpm 10 counts the
28
36
  // exclusions over every value the host is taken to be, so a list of them
29
37
  // takes nothing where the host is taken to be more than one thing; pnpm 11
30
- // does not.
38
+ // does not. pnpm 12 takes, of each value, the first item that names it.
31
39
  function checkList(values, list, major) {
32
40
  if (list.length === 1 && list[0] === 'any') return true
33
41
  let match = false
@@ -37,7 +45,10 @@ function checkList(values, list, major) {
37
45
  if (item.startsWith('!')) {
38
46
  if (item.slice(1) === value) return false
39
47
  excluded++
40
- } else if (item === value) match = true
48
+ } else if (item === value) {
49
+ match = true
50
+ if (major >= 12) break
51
+ }
41
52
  }
42
53
  }
43
54
  return match || (major >= 11 ? list.every((item) => item.startsWith('!')) : excluded === list.length)
@@ -76,8 +87,17 @@ const takesPlatform = (pkg, host, supported) => checkList(current(host.os, suppo
76
87
 
77
88
  const takesEngine = (engines, node) => !engines.node || satisfies(node, engines.node, { includePrerelease: true })
78
89
 
79
- // The Node pnpm checks engines.node against.
80
- const nodeOf = ({ host, settings }) => settings.nodeVersion ?? host.node
90
+ // Refuses an engines.node, `what`, that pnpm 12 may read otherwise than
91
+ // npm's semver: it drops what of a range it cannot parse, where npm's
92
+ // takes none of it, and reads a `-` range with an `x` as taking nothing.
93
+ function checkSure12(range, where, what = 'its engines.node') {
94
+ if (typeof range !== 'string' || (validRange(range) !== null && !(/\s-\s/u.test(range) && /[*xX]/u.test(range)))) return
95
+ throw new DeptreeError(`${what}, ${quote(range)}, pnpm 12 reads otherwise than npm's semver, which is not supported`, where)
96
+ }
97
+
98
+ // The Node pnpm checks engines.node against: nodeVersion, else the Node
99
+ // the root's engines.runtime pins, else the host's.
100
+ const nodeOf = ({ host, settings }) => settings.nodeVersion ?? settings.runtimeNodeVersion ?? host.node
81
101
 
82
102
  // With engineStrict, pnpm 11 passes over the engines the lockfile records
83
103
  // of a patched snapshot, and holds those of its package.json, once
@@ -93,12 +113,27 @@ function platformList(value, where) {
93
113
  throw new DeptreeError('expected a string or a list of them', where)
94
114
  }
95
115
 
116
+ // pnpm 12 checks the root project's engines.node, where it is text, with
117
+ // engineStrict alone.
118
+ function checkRoot12(manifest, where, context) {
119
+ const range = manifest.engines?.node
120
+ if (!context.settings.engineStrict || typeof range !== 'string' || range === '') return
121
+ const node = nodeOf(context)
122
+ checkSure12(range, where)
123
+ if (!takesEngine({ node: range }, node)) throw new DeptreeError(`its engines.node, ${quote(range)}, does not take Node ${node}, which engineStrict refuses`, where)
124
+ }
125
+
96
126
  // A project as pnpm's packageIsInstallable holds it when it reads its
97
127
  // package.json: a platform the host is not only warns, and so does an
98
128
  // engines.node it does not take, unless engineStrict; an engines.pnpm it
99
129
  // does not take is always refused. As pnpm has it, a platform that does
100
130
  // not match is found first, and the engines are then not looked at.
101
- export function checkProject(manifest, where, { host, settings }) {
131
+ // pnpm 12's is checkRoot12, of the root alone.
132
+ export function checkProject(manifest, where, { host, settings, root }) {
133
+ if (host.major >= 12) {
134
+ if (root) checkRoot12(manifest, where, { host, settings })
135
+ return
136
+ }
102
137
  const platform = { os: platformList(manifest.os, `${where}.os`), cpu: platformList(manifest.cpu, `${where}.cpu`), libc: platformList(manifest.libc, `${where}.libc`) }
103
138
  if (!takesPlatform(platform, host, settings.supportedArchitectures)) return
104
139
  const engines = manifest.engines
@@ -113,18 +148,22 @@ export function checkProject(manifest, where, { host, settings }) {
113
148
  // A check of one snapshot: true where the host can run it, false where it
114
149
  // is optional and cannot, and null where it cannot but is not optional and
115
150
  // is installed anyway. With `engineStrict` that last is refused, where the
116
- // lockfile does not mark the snapshot optional. pnpm 10 takes a snapshot
117
- // to be optional as the lockfile marks it; pnpm 11 as the edge it is
118
- // reached by.
151
+ // lockfile does not mark the snapshot optional, or with pnpm 12. pnpm 10
152
+ // takes a snapshot to be optional as the lockfile marks it; pnpm 11 as the
153
+ // edge it is reached by. A patched one's engines wait for its package.json,
154
+ // patched (patchedLater), but where pnpm 12 is `walking` the lockfile,
155
+ // which holds it to its published ones.
119
156
  function createCheck(context) {
120
157
  const { host, settings } = context
121
158
  const node = nodeOf(context)
122
159
  const later = patchedLater(context)
123
- return (key, pkg, optional = pkg.optional) => {
160
+ return (key, pkg, optional = pkg.optional, walking = false) => {
124
161
  const platform = takesPlatform(host.major >= 11 && optional ? effectivePlatform(pkg) : pkg, host, settings.supportedArchitectures)
125
- if (platform && takesEngine(later && pkg.patchHash !== undefined ? {} : pkg.engines, node)) return true
162
+ const engines = later && !(walking && host.major >= 12) && pkg.patchHash !== undefined ? {} : pkg.engines
163
+ if (host.major >= 12 && platform && (optional || settings.engineStrict)) checkSure12(engines.node, quote(key))
164
+ if (platform && takesEngine(engines, node)) return true
126
165
  if (optional) return false
127
- if (settings.engineStrict && !pkg.optional) throw new DeptreeError(`the host does not take its ${platform ? 'engines.node' : 'os, cpu or libc'}, which engineStrict refuses`, quote(key))
166
+ if (settings.engineStrict && (host.major >= 12 || !pkg.optional)) throw new DeptreeError(`the host does not take its ${platform ? 'engines.node' : 'os, cpu or libc'}, which engineStrict refuses`, quote(key))
128
167
  return null
129
168
  }
130
169
  }
@@ -132,13 +171,17 @@ function createCheck(context) {
132
171
  // A check of a patched package's package.json, once patched, where pnpm
133
172
  // makes one (patchedLater): it fails where the Node is not taken; where
134
173
  // the package is optional, it removes it from the tree it has linked,
135
- // which is refused too.
174
+ // which is refused too. pnpm 12 holds it to nodeVersion, else the host's
175
+ // Node, whatever the root's engines.runtime pins.
136
176
  export function createPatchedCheck(context) {
137
177
  if (!patchedLater(context)) return undefined
138
- const node = nodeOf(context)
178
+ const { host, settings } = context
179
+ const node = host.major >= 12 ? settings.nodeVersion ?? host.node : nodeOf(context)
139
180
  return (manifest, where) => {
140
- if (manifest.engines === undefined || manifest.engines === null || takesEngine(manifest.engines, node)) return
141
- throw new DeptreeError(`its package.json, patched, has an engines.node, ${quote(String(manifest.engines.node))}, that does not take Node ${node}, which pnpm 11 refuses with engineStrict, or removes the package for where it is optional`, where)
181
+ if (manifest.engines === undefined || manifest.engines === null) return
182
+ if (host.major >= 12) checkSure12(manifest.engines.node, where, 'the engines.node of its package.json, patched')
183
+ if (takesEngine(manifest.engines, node)) return
184
+ throw new DeptreeError(`its package.json, patched, has an engines.node, ${quote(String(manifest.engines.node))}, that does not take Node ${node}, which pnpm ${host.major} refuses with engineStrict, or removes the package for where it is optional`, where)
142
185
  }
143
186
  }
144
187
 
@@ -175,20 +218,22 @@ function skippedSnapshots11(lockfile, check) {
175
218
  const starts = queue.map(({ key }) => key)
176
219
  const installed = new Set()
177
220
  const required = new Set()
178
- const incompatible = new Map()
221
+ // Each snapshot reached, and whether the host cannot run it, as checked
222
+ // where an optional edge first reaches it.
223
+ const reached = new Map()
179
224
  for (let i = 0; i < queue.length; i++) {
180
225
  const { key, optional } = queue[i]
181
226
  if (!optional) required.add(key)
182
227
  if (installed.has(key)) continue
183
228
  const pkg = lockfile.packages[key]
184
- if (!incompatible.has(key)) incompatible.set(key, check(key, pkg, true) === false)
185
- if (optional && incompatible.get(key)) continue
229
+ if (!reached.has(key)) reached.set(key, optional && check(key, pkg, true, true) === false)
230
+ if (optional && reached.get(key)) continue
186
231
  installed.add(key)
187
232
  queue.push(...edgesOf(pkg.dependencies, false), ...edgesOf(pkg.optionalDependencies, true))
188
233
  }
189
234
  const skipped = new Set()
190
235
  const warned = new Set()
191
- for (const key of incompatible.keys()) {
236
+ for (const key of reached.keys()) {
192
237
  const pkg = lockfile.packages[key]
193
238
  const ok = check(key, pkg, !installed.has(key) || !required.has(key))
194
239
  if (ok === false) skipped.add(key)
package/src/pnpm/local.js CHANGED
@@ -1,65 +1,127 @@
1
- // Directories outside node_modules the tree links to or installs,
2
- // read from the Vfs given as `vfs` where there is one: those local
3
- // overrides name, and every other a `link:` leads to that is no project
4
- // and is under the lockfile's directory. Each has to hold a package.json
5
- // there, whose bins take their names as pnpm links them. An override to a
6
- // directory is read only from a Vfs given. One by `file:` has pnpm install
7
- // the directory as a package, of the files npm-packlist picks
8
- // (packlist.js); one to a tarball is refused.
1
+ // Directories outside node_modules the tree links to or installs, read
2
+ // from the project (project.js) where one is given: those local overrides
3
+ // name, and every other a `link:` leads to that is no project and is under
4
+ // the lockfile's directory. Each has to hold a package.json there, whose
5
+ // bins take their names as pnpm links them. An override to a directory is
6
+ // read only from a project given. One by `file:` has pnpm install the
7
+ // directory as a package, of the files npm-packlist picks (packlist.js);
8
+ // one to a tarball is refused. pnpm 12 holds one a project depends on to
9
+ // the lockfile before it installs (createFreshnessCheck).
9
10
 
10
- import { DeptreeError, quote } from '../error.js'
11
+ import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
12
+ import { DeptreeError, difference, quote } from '../error.js'
13
+ import { targetName, versionRange } from './frozen.js'
14
+ import { localOf } from './overrides.js'
11
15
  import { packDirectory } from './packlist.js'
16
+ import { readText, typeOf } from './project.js'
12
17
  import { readManifest } from './projects.js'
13
18
 
14
- // readManifest drops a byte order mark, as pnpm does one.
15
- const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
16
-
17
- function manifestAt(vfs, dir, where) {
18
- const path = `/${dir}/package.json`
19
- if (!vfs.isFile(path)) throw new DeptreeError(`${quote(dir)} holds no package.json in the Vfs given`, where)
20
- let text
21
- try {
22
- text = decoder.decode(vfs.readFile(path))
23
- } catch {
24
- throw new DeptreeError(`${quote(`${dir}/package.json`)} is not UTF-8`, where)
25
- }
19
+ function manifestAt(project, dir, where) {
20
+ const text = readText(project, `/${dir}/package.json`, where)
21
+ if (text === undefined) throw new DeptreeError(`${quote(dir)} holds no package.json in the project given`, where)
26
22
  return readManifest(text, where)
27
23
  }
28
24
 
29
25
  // `overrides` is listOverrides's. It gives back the directories `file:`
30
26
  // overrides have pnpm install.
31
- export function checkLocalOverrides(overrides, vfs) {
27
+ export function checkLocalOverrides(overrides, project) {
32
28
  const installed = new Set()
33
29
  for (const { selector, local } of overrides) {
34
30
  if (local === undefined) continue
35
31
  const where = `overrides[${quote(selector)}]`
36
- if (vfs === undefined) throw new DeptreeError(`an override to a directory, ${quote(local.dir)}, is read only from a Vfs given as vfs`, where)
37
- if (local.protocol === 'file:' && vfs.isFile(`/${local.dir}`)) throw new DeptreeError(`${quote(local.dir)} is a file in the Vfs given, and an override to a tarball is not supported`, where)
38
- manifestAt(vfs, local.dir, where)
32
+ if (project === undefined) throw new DeptreeError(`an override to a directory, ${quote(local.dir)}, is read only from a project given`, where)
33
+ if (local.protocol === 'file:' && typeOf(project, `/${local.dir}`) === 'file') throw new DeptreeError(`${quote(local.dir)} is a file in the project given, and an override to a tarball is not supported`, where)
34
+ manifestAt(project, local.dir, where)
39
35
  if (local.protocol === 'file:') installed.add(local.dir)
40
36
  }
41
37
  return installed
42
38
  }
43
39
 
44
- // The package at the directory a `file:` dependency names, from `vfs`:
40
+ // The package at the directory a `file:` dependency names, from `project`:
45
41
  // its files as npm-packlist picks them, and its package.json, which has
46
42
  // to be for the name the lockfile has; the lockfile has no version.
47
- export function readDirectoryPackage(vfs, pkg, where, major) {
43
+ export function readDirectoryPackage(project, pkg, where, major) {
48
44
  const { directory } = pkg.resolution
49
- const manifest = manifestAt(vfs, directory, where)
45
+ const manifest = manifestAt(project, directory, where)
50
46
  if (manifest.name !== pkg.name) throw new DeptreeError(`its package.json is for ${quote(String(manifest.name))}`, where)
51
- return { files: packDirectory(vfs, directory, manifest, major, where), manifest }
47
+ return { files: packDirectory(project, directory, manifest, major, where), manifest }
52
48
  }
53
49
 
54
50
  // By directory, the package.json of each directory the tree links to that
55
51
  // is no node of `nodes`, no project of `projects`, and under the
56
- // lockfile's directory, read from `vfs`; none without one.
57
- export function readLinked(links, nodes, projects, vfs) {
52
+ // lockfile's directory, read from `project`; none without one.
53
+ export function readLinked(links, nodes, projects, project) {
58
54
  const linked = new Map()
59
- if (vfs === undefined) return linked
55
+ if (project === undefined) return linked
60
56
  for (const [path, target] of links) {
61
57
  if (nodes.has(target) || projects.has(target) || linked.has(target) || target === '..' || target.startsWith('../')) continue
62
- linked.set(target, manifestAt(vfs, target, quote(path)))
58
+ linked.set(target, manifestAt(project, target, quote(path)))
63
59
  }
64
60
  return linked
65
61
  }
62
+
63
+ // Whether pnpm 12 takes a dependency on `name` by `spec`, a specifier not
64
+ // to a directory, to be what the lockfile resolved it to, `target`: a
65
+ // package of the name it asks for, `npm:` aliasing another, at a version
66
+ // in its range, where it is a range and the version is one.
67
+ function resolvesTo(name, spec, target, packages) {
68
+ if (target.startsWith('link:')) return false
69
+ const locked = packages[target]
70
+ if (locked.name !== targetName(spec, name)) return false
71
+ const range = versionRange(spec)
72
+ const version = valid(locked.version ?? '')
73
+ return validRange(range) === null || version === null || satisfies(version, range)
74
+ }
75
+
76
+ const optionalPeers = (meta) => Object.entries(meta ?? {}).filter(([, item]) => item?.optional === true).map(([name]) => name).sort()
77
+
78
+ // pnpm 12 holds a directory a project depends on by `file:` to the
79
+ // lockfile as it reads the directory's package.json, overridden, `read`:
80
+ // each dependency the snapshot `pkg` has is one it asks for, a peer among
81
+ // them, and each it asks for is there, resolved as it asks, an optional one
82
+ // there or not; its peers are exactly what the lockfile records, and so is
83
+ // which of them are optional. A `file:` or `link:` one is held to where it
84
+ // leads by tarball.js's checkDependencies; a path alone, or `workspace:`,
85
+ // is refused. `packages` is the lockfile's.
86
+ function checkFresh(read, pkg, packages, where) {
87
+ const outdated = (why) => new DeptreeError(`the lockfile is not up to date with its package.json, which a frozen install of pnpm 12 refuses: ${why}`, where)
88
+ const wanted = { dependencies: read.dependencies ?? {}, optionalDependencies: read.optionalDependencies ?? {} }
89
+ const peers = read.peerDependencies ?? {}
90
+ for (const [kind, others] of [['dependencies', peers], ['optionalDependencies', {}]]) {
91
+ for (const name of Object.keys(pkg[kind])) {
92
+ if (!Object.hasOwn(wanted[kind], name) && !Object.hasOwn(others, name)) throw outdated(`${kind}.${name} is not one it asks for`)
93
+ }
94
+ for (const [name, spec] of Object.entries(wanted[kind])) {
95
+ const target = pkg[kind][name]
96
+ if (target === undefined) {
97
+ if (kind === 'optionalDependencies') continue
98
+ throw outdated(`${kind}.${name} is not in the lockfile`)
99
+ }
100
+ if (spec.startsWith('file:') || spec.startsWith('link:')) continue
101
+ if (spec.startsWith('workspace:')) throw new DeptreeError(`a workspace: dependency, ${quote(name)}, of a directory pnpm 12 holds to the lockfile is not supported`, where)
102
+ if (localOf(spec, where) !== undefined || !resolvesTo(name, spec, target, packages)) throw outdated(`${kind}.${name} is not resolved as it asks`)
103
+ }
104
+ }
105
+ const peersDiffer = difference(peers, pkg.peerDependencies, ['its package.json', 'the lockfile'])
106
+ if (peersDiffer !== undefined) throw outdated(`its peerDependencies are not the lockfile's: ${peersDiffer}`)
107
+ if (JSON.stringify(optionalPeers(read.peerDependenciesMeta)) !== JSON.stringify(optionalPeers(pkg.peerDependenciesMeta))) throw outdated('which of its peers are optional is not the lockfile\'s')
108
+ }
109
+
110
+ // pnpm 12's check, before it installs, of each snapshot a project depends
111
+ // on by a `file:` specifier to a directory: undefined for another pnpm.
112
+ // It is given the node of a snapshot and its package.json as hook.js reads
113
+ // it.
114
+ export function createFreshnessCheck(lockfile, major) {
115
+ if (major < 12) return undefined
116
+ const direct = new Set()
117
+ for (const importer of Object.values(lockfile.importers)) {
118
+ for (const [name, target] of Object.entries({ ...importer.dependencies, ...importer.devDependencies, ...importer.optionalDependencies })) {
119
+ const spec = importer.specifiers[name]
120
+ if (target.startsWith('link:') || !spec?.startsWith('file:') || /\.(?:tgz|tar\.gz|tar)$/u.test(spec)) continue
121
+ if (lockfile.packages[target].resolution.type === 'directory') direct.add(target)
122
+ }
123
+ }
124
+ return (node, read) => {
125
+ if (direct.has(node.key)) checkFresh(read, node.pkg, lockfile.packages, quote(node.key))
126
+ }
127
+ }
@@ -1,8 +1,9 @@
1
1
  // The files pnpm installs of a directory a `file:` dependency names: its
2
2
  // directory fetcher picks them with npm-packlist — 5.1.3 for pnpm 10,
3
- // 10.0.4 for pnpm 11 — and hardlinks them into the tree. Only
4
- // npm-packlist's built-in rules are followed here, which leave out, by
5
- // name and whatever its case:
3
+ // 10.0.4 for pnpm 11, its own port of it (fs-packlist) for pnpm 12 — and
4
+ // hardlinks or copies them into the tree (tree.js). Only the built-in
5
+ // rules are followed here. npm-packlist's leave out, by name and whatever
6
+ // its case:
6
7
  //
7
8
  // - anywhere, `.git`, `.svn`, `.hg`, `CVS`, `.npmrc`, `.DS_Store`,
8
9
  // `npm-debug.log`, `.npmignore`, `.gitignore`, and a name starting
@@ -14,18 +15,29 @@
14
15
  // - at the top, `node_modules` and the lockfiles `package-lock.json`,
15
16
  // `yarn.lock`, `pnpm-lock.yaml` and, with pnpm 11, `bun.lockb`;
16
17
  //
17
- // and every name with a `*` in it. A directory those do not describe is
18
- // refused: one with a .npmignore or .gitignore in it, or a package.json
19
- // with `files` or bundled dependencies, whose rules are not followed
20
- // here; one with a link in it, which the two pass over differently; and
21
- // one where a file those leave out is one npm-packlist would keep, a
22
- // readme, copying, license or licence file, or one `main`, `browser` or
23
- // `bin` names, as the two keep them differently. So is a file whose mode
24
- // is not 0o644 or 0o755, which linking a bin would change otherwise than
25
- // fixBin has it.
18
+ // and every name with a `*` in it. pnpm 12's leave out, by name as it is
19
+ // spelled:
20
+ //
21
+ // - anywhere, `.git`, `.svn`, `.hg` and `CVS`, with everything in them,
22
+ // and a file `.npmrc`, `npm-debug.log`, `.DS_Store`,
23
+ // `package-lock.json`, `yarn.lock` or `pnpm-lock.yaml`, or one whose
24
+ // name ends in `.orig`;
25
+ // - at the top, `node_modules`.
26
+ //
27
+ // A directory those do not describe is refused: one with a .npmignore
28
+ // or .gitignore in it, or a package.json with `files` or bundled
29
+ // dependencies, whose rules are not followed here; one with a link in
30
+ // it, which the two pass over differently; and one where a file those
31
+ // leave out is one npm-packlist would keep, a readme, copying, license or
32
+ // licence file, or one `main`, `browser` or `bin` names, as the two keep
33
+ // them differently, or, with pnpm 12, one in node_modules that `main` or
34
+ // `bin` names, the only file it keeps of those its rules leave out. So is
35
+ // a file whose mode is not 0o644 or 0o755, which linking a bin would
36
+ // change otherwise than fixBin has it.
26
37
 
27
38
  import { join } from '@preventive/vfs/path.js'
28
39
  import { DeptreeError, quote } from '../error.js'
40
+ import { readBytes } from './project.js'
29
41
 
30
42
  // The rules each name is held to, folded, wherever it is.
31
43
  const ANYWHERE = /^(?:\.git|\.svn|\.hg|cvs|\.npmrc|\.ds_store|npm-debug\.log|\.npmignore|\.gitignore|\._.*|\..*\.swp|.*\.orig)$/u
@@ -40,9 +52,28 @@ const anchored = (names, directory) => (names.length === 1 && (names[0] === '.lo
40
52
  const TOP = ['node_modules', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
41
53
  const TOP_11 = [...TOP, 'bun.lockb']
42
54
 
43
- // Whether the built-in rules leave out the entry at `names`, its path from
44
- // the package's directory by name, which is a directory where `directory`.
45
- function leftOut(names, directory, major) {
55
+ // pnpm 12's rules: the names left out wherever they are, and the files.
56
+ const VCS = new Set(['.git', '.svn', '.hg', 'CVS'])
57
+ const CRUFT = new Set(['.npmrc', 'npm-debug.log', '.DS_Store', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'])
58
+
59
+ // Whether pnpm 12's rules leave out the entry at `names`, its path from the
60
+ // package's directory by name, which is a directory where `directory`.
61
+ function leftOut12(names, directory) {
62
+ const name = names.at(-1)
63
+ return VCS.has(name) || (names.length === 1 && name === 'node_modules') || (!directory && (CRUFT.has(name) || name.endsWith('.orig')))
64
+ }
65
+
66
+ // Whether pnpm 12 leaves out the file at `path` even where `main` or `bin`
67
+ // names it: by all its rules but node_modules's.
68
+ function alwaysLeftOut12(path) {
69
+ const names = path.split('/')
70
+ const name = names.at(-1)
71
+ return names.some((each) => VCS.has(each)) || CRUFT.has(name) || name.endsWith('.orig')
72
+ }
73
+
74
+ // Whether npm-packlist's built-in rules, as pnpm `major` runs it, leave out
75
+ // the entry at `names`, as for leftOut12.
76
+ function leftOutByNpm(names, directory, major) {
46
77
  const folded = names.map((name) => name.toLowerCase())
47
78
  const readIn = major >= 11 ? folded.map((_, i) => folded.slice(i)) : [folded]
48
79
  return ANYWHERE.test(folded.at(-1)) || readIn.some((path) => anchored(path, directory))
@@ -53,45 +84,49 @@ function leftOut(names, directory, major) {
53
84
  const MUST_HAVE = /^(?:readme|copying|license|licence)(?:\..*[^~$])?$/iu
54
85
 
55
86
  // The paths a package.json's main, browser and bin name, from its
56
- // directory, whatever their case.
57
- function namedByManifest(manifest) {
87
+ // directory, whatever their case, that pnpm `major` may keep whatever its
88
+ // rules say: with pnpm 12, those main and bin name that its rules but
89
+ // node_modules's do not leave out.
90
+ function namedByManifest(manifest, major) {
58
91
  const { main, browser, bin } = manifest
59
- const paths = [main, browser, ...typeof bin === 'string' ? [bin] : Object.values(bin ?? {})]
60
- return paths.filter((path) => typeof path === 'string').map((path) => join('.', path).toLowerCase())
92
+ const bins = typeof bin === 'string' ? [bin] : Object.values(bin ?? {})
93
+ const paths = (major >= 12 ? [main, ...bins] : [main, browser, ...bins]).filter((path) => typeof path === 'string').map((path) => join('.', path))
94
+ return (major >= 12 ? paths.filter((path) => !alwaysLeftOut12(path)) : paths).map((path) => path.toLowerCase())
61
95
  }
62
96
 
63
97
  // Whether a package.json's list of bundled dependencies may name any: an
64
98
  // empty one bundles none, with either npm-packlist.
65
99
  const bundles = (list) => Boolean(list) && !(Array.isArray(list) && list.length === 0)
66
100
 
67
- // The files of the package at `dir` of `vfs` npm-packlist picks, with
101
+ // The files of the package at `dir` of `project` npm-packlist picks, with
68
102
  // their data and modes, by their paths from it; `manifest` is its
69
103
  // package.json as parsed.
70
- export function packDirectory(vfs, dir, manifest, major, where) {
104
+ export function packDirectory(project, dir, manifest, major, where) {
71
105
  if (manifest.files !== undefined) throw new DeptreeError('its package.json has `files`, which npm-packlist picks the files pnpm installs by, and which is not followed here', where)
72
106
  if (bundles(manifest.bundleDependencies) || bundles(manifest.bundledDependencies)) throw new DeptreeError('a directory with bundled dependencies is not supported', where)
73
- const named = namedByManifest(manifest)
107
+ const named = namedByManifest(manifest, major)
108
+ const leftOut = major >= 12 ? leftOut12 : (names, directory) => leftOutByNpm(names, directory, major)
74
109
  const files = new Map()
75
110
  const visit = (names) => {
76
- for (const entry of vfs.readdir(['', dir, ...names].join('/'))) {
111
+ for (const entry of project.readdir(['', dir, ...names].join('/'))) {
77
112
  const at = [...names, entry]
78
113
  const rel = at.join('/')
79
114
  const here = `${where}: ${quote(rel)}`
80
- const { type, mode } = vfs.lstat(`/${dir}/${rel}`)
115
+ const { type, mode } = project.lstat(`/${dir}/${rel}`)
81
116
  if (type === 'symlink') throw new DeptreeError('a link in a directory pnpm installs a copy of is not supported', here)
82
117
  if (entry === '.npmignore' || entry === '.gitignore') throw new DeptreeError(`${entry}'s rules, which npm-packlist picks the files pnpm installs by, are not followed here`, here)
83
- if (names.length === 0 && entry !== 'node_modules' && entry.toLowerCase() === 'node_modules') throw new DeptreeError('a name that is node_modules but for its case is kept by pnpm 10 and left out by pnpm 11', here)
84
- if (entry.includes('*')) continue
85
- if (leftOut(at, type === 'directory', major)) {
118
+ if (major < 12 && names.length === 0 && entry !== 'node_modules' && entry.toLowerCase() === 'node_modules') throw new DeptreeError('a name that is node_modules but for its case is kept by pnpm 10 and left out by pnpm 11', here)
119
+ if (major < 12 && entry.includes('*')) continue
120
+ if (leftOut(at, type === 'directory')) {
86
121
  const folded = rel.toLowerCase()
87
- if (MUST_HAVE.test(entry) || named.some((kept) => kept === folded || kept.startsWith(`${folded}/`))) {
122
+ if ((major < 12 && MUST_HAVE.test(entry)) || named.some((kept) => kept === folded || kept.startsWith(`${folded}/`))) {
88
123
  throw new DeptreeError('whether pnpm installs it turns on rules of npm-packlist not followed here', here)
89
124
  }
90
125
  continue
91
126
  }
92
127
  if (type === 'directory') visit(at)
93
128
  else if (mode !== 0o644 && mode !== 0o755) throw new DeptreeError(`its mode, ${mode.toString(8)}, is not 644 or 755, which is not supported`, here)
94
- else files.set(rel, { data: vfs.readFile(`/${dir}/${rel}`), mode })
129
+ else files.set(rel, { data: readBytes(project, `/${dir}/${rel}`), mode })
95
130
  }
96
131
  }
97
132
  visit([])