@preventive/deptree 1.0.0-alpha.0
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.
- package/LICENSE +21 -0
- package/package.json +71 -0
- package/pnpm.d.ts +227 -0
- package/pnpm.js +12 -0
- package/src/error.js +32 -0
- package/src/hash.js +23 -0
- package/src/matcher.js +34 -0
- package/src/mount.js +63 -0
- package/src/patch.js +152 -0
- package/src/pnpm/bins.js +436 -0
- package/src/pnpm/checks.js +59 -0
- package/src/pnpm/filename.js +26 -0
- package/src/pnpm/frozen.js +213 -0
- package/src/pnpm/graph.js +54 -0
- package/src/pnpm/hoist.js +109 -0
- package/src/pnpm/hook.js +106 -0
- package/src/pnpm/install.js +229 -0
- package/src/pnpm/local.js +49 -0
- package/src/pnpm/npmrc.js +31 -0
- package/src/pnpm/overrides.js +128 -0
- package/src/pnpm/patches.js +142 -0
- package/src/pnpm/projects.js +240 -0
- package/src/pnpm/readers.js +270 -0
- package/src/pnpm/settings.js +228 -0
- package/src/pnpm/tree.js +288 -0
- package/src/pnpm/uptodate.js +87 -0
- package/src/pnpm/workspace.js +73 -0
- package/src/tarball.js +152 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// The settings a pnpm 10 install reads from the .npmrc beside the lockfile,
|
|
2
|
+
// from pnpm-workspace.yaml, and from the root package.json's `pnpm` field,
|
|
3
|
+
// each over the one before: `pnpm install` spreads what the package.json
|
|
4
|
+
// sets over the config it read the others into, so there the package.json
|
|
5
|
+
// wins, whatever pnpm's config alone would say.
|
|
6
|
+
// In pnpm-workspace.yaml and the package.json, every key is one of three
|
|
7
|
+
// things (readers.js): a setting read here, and held to the values this
|
|
8
|
+
// package builds a tree for; a setting that leaves the tree as it is,
|
|
9
|
+
// whether because a frozen lockfile already says what it would have
|
|
10
|
+
// changed, because it is about the network, the store, a cache, a script
|
|
11
|
+
// or a bin — no script is ever run, whatever a setting allows — or because
|
|
12
|
+
// it is a credential; or anything else, which is refused by name, as is a
|
|
13
|
+
// value read here that this package does not build for.
|
|
14
|
+
//
|
|
15
|
+
// An .npmrc is read as pnpm reads one: by the kebab-case names of its
|
|
16
|
+
// settings alone, and of those only the ones it has types for, which are
|
|
17
|
+
// npm's and its own. Every one of those that can change the tree is read
|
|
18
|
+
// here as above; anything else in the file — npm's settings pnpm has no
|
|
19
|
+
// use for, publishing's, credentials, any other spelling — pnpm passes
|
|
20
|
+
// over for an install, and so does this. A value pnpm would take from the
|
|
21
|
+
// environment is not known here: pnpm drops the whole file where one such
|
|
22
|
+
// variable is unset, so one in a line passed over is taken only where the
|
|
23
|
+
// file sets nothing that dropping it would change.
|
|
24
|
+
//
|
|
25
|
+
// Only these files are read. Settings from anywhere else pnpm looks — a
|
|
26
|
+
// user or global .npmrc, `npm_config_*` in the environment, the command
|
|
27
|
+
// line — are not seen, and a tree built here is the one those leave at
|
|
28
|
+
// their defaults. Of the package.json, pnpm 10 reads only the keys of
|
|
29
|
+
// `pnpm` below (MANIFEST_KEYS) and Yarn's `resolutions`, and so does this.
|
|
30
|
+
//
|
|
31
|
+
// pnpm 11 reads its settings from pnpm-workspace.yaml alone: an .npmrc
|
|
32
|
+
// for credentials and registries, and the package.json for none but the
|
|
33
|
+
// Node its engines.runtime pins, which it takes for nodeVersion. Of the
|
|
34
|
+
// yaml it passes over a key not in camelCase, and one about the machine,
|
|
35
|
+
// the run or a login; it has settings pnpm 10 has not (READ_11, IGNORED_11),
|
|
36
|
+
// and reads linkWorkspacePackages for a frozen install too.
|
|
37
|
+
|
|
38
|
+
import { valid, validRange } from '@preventive/upstream/semver.js'
|
|
39
|
+
import { DeptreeError, quote } from '../error.js'
|
|
40
|
+
import { parseNpmrc } from './npmrc.js'
|
|
41
|
+
import { replaceReferences } from './overrides.js'
|
|
42
|
+
import { IGNORED, MANIFEST_KEYS, READ, checkRegistry, readerOf, readers } from './readers.js'
|
|
43
|
+
|
|
44
|
+
// An .npmrc value read only where it can mean one thing: not quoted, not
|
|
45
|
+
// escaped, with no `;` or `#` that ini would cut it at. Neither file's
|
|
46
|
+
// value is read where pnpm would fill it in from the environment.
|
|
47
|
+
const PLAIN = /^[^"'`;#\\]*$/u
|
|
48
|
+
function plain(value, where) {
|
|
49
|
+
if (!PLAIN.test(value)) throw new DeptreeError(`${quote(value)} is quoted, escaped or commented, which is not read here`, where)
|
|
50
|
+
return value
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const fromEnvironment = (value) => typeof value === 'string' && value.includes('${')
|
|
54
|
+
|
|
55
|
+
function noEnvironment(value, where) {
|
|
56
|
+
if (fromEnvironment(value)) throw new DeptreeError(`${quote(value)} is taken from the environment, which is not read here`, where)
|
|
57
|
+
if (Array.isArray(value)) for (const item of value) noEnvironment(item, where)
|
|
58
|
+
return value
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const KEBAB = /^[a-z][\da-z]*(?:-[\da-z]+)*$/u
|
|
62
|
+
const camelCase = (key) => key.replace(/-+([a-z\d])/gu, (_, char) => char.toUpperCase())
|
|
63
|
+
|
|
64
|
+
// An .npmrc's settings by name, each written once, or once with `[]` each
|
|
65
|
+
// time, and whether any line takes something from the environment. A
|
|
66
|
+
// 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) {
|
|
70
|
+
const settings = new Map()
|
|
71
|
+
let environment = false
|
|
72
|
+
for (const { key, value, list, line } of parseNpmrc(text)) {
|
|
73
|
+
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
|
+
if (/^@[^:]+:registry$/u.test(key)) {
|
|
79
|
+
checkRegistry(plain(noEnvironment(value, where), where), where)
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
const name = KEBAB.test(key) ? camelCase(key) : undefined
|
|
83
|
+
if (!(name in READ) || READ[name].rc === false || IGNORED.has(name)) {
|
|
84
|
+
environment ||= fromEnvironment(key) || fromEnvironment(value)
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
noEnvironment(value, where)
|
|
88
|
+
const earlier = settings.get(name)
|
|
89
|
+
if (earlier !== undefined && !(list && earlier.list)) throw new DeptreeError('set more than once', where)
|
|
90
|
+
if (list && READ[name].kind !== 'texts') throw new DeptreeError('not a list', where)
|
|
91
|
+
const next = list ? [...(earlier?.value ?? []), plain(value, where)] : plain(value, where)
|
|
92
|
+
settings.set(name, { value: next, list, where, read: READ[name] })
|
|
93
|
+
}
|
|
94
|
+
return { settings, environment }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The root package.json's settings: the keys of `pnpm` pnpm reads, and
|
|
98
|
+
// overrides of `resolutions` and `pnpm.overrides` both, the second over the
|
|
99
|
+
// first.
|
|
100
|
+
function fromManifest(manifest) {
|
|
101
|
+
const pnpm = manifest.pnpm === undefined ? {} : readers.mapping(manifest.pnpm, 'package.json: pnpm')
|
|
102
|
+
const settings = new Map()
|
|
103
|
+
for (const name of MANIFEST_KEYS) {
|
|
104
|
+
if (!Object.hasOwn(pnpm, name) || name === 'overrides') continue
|
|
105
|
+
const where = `package.json: pnpm.${name}`
|
|
106
|
+
noEnvironment(pnpm[name], where)
|
|
107
|
+
const read = readerOf(name, where, 10)
|
|
108
|
+
if (read !== undefined) settings.set(name, { value: pnpm[name], where, read })
|
|
109
|
+
}
|
|
110
|
+
const { resolutions } = manifest
|
|
111
|
+
if (resolutions !== undefined || Object.hasOwn(pnpm, 'overrides')) {
|
|
112
|
+
const where = 'package.json: resolutions and pnpm.overrides'
|
|
113
|
+
const value = { ...(resolutions === undefined ? {} : readers.mapping(resolutions, 'package.json: resolutions')), ...(Object.hasOwn(pnpm, 'overrides') ? readers.mapping(pnpm.overrides, 'package.json: pnpm.overrides') : {}) }
|
|
114
|
+
settings.set('overrides', { value, where, read: READ.overrides })
|
|
115
|
+
}
|
|
116
|
+
return settings
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// pnpm 11 passes over a key not in camelCase.
|
|
120
|
+
const CAMEL = /^[a-z][\dA-Za-z]*$/u
|
|
121
|
+
|
|
122
|
+
function fromWorkspace(workspace, major) {
|
|
123
|
+
if (workspace === null || typeof workspace !== 'object' || Array.isArray(workspace)) throw new DeptreeError('expected a mapping', 'pnpm-workspace.yaml')
|
|
124
|
+
const settings = new Map()
|
|
125
|
+
for (const [name, value] of Object.entries(workspace)) {
|
|
126
|
+
const where = `pnpm-workspace.yaml: ${name}`
|
|
127
|
+
noEnvironment(name, where)
|
|
128
|
+
noEnvironment(value, where)
|
|
129
|
+
if (major >= 11 && !CAMEL.test(name)) continue
|
|
130
|
+
const read = readerOf(name, where, major)
|
|
131
|
+
if (read !== undefined) settings.set(name, { value, where, read })
|
|
132
|
+
}
|
|
133
|
+
return settings
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The settings as pnpm 10 derives what it installs by: `hoist: false`
|
|
137
|
+
// drops the private pattern, `shamefullyHoist` sets or drops the public
|
|
138
|
+
// one, and an empty public pattern is none. A pattern left undefined is
|
|
139
|
+
// not hoisted to at all.
|
|
140
|
+
function derive(get, os) {
|
|
141
|
+
const shamefullyHoist = get('shamefullyHoist')
|
|
142
|
+
let publicHoistPattern = get('publicHoistPattern') ?? []
|
|
143
|
+
if (shamefullyHoist === true) publicHoistPattern = ['*']
|
|
144
|
+
else if (shamefullyHoist === false || (publicHoistPattern.length === 1 && publicHoistPattern[0] === '')) publicHoistPattern = undefined
|
|
145
|
+
return {
|
|
146
|
+
virtualStoreDirMaxLength: get('virtualStoreDirMaxLength') ?? (os === 'win32' ? 60 : 120),
|
|
147
|
+
hoistPattern: get('hoist') === false ? undefined : get('hoistPattern') ?? ['*'],
|
|
148
|
+
publicHoistPattern,
|
|
149
|
+
hoistWorkspacePackages: get('hoistWorkspacePackages') ?? true,
|
|
150
|
+
engineStrict: get('engineStrict') ?? false,
|
|
151
|
+
nodeVersion: get('nodeVersion'),
|
|
152
|
+
supportedArchitectures: get('supportedArchitectures'),
|
|
153
|
+
patchedDependencies: get('patchedDependencies'),
|
|
154
|
+
overrides: get('overrides'),
|
|
155
|
+
catalogs: catalogsOf(get('catalog'), get('catalogs')),
|
|
156
|
+
packageExtensions: get('packageExtensions'),
|
|
157
|
+
ignoredOptionalDependencies: get('ignoredOptionalDependencies') ?? [],
|
|
158
|
+
autoInstallPeers: get('autoInstallPeers') ?? true,
|
|
159
|
+
dedupePeers: get('dedupePeers') ?? false,
|
|
160
|
+
peersSuffixMaxLength: get('peersSuffixMaxLength') ?? 1000,
|
|
161
|
+
packages: get('packages'),
|
|
162
|
+
linkWorkspacePackages: get('linkWorkspacePackages') ?? false,
|
|
163
|
+
pmOnFail: get('pmOnFail'),
|
|
164
|
+
runtimeOnFail: get('runtimeOnFail'),
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The catalogs by name, `catalog` being `default`, as pnpm has them, which
|
|
169
|
+
// refuses the default one written both ways.
|
|
170
|
+
function catalogsOf(catalog, catalogs = {}) {
|
|
171
|
+
if (catalog !== undefined && Object.hasOwn(catalogs, 'default')) {
|
|
172
|
+
throw new DeptreeError('the default catalog is defined twice, as catalog and as catalogs.default', 'pnpm-workspace.yaml: catalog')
|
|
173
|
+
}
|
|
174
|
+
return Object.assign(Object.create(null), catalog === undefined ? {} : { default: catalog }, catalogs)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Each layer over the one before, as `derive` has them.
|
|
178
|
+
function settle(layers, manifest, os) {
|
|
179
|
+
const values = new Map()
|
|
180
|
+
for (const layer of layers) {
|
|
181
|
+
for (const [name, { value, where, read: { kind, check } }] of layer) {
|
|
182
|
+
let read = readers[kind](value, where)
|
|
183
|
+
check?.(read, where)
|
|
184
|
+
if (name === 'overrides') {
|
|
185
|
+
if (Object.keys(read).length === 0) continue
|
|
186
|
+
read = replaceReferences(read, manifest, where)
|
|
187
|
+
}
|
|
188
|
+
values.set(name, read)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return derive((name) => values.get(name), os)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// `workspace` is pnpm-workspace.yaml as parsed and `npmrc` the text of the
|
|
195
|
+
// .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))) {
|
|
204
|
+
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
|
+
}
|
|
206
|
+
if (major >= 11) settings.nodeVersion ??= runtimeNode(manifest, settings.runtimeOnFail)
|
|
207
|
+
return settings
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The Node the root package.json's devEngines.runtime or engines.runtime
|
|
211
|
+
// pins, which pnpm 11 takes for nodeVersion where none is set: the first
|
|
212
|
+
// that names a range for Node decides, and gives its version where that is
|
|
213
|
+
// exact. One to download, which gives the range's lowest, is refused;
|
|
214
|
+
// runtimeOnFail stands for each one's onFail.
|
|
215
|
+
function runtimeNode(manifest, onFail) {
|
|
216
|
+
for (const field of ['devEngines', 'engines']) {
|
|
217
|
+
const runtime = manifest[field]?.runtime
|
|
218
|
+
if (runtime == null) continue
|
|
219
|
+
const where = `manifests["."].${field}.runtime`
|
|
220
|
+
const runtimes = Array.isArray(runtime) ? runtime : [runtime]
|
|
221
|
+
if (runtimes.some((item) => item === null || typeof item !== 'object')) throw new DeptreeError('expected a mapping or a list of mappings, which pnpm fails on otherwise', where)
|
|
222
|
+
const node = runtimes.find((item) => item.name === 'node')
|
|
223
|
+
if (typeof node?.version !== 'string' || validRange(node.version.trim()) === null) continue
|
|
224
|
+
if ((onFail ?? node.onFail) === 'download') throw new DeptreeError('a Node runtime to download is not supported', where)
|
|
225
|
+
return valid(node.version.trim()) ?? undefined
|
|
226
|
+
}
|
|
227
|
+
return undefined
|
|
228
|
+
}
|
package/src/pnpm/tree.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
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.
|
|
21
|
+
|
|
22
|
+
import { packageKeyOf, parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
|
|
23
|
+
import { parseYaml } from '@preventive/lockfile/yaml.js'
|
|
24
|
+
import { Vfs } from '@preventive/vfs'
|
|
25
|
+
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'
|
|
29
|
+
import { applyPatch, parsePatch } from '../patch.js'
|
|
30
|
+
import { REGISTRY, checkDependencies, fetchPackage, tarballUrl } from '../tarball.js'
|
|
31
|
+
import { binTargets, checkPatchOfBins, fixBin } from './bins.js'
|
|
32
|
+
import { buildGraph } from './graph.js'
|
|
33
|
+
import { hoist } from './hoist.js'
|
|
34
|
+
import { checkLocalOverrides, readLinked } from './local.js'
|
|
35
|
+
import { checkPatchedEngines, createCheck, skippedSnapshots } from './install.js'
|
|
36
|
+
import { checkCollisions, checkLinks, checkOptional } from './checks.js'
|
|
37
|
+
import { createHook } from './hook.js'
|
|
38
|
+
import { listOverrides } from './overrides.js'
|
|
39
|
+
import { checkProjects, readManifests, workspaceNames } from './projects.js'
|
|
40
|
+
import { readSettings } from './settings.js'
|
|
41
|
+
import { checkUpToDate } from './uptodate.js'
|
|
42
|
+
import { checkWorkspace } from './workspace.js'
|
|
43
|
+
|
|
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
|
+
|
|
62
|
+
// What the lockfile holds that no tree is built for here.
|
|
63
|
+
function checkLockfile(lockfile) {
|
|
64
|
+
if (lockfile.settings.excludeLinksFromLockfile) throw new DeptreeError('links left out of the lockfile would be left out of the tree', 'settings.excludeLinksFromLockfile')
|
|
65
|
+
if (lockfile.settings.injectWorkspacePackages) throw new DeptreeError('injected workspace packages are not supported', 'settings.injectWorkspacePackages')
|
|
66
|
+
if (lockfile.pnpmfileChecksum !== undefined) throw new DeptreeError('a pnpmfile\'s hooks are not run here', 'pnpmfileChecksum')
|
|
67
|
+
for (const [id, importer] of Object.entries(lockfile.importers)) {
|
|
68
|
+
if (id === '..' || id.startsWith('../')) throw new DeptreeError('a project outside the lockfile\'s directory is not supported', `importers[${quote(id)}]`)
|
|
69
|
+
if (id.split('/').includes('node_modules')) throw new DeptreeError('a project inside node_modules would be inside the tree', `importers[${quote(id)}]`)
|
|
70
|
+
for (const [name, meta] of Object.entries(importer.dependenciesMeta)) {
|
|
71
|
+
if (meta.injected) throw new DeptreeError('an injected dependency is not supported', `importers[${quote(id)}].dependenciesMeta[${quote(name)}]`)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// A package fetched here comes from the public registry, as upstream
|
|
77
|
+
// fetches it: its key is its name and version, and its resolution a
|
|
78
|
+
// tarball there with a sha512.
|
|
79
|
+
function checkRegistry(node) {
|
|
80
|
+
const { key, pkg } = node
|
|
81
|
+
const { resolution } = pkg
|
|
82
|
+
const fromRegistry = pkg.version !== undefined && packageKeyOf(key) === `${pkg.name}@${pkg.version}` && resolution.type === 'tarball'
|
|
83
|
+
&& resolution.path === undefined && !resolution.gitHosted && (resolution.tarball ?? tarballUrl(pkg.name, pkg.version)) === tarballUrl(pkg.name, pkg.version)
|
|
84
|
+
if (!fromRegistry) throw new DeptreeError(`only packages from ${REGISTRY} are supported`, quote(key))
|
|
85
|
+
if (!resolution.integrity?.startsWith('sha512-')) throw new DeptreeError('expected a sha512 integrity', quote(key))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// What a package's snapshots all have of it, and it is fetched and held to.
|
|
89
|
+
const PACKAGE_FIELDS = ['resolution', 'os', 'cpu', 'libc', 'hasBin', 'bundledDependencies']
|
|
90
|
+
const packageFields = (pkg) => JSON.stringify(PACKAGE_FIELDS.map((field) => pkg[field]))
|
|
91
|
+
|
|
92
|
+
// Each package's files and package.json, by its name and version: a
|
|
93
|
+
// 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) {
|
|
96
|
+
const packages = new Map()
|
|
97
|
+
for (const { key, pkg } of nodes.values()) {
|
|
98
|
+
const id = packageKeyOf(key)
|
|
99
|
+
if (!packages.has(id)) packages.set(id, pkg)
|
|
100
|
+
else if (packageFields(packages.get(id)) !== packageFields(pkg)) throw new DeptreeError(`its snapshots differ on what the package is: ${PACKAGE_FIELDS.join(', ')}`, quote(id))
|
|
101
|
+
}
|
|
102
|
+
const queue = [...packages]
|
|
103
|
+
const fetched = new Map()
|
|
104
|
+
let failed = false
|
|
105
|
+
const worker = async () => {
|
|
106
|
+
while (queue.length > 0 && !failed) {
|
|
107
|
+
const [id, pkg] = queue.shift()
|
|
108
|
+
try {
|
|
109
|
+
fetched.set(id, await fetchPackage(pkg, quote(id)))
|
|
110
|
+
} catch (error) {
|
|
111
|
+
failed = true
|
|
112
|
+
throw error instanceof DeptreeError ? error : new DeptreeError(error.message, quote(id), { cause: error })
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
|
|
117
|
+
return fetched
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Each node with its package's files and package.json, by its directory:
|
|
121
|
+
// 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)
|
|
125
|
+
const byDir = new Map()
|
|
126
|
+
for (const node of nodes.values()) {
|
|
127
|
+
const id = packageKeyOf(node.key)
|
|
128
|
+
const got = fetched.get(id)
|
|
129
|
+
got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
|
|
130
|
+
checkDependencies(got.manifest, got.read, node.pkg, quote(node.key))
|
|
131
|
+
byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest })
|
|
132
|
+
}
|
|
133
|
+
return { byDir, tarballs: fetched.size }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 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) {
|
|
140
|
+
const where = quote(node.key)
|
|
141
|
+
let files = node.files
|
|
142
|
+
const { patchHash } = node.pkg
|
|
143
|
+
if (patchHash !== undefined) {
|
|
144
|
+
if (!patches.has(patchHash)) throw new DeptreeError(`the patch ${patchHash} is not given`, where)
|
|
145
|
+
const patch = patches.get(patchHash)
|
|
146
|
+
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)
|
|
149
|
+
}
|
|
150
|
+
if (targets.size === 0) return files
|
|
151
|
+
files = new Map(files)
|
|
152
|
+
for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`))
|
|
153
|
+
return files
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
|
|
157
|
+
|
|
158
|
+
// Writes a file where nothing is, or the same file is: a write never
|
|
159
|
+
// replaces anything else.
|
|
160
|
+
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)) {
|
|
164
|
+
vfs.mkdir(dirname(path), { recursive: true })
|
|
165
|
+
vfs.writeFile(path, data, { mode })
|
|
166
|
+
return true
|
|
167
|
+
}
|
|
168
|
+
throw new DeptreeError('would be written over with something else', quote(path.slice(1)))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// A link's target spelled from the directory the link is in, as pnpm's
|
|
172
|
+
// symlink-dir spells it; a target may climb out of the tree, so both are
|
|
173
|
+
// read under as many directories as it climbs.
|
|
174
|
+
function linkTarget(path, target) {
|
|
175
|
+
const climbs = target.split('/').filter((segment) => segment === '..').length
|
|
176
|
+
const root = '/_'.repeat(climbs)
|
|
177
|
+
return relative(`${root}/${dirname(path)}`, `${root}/${target}`) || '.'
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Every link in the tree, by its path: each node's children beside it and
|
|
181
|
+
// itself inside it where it depends on itself, then what is hoisted, then
|
|
182
|
+
// 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]))
|
|
185
|
+
const links = new Map()
|
|
186
|
+
for (const node of nodes.values()) {
|
|
187
|
+
for (const [alias, dir] of node.children) if (alias !== node.name) links.set(`${node.modules}/${alias}`, dir)
|
|
188
|
+
const self = node.children.get(node.name)
|
|
189
|
+
if (byDir.has(self)) links.set(`${node.dir}/node_modules/${node.name}`, self)
|
|
190
|
+
}
|
|
191
|
+
for (const [path, dir] of hoist(byDir, direct, settings, projects, major)) links.set(path, dir)
|
|
192
|
+
for (const [id, children] of direct) {
|
|
193
|
+
for (const [alias, dir] of children) links.set(`${id === '.' ? '' : `${id}/`}node_modules/${alias}`, dir)
|
|
194
|
+
}
|
|
195
|
+
return links
|
|
196
|
+
}
|
|
197
|
+
|
|
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
|
+
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')
|
|
213
|
+
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)
|
|
218
|
+
// Refused before anything is fetched; mount checks again.
|
|
219
|
+
if (into !== undefined) checkNoModules(into, host.os === 'darwin')
|
|
220
|
+
const { lockfile, env } = parsePnpmLockfile(text)
|
|
221
|
+
// pnpm 11 locks config dependencies there, which are refused, and the
|
|
222
|
+
// pnpm a project pins, which leaves the tree as it is.
|
|
223
|
+
if (env !== undefined && host.major < 11) throw new DeptreeError('the env document pnpm 11 writes is not supported', 'env')
|
|
224
|
+
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)
|
|
229
|
+
checkWorkspace(Object.keys(lockfile.importers), settings.packages, host.major)
|
|
230
|
+
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)
|
|
233
|
+
const hook = createHook({ overrides, ignored: settings.ignoredOptionalDependencies, major: host.major })
|
|
234
|
+
checkProjects(lockfile, manifests, { hook, host, settings })
|
|
235
|
+
checkOptional(lockfile)
|
|
236
|
+
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 })
|
|
239
|
+
const { nodes, direct } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, host.major)
|
|
240
|
+
for (const node of nodes.values()) checkRegistry(node)
|
|
241
|
+
|
|
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)
|
|
245
|
+
const targets = binTargets({
|
|
246
|
+
nodes: byDir,
|
|
247
|
+
projects: linked.size === 0 ? manifests : new Map([...manifests, ...linked]),
|
|
248
|
+
direct,
|
|
249
|
+
links,
|
|
250
|
+
publicHoist: settings.publicHoistPattern?.length > 0,
|
|
251
|
+
building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
|
|
252
|
+
peers: settings.autoInstallPeers,
|
|
253
|
+
major: host.major,
|
|
254
|
+
})
|
|
255
|
+
|
|
256
|
+
const vfs = new Vfs()
|
|
257
|
+
vfs.mkdir('/node_modules/.pnpm', { recursive: true })
|
|
258
|
+
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 }
|
|
259
|
+
for (const node of byDir.values()) {
|
|
260
|
+
if (node.pkg.patchHash !== undefined) stats.patched++
|
|
261
|
+
try {
|
|
262
|
+
vfs.mkdir(`/${node.dir}`, { recursive: true })
|
|
263
|
+
for (const [path, file] of compose(node, given, targets.get(node.dir) ?? new Set(), { host, settings })) {
|
|
264
|
+
if (file.directory) vfs.mkdir(`/${node.dir}/${path}`, { recursive: true })
|
|
265
|
+
else if (writeOnce(vfs, `/${node.dir}/${path}`, file)) {
|
|
266
|
+
stats.files++
|
|
267
|
+
stats.bytes += file.data.length
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (error instanceof DeptreeError) throw error
|
|
272
|
+
throw new DeptreeError(error.message, quote(node.key), { cause: error })
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
for (const [path, target] of links) {
|
|
276
|
+
try {
|
|
277
|
+
vfs.mkdir(dirname(`/${path}`), { recursive: true })
|
|
278
|
+
vfs.symlink(linkTarget(path, target), `/${path}`)
|
|
279
|
+
} catch (error) {
|
|
280
|
+
throw new DeptreeError(`cannot be linked: ${error.message}`, quote(path), { cause: error })
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
checkLinks(vfs, links)
|
|
284
|
+
if (host.os === 'darwin') checkCollisions(vfs)
|
|
285
|
+
if (into === undefined) return { vfs, stats }
|
|
286
|
+
mount(vfs, into, host.os === 'darwin')
|
|
287
|
+
return { vfs: into, stats }
|
|
288
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Whether the lockfile is the one pnpm would install as it is. Before a
|
|
2
|
+
// frozen install pnpm holds it to the settings that shaped its resolution
|
|
3
|
+
// (@pnpm/lockfile.settings-checker's getOutdatedLockfileSetting): the
|
|
4
|
+
// catalogs, the overrides, the package extensions' checksum, the optional
|
|
5
|
+
// dependencies left out, the patches, and a few of its own settings. Where
|
|
6
|
+
// one differs, `--frozen-lockfile` refuses to install, and so does this,
|
|
7
|
+
// naming the setting as pnpm names it. An install here is always frozen.
|
|
8
|
+
// pnpm 11 takes two git specifiers of one commit in a catalog alike, and
|
|
9
|
+
// holds the patch hashes in the peers of a key to the patches too.
|
|
10
|
+
//
|
|
11
|
+
// The patches are hashed here, all of them, as pnpm reads every one it is
|
|
12
|
+
// configured with, whether or not a package installed uses it; each has to
|
|
13
|
+
// be given, by the path the settings name it by, and nothing else may be.
|
|
14
|
+
// Only one a package installed uses is read as a patch, where it is
|
|
15
|
+
// applied, as pnpm reads it.
|
|
16
|
+
|
|
17
|
+
import { normalize } from '@preventive/vfs/path.js'
|
|
18
|
+
import { DeptreeError, difference, quote } from '../error.js'
|
|
19
|
+
import { sha256Hex } from '../hash.js'
|
|
20
|
+
import { sameSpecifier } from './frozen.js'
|
|
21
|
+
import { checkPatchUse, checkPeerPatches } from './patches.js'
|
|
22
|
+
|
|
23
|
+
const outdated = (name, detail) => new DeptreeError(`${detail}, which a frozen install refuses`, name)
|
|
24
|
+
|
|
25
|
+
const SIDES = ['the lockfile', 'the settings']
|
|
26
|
+
|
|
27
|
+
// By selector, the hash and path pnpm computes of each configured patch,
|
|
28
|
+
// and by hash, the patch's text and path. `given` is the files by path.
|
|
29
|
+
async function hashPatches(configured, given) {
|
|
30
|
+
const texts = new Map()
|
|
31
|
+
for (const [key, text] of given) {
|
|
32
|
+
const path = normalize(key)
|
|
33
|
+
if (texts.has(path)) throw new DeptreeError('given twice, under two spellings', `patches[${quote(key)}]`)
|
|
34
|
+
texts.set(path, text)
|
|
35
|
+
}
|
|
36
|
+
const named = new Set()
|
|
37
|
+
const hashes = Object.create(null)
|
|
38
|
+
const byHash = new Map()
|
|
39
|
+
for (const [selector, spec] of Object.entries(configured ?? {})) {
|
|
40
|
+
const path = normalize(spec)
|
|
41
|
+
named.add(path)
|
|
42
|
+
if (!texts.has(path)) throw new DeptreeError(`the patch ${quote(path)} is not given, and pnpm reads every patch it is configured with`, `patchedDependencies[${quote(selector)}]`)
|
|
43
|
+
const text = texts.get(path)
|
|
44
|
+
const hash = await sha256Hex(text.replaceAll('\r\n', '\n'), `patches[${quote(path)}]`)
|
|
45
|
+
hashes[selector] = { hash, path }
|
|
46
|
+
if (!byHash.has(hash)) byHash.set(hash, { text, path })
|
|
47
|
+
}
|
|
48
|
+
for (const path of texts.keys()) {
|
|
49
|
+
if (!named.has(path)) throw new DeptreeError('no patchedDependencies setting names this patch', `patches[${quote(path)}]`)
|
|
50
|
+
}
|
|
51
|
+
return { hashes, byHash }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// pnpm 11's lockfile has each patch's hash alone, pnpm 10's its path too.
|
|
55
|
+
function checkPatches(locked, hashes, major) {
|
|
56
|
+
const flat = (patches) => Object.fromEntries(Object.entries(patches).map(([selector, { hash, path }]) => [selector, major >= 11 ? hash : `${hash} ${path}`]))
|
|
57
|
+
const detail = difference(flat(locked), flat(hashes), SIDES)
|
|
58
|
+
if (detail !== undefined) throw outdated('patchedDependencies', `the patches differ: ${detail}`)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Throws where pnpm would not install the lockfile as it is; hands back the
|
|
62
|
+
// patches by hash, their text and path, to apply where a snapshot names one.
|
|
63
|
+
// `overrides` is listOverrides's.
|
|
64
|
+
export async function checkUpToDate(lockfile, settings, overrides, given, major = 10) {
|
|
65
|
+
const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given)
|
|
66
|
+
for (const [name, catalog] of Object.entries(lockfile.catalogs)) {
|
|
67
|
+
for (const [alias, { specifier }] of Object.entries(catalog)) {
|
|
68
|
+
const configured = settings.catalogs[name]?.[alias]
|
|
69
|
+
if (!sameSpecifier(specifier, configured, major)) throw outdated('catalogs', `${quote(alias)} is ${quote(specifier)} in the lockfile's catalog ${quote(name)}, and ${configured === undefined ? 'nothing' : quote(configured)} in the settings`)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const overridden = difference(lockfile.overrides, Object.fromEntries(overrides.map(({ selector, spec }) => [selector, spec])), SIDES)
|
|
73
|
+
if (overridden !== undefined) throw outdated('overrides', `the overrides differ: ${overridden}`)
|
|
74
|
+
// pnpm checksums them with object-hash, which is not reproduced here.
|
|
75
|
+
if (settings.packageExtensions !== undefined && Object.keys(settings.packageExtensions).length > 0) throw new DeptreeError('package extensions are not supported: their checksum cannot be checked against the lockfile\'s here', 'packageExtensions')
|
|
76
|
+
if (lockfile.packageExtensionsChecksum !== undefined) throw outdated('packageExtensionsChecksum', 'the lockfile was resolved with package extensions, and the settings have none')
|
|
77
|
+
const ignored = (list) => JSON.stringify([...list].sort())
|
|
78
|
+
if (ignored(lockfile.ignoredOptionalDependencies) !== ignored(settings.ignoredOptionalDependencies)) throw outdated('ignoredOptionalDependencies', 'the optional dependencies left out differ')
|
|
79
|
+
checkPatches(lockfile.patchedDependencies, hashes, major)
|
|
80
|
+
const locked = lockfile.settings
|
|
81
|
+
if (locked.autoInstallPeers !== undefined && locked.autoInstallPeers !== settings.autoInstallPeers) throw outdated('settings.autoInstallPeers', `autoInstallPeers is ${locked.autoInstallPeers} in the lockfile`)
|
|
82
|
+
if (Boolean(locked.dedupePeers) !== settings.dedupePeers) throw outdated('settings.dedupePeers', `dedupePeers is ${Boolean(locked.dedupePeers)} in the lockfile`)
|
|
83
|
+
if ((locked.peersSuffixMaxLength ?? 1000) !== settings.peersSuffixMaxLength) throw outdated('settings.peersSuffixMaxLength', `peersSuffixMaxLength is ${locked.peersSuffixMaxLength ?? 'left at 1000'} in the lockfile`)
|
|
84
|
+
checkPatchUse(lockfile, hashes)
|
|
85
|
+
if (major >= 11) checkPeerPatches(lockfile, hashes)
|
|
86
|
+
return byHash
|
|
87
|
+
}
|