@preventive/deptree 1.0.0-alpha.5 → 1.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +36 -10
  5. package/pnpm.d.ts +116 -22
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +64 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +59 -10
  15. package/src/mount.js +95 -44
  16. package/src/npm/bins.js +71 -0
  17. package/src/npm/compat.js +92 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +80 -0
  21. package/src/npm/manifests.js +138 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/{pnpm/npmrc.js → npmrc.js} +5 -11
  28. package/src/patch.js +21 -31
  29. package/src/pnpm/bins.js +32 -103
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +49 -86
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +27 -70
  34. package/src/pnpm/gitignore.js +137 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +65 -55
  38. package/src/pnpm/hook.js +26 -31
  39. package/src/pnpm/inputs.js +67 -40
  40. package/src/pnpm/install.js +72 -115
  41. package/src/pnpm/local.js +21 -40
  42. package/src/pnpm/minimatch.js +328 -0
  43. package/src/pnpm/npm-packlist.js +221 -0
  44. package/src/pnpm/overrides.js +10 -49
  45. package/src/pnpm/package.js +120 -0
  46. package/src/pnpm/packlist.js +168 -109
  47. package/src/pnpm/patches.js +18 -25
  48. package/src/pnpm/projects.js +63 -107
  49. package/src/pnpm/readers.js +46 -55
  50. package/src/pnpm/settings.js +60 -97
  51. package/src/pnpm/tree.js +134 -149
  52. package/src/pnpm/uptodate.js +16 -28
  53. package/src/pnpm/workspace.js +122 -131
  54. package/src/project.js +41 -0
  55. package/src/soldeer/config.js +8 -24
  56. package/src/soldeer/inputs.js +2 -5
  57. package/src/soldeer/tree.js +20 -56
  58. package/src/soldeer/zip.js +17 -36
  59. package/src/tarball.js +38 -142
  60. package/src/yarn1/bins.js +9 -19
  61. package/src/yarn1/compat.js +9 -28
  62. package/src/yarn1/hoist.js +53 -68
  63. package/src/yarn1/inputs.js +16 -51
  64. package/src/yarn1/manifest.js +8 -23
  65. package/src/yarn1/package.js +24 -63
  66. package/src/yarn1/peers.js +8 -15
  67. package/src/yarn1/requests.js +19 -37
  68. package/src/yarn1/resolve.js +35 -111
  69. package/src/yarn1/settings.js +14 -41
  70. package/src/yarn1/tree.js +67 -91
  71. package/yarn1.d.ts +30 -2
  72. package/yarn1.js +1 -8
  73. package/src/pnpm/project.js +0 -97
  74. package/src/yarn1/glob.js +0 -52
  75. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,138 @@
1
+ // The project's package.json files, which npm ci reads from disk in place
2
+ // of the lockfile's entries, held to ask for exactly what those entries do.
3
+
4
+ import { join } from '@preventive/vfs/path.js'
5
+ import { DeptreeError, quote } from '../error.js'
6
+ import { own } from '../manifest.js'
7
+ import { checkEngine, checkPlatform } from './compat.js'
8
+ import { checkDevEngines } from './dev-engines.js'
9
+
10
+ const where = (dir) => `manifests[${quote(dir)}]`
11
+
12
+ function specsOf(manifest, list, at) {
13
+ const specs = manifest[list] ?? {}
14
+ if (typeof specs !== 'object' || Array.isArray(specs) || Object.values(specs).some((spec) => typeof spec !== 'string')) {
15
+ throw new DeptreeError('expected a mapping of names to specs, which npm fails without', `${at}.${list}`)
16
+ }
17
+ return specs
18
+ }
19
+
20
+ // Node#loadDeps: a name's edge is of the last list that has it, but a
21
+ // workspace's, which none takes over.
22
+ function edgesOf(manifest, at, workspaces, legacyPeerDeps) {
23
+ const edges = new Map()
24
+ const add = (name, type, spec) => {
25
+ if (edges.get(name)?.type === 'workspace') return
26
+ edges.delete(name)
27
+ edges.set(name, { type, spec })
28
+ }
29
+ for (const [name, dir] of workspaces) add(name, 'workspace', `file:${dir}`)
30
+ const peers = Object.entries(specsOf(manifest, 'peerDependencies', at))
31
+ const meta = manifest.peerDependenciesMeta || {}
32
+ if (!legacyPeerDeps) {
33
+ for (const [name, spec] of peers) if (!own(meta, name)?.optional) add(name, 'peer', spec)
34
+ for (const [name, spec] of peers) if (own(meta, name)?.optional) add(name, 'peerOptional', spec)
35
+ }
36
+ for (const [list, type] of [['dependencies', 'prod'], ['optionalDependencies', 'optional'], ['devDependencies', 'dev']]) {
37
+ for (const [name, spec] of Object.entries(specsOf(manifest, list, at))) add(name, type, spec)
38
+ }
39
+ return edges
40
+ }
41
+
42
+ const describe = (edge) => (edge === undefined ? 'nothing' : `${edge.type} ${quote(edge.spec)}`)
43
+
44
+ function compareEdges(edges, importer, at) {
45
+ for (const name of new Set([...edges.keys(), ...Object.keys(importer.edges)])) {
46
+ const ours = edges.get(name)
47
+ const theirs = importer.edges[name]
48
+ if (ours?.type === theirs?.type && ours?.spec === theirs?.spec) continue
49
+ throw new DeptreeError(`asks for ${quote(name)} as ${describe(ours)}, and the lockfile as ${describe(theirs)}, which npm ci refuses or resolves again`, at)
50
+ }
51
+ }
52
+
53
+ // npm 10's #checkRootEdges: unless the root's edges are its lockfile lists
54
+ // to the letter (no name in two lists, no peer under legacy-peer-deps, no
55
+ // workspace asked for by name too), npm 10 works every flag out again.
56
+ export function recalculates(lists, edges) {
57
+ const { dependencies = {}, devDependencies = {}, optionalDependencies = {}, peerDependencies = {}, peerDependenciesMeta = {} } = lists
58
+ const byType = { dev: devDependencies, optional: optionalDependencies, peer: { ...peerDependencies }, peerOptional: {}, prod: { ...dependencies } }
59
+ for (const [name, meta] of Object.entries(peerDependenciesMeta)) {
60
+ if (meta?.optional && own(byType.peer, name) !== undefined) {
61
+ byType.peerOptional[name] = byType.peer[name]
62
+ delete byType.peer[name]
63
+ }
64
+ }
65
+ for (const name of Object.keys(optionalDependencies)) delete byType.prod[name]
66
+ const left = new Set([...edges].filter(([, edge]) => edge.type !== 'workspace').map(([name]) => name))
67
+ for (const [type, specs] of Object.entries(byType)) {
68
+ for (const [name, spec] of Object.entries(specs)) {
69
+ if (edges.get(name)?.type !== type || edges.get(name).spec !== spec) return true
70
+ left.delete(name)
71
+ }
72
+ }
73
+ return left.size > 0
74
+ }
75
+
76
+ // map-workspaces names a workspace by its package.json, or its folder.
77
+ function workspacesOf(manifests) {
78
+ const workspaces = new Map()
79
+ for (const [dir, manifest] of manifests) {
80
+ if (dir === '.') continue
81
+ const segments = dir.split('/')
82
+ const name = manifest.name || (segments.at(-2)?.startsWith('@') ? segments.slice(-2).join('/') : segments.at(-1))
83
+ if (workspaces.has(name)) throw new DeptreeError(`the name of the workspace ${quote(workspaces.get(name))} too, which npm fails on`, where(dir))
84
+ workspaces.set(name, dir)
85
+ }
86
+ return workspaces
87
+ }
88
+
89
+ export const rootEdgesOf = (manifests, settings) => edgesOf(manifests.get('.'), where('.'), workspacesOf(manifests), settings.legacyPeerDeps)
90
+
91
+ // A workspace's name is held to the lockfile's by the root's edge to it.
92
+ // npm links its bins after every package's, so only one into its own
93
+ // node_modules changes the tree.
94
+ function checkWorkspace(dir, manifest, importer) {
95
+ if (/[#%]/u.test(dir)) throw new DeptreeError('a workspace whose directory has a "#" or "%", which npm escapes in one place and not another, is not supported', where(dir))
96
+ if (manifest.version !== importer.version) throw new DeptreeError(`is ${quote(String(manifest.version))}, and the lockfile has ${quote(String(importer.version))}, which npm ci refuses`, `${where(dir)}.version`)
97
+ if (manifest.directories?.bin !== undefined) throw new DeptreeError('directories.bin, which npm reads otherwise across its releases, is not supported', `${where(dir)}.directories.bin`)
98
+ const { bin } = manifest
99
+ const targets = typeof bin === 'string' ? [bin] : bin !== null && typeof bin === 'object' ? Object.values(bin) : []
100
+ if (targets.some((target) => typeof target === 'string' && /^node_modules(?:\/|$)/u.test(join('/', target.replace(/\\/gu, '/')).slice(1)))) {
101
+ throw new DeptreeError('a bin in its own node_modules, which is another package\'s, is not supported', `${where(dir)}.bin`)
102
+ }
103
+ }
104
+
105
+ // The root and workspaces are never left out; npm skips the root's engines
106
+ // where it has devEngines.
107
+ function checkHostOf(dir, manifest, host, settings) {
108
+ const reason = checkPlatform(manifest, host, where(dir))
109
+ if (reason !== undefined) throw new DeptreeError(`${reason}, which npm fails on`, where(dir))
110
+ if (!settings.engineStrict || (dir === '.' && manifest.devEngines)) return
111
+ const engine = checkEngine(manifest, host)
112
+ if (engine !== undefined) throw new DeptreeError(`${engine}, which npm fails on with engine-strict`, where(dir))
113
+ }
114
+
115
+ export function checkManifests({ lockfile, manifests, settings, host, rootEdges }) {
116
+ const root = manifests.get('.')
117
+ if (root.overrides != null && (typeof root.overrides !== 'object' || Object.keys(root.overrides).length > 0)) {
118
+ throw new DeptreeError('overrides, which change what npm asks for, are not supported', `${where('.')}.overrides`)
119
+ }
120
+ if (host.allowScripts && root.allowScripts !== undefined) throw new DeptreeError('allowScripts, which npm reads for whose bins to link, is not supported', `${where('.')}.allowScripts`)
121
+ checkDevEngines(root.devEngines, host, `${where('.')}.devEngines`)
122
+ for (const [dir, importer] of Object.entries(lockfile.importers)) {
123
+ if (dir === '.') continue
124
+ if (!importer.workspace) throw new DeptreeError('a directory linked by file:, not a workspace, is not supported', `importers[${quote(dir)}]`)
125
+ if (!manifests.has(dir)) throw new DeptreeError('a workspace of the lockfile npm does not find', where(dir))
126
+ }
127
+ for (const [dir, manifest] of manifests) {
128
+ const importer = lockfile.importers[dir]
129
+ if (importer === undefined) throw new DeptreeError('a workspace the lockfile does not have, which npm ci refuses', where(dir))
130
+ if (dir !== '.') checkWorkspace(dir, manifest, importer)
131
+ if (manifest.acceptDependencies != null || Object.values(importer.edges).some((edge) => edge.accept !== undefined)) {
132
+ throw new DeptreeError('acceptDependencies, which npm reads otherwise for devDependencies, is not supported', `${where(dir)}.acceptDependencies`)
133
+ }
134
+ compareEdges(dir === '.' ? rootEdges : edgesOf(manifest, where(dir), [], settings.legacyPeerDeps), importer, where(dir))
135
+ if (host.reuse && dir !== '.' && manifest.scripts?.prepare) throw new DeptreeError('a workspace with a prepare script, which npm 10 runs even with --ignore-scripts, is not supported', `${where(dir)}.scripts.prepare`)
136
+ checkHostOf(dir, manifest, host, settings)
137
+ }
138
+ }
@@ -0,0 +1,57 @@
1
+ // A tarball unpacked as pacote has tar unpack it: files alone, so no empty
2
+ // directory; modes with read and write for all, less a 0o022 umask, and no
3
+ // execute bits added, as npm reads no packument for a resolved URL. Where a
4
+ // .npmignore follows a .gitignore renamed to it, tar writes the second's
5
+ // bytes into the first's file, keeping its mode. What tar's releases read
6
+ // otherwise, or npm never packs, is refused.
7
+
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { fetchTarball, fromMirror, isModules, ownTarball, withDirs } from '../tarball.js'
10
+
11
+ const UMASK = 0o022
12
+
13
+ // npm's URL, a scope's `/` as `/`, which npm may write `%2f`.
14
+ const asNpm = (url) => fromMirror(url).replace(/^(https:\/\/registry\.npmjs\.org\/@[^/]+)%2f/iu, '$1/')
15
+
16
+ export function registryTarball({ name, version, resolution }, where) {
17
+ if (resolution === undefined) throw new DeptreeError('a package bundled in another is not supported', where)
18
+ if (resolution.type === 'git') throw new DeptreeError('a git repository is not supported', where)
19
+ if (resolution.tarball === undefined) throw new DeptreeError('a package with no resolved URL, which npm fetches by the registry\'s packument, whose bins it makes executable, is not supported', where)
20
+ return ownTarball(asNpm(resolution.tarball), name, version, resolution.integrity, where)
21
+ }
22
+
23
+ const FILES = new Set(['file', 'contiguous-file'])
24
+
25
+ function unpack(entries, where) {
26
+ const files = new Map()
27
+ const ignores = new Set()
28
+ let top
29
+ for (const { storedName, storedLinkname, type, mode, data, pax, globalPax } of entries) {
30
+ const segments = storedName.replace(/(?<=.)\/$/u, '').split('/')
31
+ if (segments.length > 1024 || /[\\\0]/u.test(storedName) || segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
32
+ throw new DeptreeError(`${quote(storedName)} is a name tar reads otherwise`, where)
33
+ }
34
+ if (globalPax.size > 0 || pax.has('size')) throw new DeptreeError(`${quote(storedName)} has a pax header tar's releases read otherwise`, where)
35
+ if (top !== undefined && segments[0] !== top) throw new DeptreeError('the tarball has entries under more than one directory', where)
36
+ top = segments[0]
37
+ if (!FILES.has(type)) continue
38
+ if (storedLinkname !== '') throw new DeptreeError(`${quote(storedName)} is a file with a link name, which tar's releases read otherwise`, where)
39
+ if (segments.length === 1) throw new DeptreeError(`${quote(storedName)} is a file at the top of the tarball`, where)
40
+ if (isModules(segments[1])) throw new DeptreeError(`${quote(storedName)} is in the package's own node_modules, where npm installs its dependencies, which is not supported`, where)
41
+ if ((mode & 0o7000) !== 0) throw new DeptreeError(`${quote(storedName)} has a setuid, setgid or sticky bit, which is not supported`, where)
42
+ let path = segments.slice(1).join('/')
43
+ if (segments.at(-1) === '.npmignore') ignores.add(path)
44
+ else if (segments.at(-1) === '.gitignore') {
45
+ path = path.replace(/\.gitignore$/u, '.npmignore')
46
+ if (ignores.has(path)) continue
47
+ }
48
+ files.set(path, { data, mode: files.get(path)?.mode ?? ((mode | 0o666) & ~UMASK & 0o777) })
49
+ }
50
+ return withDirs(files, where)
51
+ }
52
+
53
+ export async function fetchNpmPackage({ name, version, integrity }, where, check) {
54
+ const { bytes, entries, inflated } = await fetchTarball(name, version, integrity, where)
55
+ await check?.(bytes, inflated, where)
56
+ return unpack(entries, where)
57
+ }
@@ -0,0 +1,34 @@
1
+ // tar 7.5.19 on gives up once what it has inflated is over 1000 times what
2
+ // it has read, checked at each piece of output, so where depends on how the
3
+ // bytes arrive: a tarball is refused if any prefix inflates 900 times. Such
4
+ // a prefix is no longer than 1/900 of what all of it, or any longer prefix,
5
+ // inflates to: a bound that shrinks each time it is taken again.
6
+
7
+ import { decompress } from '@preventive/archive/compression.js'
8
+ import { DeptreeError } from '../error.js'
9
+
10
+ const RATIO = 900
11
+ const STEPS = 32
12
+
13
+ async function inflatedFrom(bytes, length) {
14
+ try {
15
+ return (await decompress(bytes.subarray(0, length), 'gzip')).length
16
+ } catch (error) {
17
+ if (error?.bytes instanceof Uint8Array && !error.limited) return error.bytes.length
18
+ throw error
19
+ }
20
+ }
21
+
22
+ export async function checkRatio(bytes, inflated, where) {
23
+ const refuse = (detail) => {
24
+ throw new DeptreeError(`the tarball ${detail}, which npm's tar may give up at`, where)
25
+ }
26
+ if (inflated >= RATIO * bytes.length) refuse(`inflates ${Math.floor(inflated / bytes.length)} times its length`)
27
+ let bound = Math.min(Math.floor(inflated / RATIO), bytes.length - 1)
28
+ for (let step = 0; bound > 0; step++) {
29
+ if (step === STEPS) refuse('inflates close to as far from some prefix')
30
+ const out = await inflatedFrom(bytes, bound)
31
+ if (out >= RATIO * bound) refuse(`inflates ${Math.floor(out / bound)} times its first ${bound} bytes`)
32
+ bound = Math.min(Math.floor(out / RATIO), bound - 1)
33
+ }
34
+ }
@@ -0,0 +1,67 @@
1
+ // The project's .npmrc. npm hands the install its settings as ini reads
2
+ // them, before validating them (`bin-links=0` links bins, "0" being
3
+ // truthy), so one that can change the tree is read only in a form with one
4
+ // reading. The rest only change where and how npm fetches, which the
5
+ // lockfile's integrities make moot, or what it prints.
6
+
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { parseNpmrc } from '../npmrc.js'
9
+
10
+ const FOLLOWED = { __proto__: null, 'legacy-peer-deps': 'legacyPeerDeps', 'engine-strict': 'engineStrict', 'bin-links': 'binLinks' }
11
+
12
+ const DEFAULTS = {
13
+ __proto__: null,
14
+ 'allow-git': ['all'],
15
+ 'allow-directory': ['all'],
16
+ 'allow-file': ['all'],
17
+ 'allow-remote': ['all'],
18
+ 'install-strategy': ['hoisted'],
19
+ 'install-links': ['false'],
20
+ force: ['false'],
21
+ 'dry-run': ['false'],
22
+ global: ['false'],
23
+ 'package-lock-only': ['false'],
24
+ usage: ['false'],
25
+ 'include-workspace-root': ['false'],
26
+ // Any other version npm fails on.
27
+ 'lockfile-version': ['1', '2', '3'],
28
+ }
29
+
30
+ // A credential not scoped to a registry fails npm ci; allow-scripts fails
31
+ // npm 11.16 on, or picks whose bins it links.
32
+ const REFUSED = new Set([
33
+ 'omit', 'include', 'production', 'dev', 'only', 'also', 'optional', 'os', 'cpu', 'libc', 'workspace', 'workspaces',
34
+ 'location', 'umask', 'prefix', 'globalconfig', 'userconfig', '_auth', '_authToken', '_authtoken', '-authtoken', 'username',
35
+ '_password', 'allow-scripts',
36
+ ])
37
+
38
+ // Pairs npm fails on, both set.
39
+ const SAVES = ['save-dev', 'save-optional', 'save-peer', 'save-prod']
40
+ const EXCLUSIVE = [
41
+ ['before', 'min-release-age'], ['expect-results', 'expect-result-count'], ['provenance', 'provenance-file'], ['prefer-online', 'prefer-offline'],
42
+ ...SAVES.flatMap((save, i) => SAVES.slice(i + 1).map((other) => [save, other])),
43
+ ]
44
+
45
+ // ini unquotes, unescapes and cuts at `;` or `#` a key as it does a value,
46
+ // and npm fills a `${VAR}` in either from the environment.
47
+ const PLAIN = /^[^"'`;#\\]*$/u
48
+ const plain = (text) => PLAIN.test(text) && !text.includes('${')
49
+
50
+ export function readSettings(text) {
51
+ const settings = { legacyPeerDeps: false, engineStrict: false, binLinks: true }
52
+ const seen = new Set()
53
+ for (const { key, value, list, line } of text === undefined ? [] : parseNpmrc(text)) {
54
+ const where = `.npmrc:${line}`
55
+ if (!plain(key)) throw new DeptreeError(`${quote(key)} is quoted, escaped, commented or taken from the environment, which is not read here`, where)
56
+ seen.add(key)
57
+ if (REFUSED.has(key)) throw new DeptreeError(`${quote(key)} is a setting not supported here: it may change what npm installs`, where)
58
+ const accepted = key in FOLLOWED ? ['true', 'false'] : DEFAULTS[key]
59
+ if (accepted === undefined) continue
60
+ if (list || !accepted.includes(value)) throw new DeptreeError(`expected ${accepted.join(' or ')} for ${quote(key)}`, where)
61
+ if (key in FOLLOWED) settings[FOLLOWED[key]] = value === 'true'
62
+ }
63
+ for (const pair of EXCLUSIVE) {
64
+ if (pair.every((key) => seen.has(key))) throw new DeptreeError(`${quote(pair[0])} and ${quote(pair[1])} are both set, which npm fails on`, '.npmrc')
65
+ }
66
+ return settings
67
+ }
@@ -0,0 +1,136 @@
1
+ // The tree `npm ci --ignore-scripts` makes, but node_modules/.bin and npm's
2
+ // node_modules/.package-lock.json.
3
+
4
+ import { parseNpmLockfile } from '@preventive/lockfile/npm.js'
5
+ import { Vfs } from '@preventive/vfs'
6
+ import { dirname, relative } from '@preventive/vfs/path.js'
7
+ import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
8
+ import { eachConcurrently } from '../concurrent.js'
9
+ import { DeptreeError, quote } from '../error.js'
10
+ import { checkNoModules, isInside, makeDirs, mount, writeFiles, writeLink } from '../mount.js'
11
+ import { fixBins } from './bins.js'
12
+ import { skippedOf } from './compat.js'
13
+ import { graphOf } from './graph.js'
14
+ import { checkHost, inputsOf } from './inputs.js'
15
+ import { checkManifests, recalculates, rootEdgesOf } from './manifests.js'
16
+ import { fetchNpmPackage, registryTarball } from './package.js'
17
+ import { checkRatio } from './ratio.js'
18
+
19
+ const whereOf = (node) => `packages[${quote(node.location)}]`
20
+
21
+ function checkLinks(lockfile) {
22
+ for (const [location, target] of Object.entries(lockfile.links)) {
23
+ const where = `packages[${quote(location)}]`
24
+ const importer = lockfile.importers[target]
25
+ if (!importer?.workspace) throw new DeptreeError(`a link to ${importer === undefined ? 'a package' : 'the project'} is not supported`, where)
26
+ if (location !== `node_modules/${importer.name}`) throw new DeptreeError(`a workspace linked other than as node_modules/${importer.name} is not supported`, where)
27
+ }
28
+ }
29
+
30
+ const LISTS = { prod: 'dependencies', optional: 'optionalDependencies', dev: 'devDependencies', peer: 'peerDependencies', peerOptional: 'peerDependencies', workspace: 'workspaces' }
31
+ const WILDCARD = /(?:^|[^\w-])[*Xx]\.\d/u
32
+
33
+ // semver 7.8.4 (npm 11.17 on) reads `1.x.0` otherwise; npm 10 resolves an
34
+ // unmet optional peer again, where npm 11 takes it as it is.
35
+ function checkSpecs(lockfile, host) {
36
+ for (const [location, pkg] of [...Object.entries(lockfile.importers), ...Object.entries(lockfile.packages)]) {
37
+ for (const [name, { type, spec, accept, target }] of Object.entries(pkg.edges)) {
38
+ const where = `packages[${quote(location === '.' ? '' : location)}].${LISTS[type]}[${quote(name)}]`
39
+ const ranges = [spec, accept].filter((range) => range !== undefined)
40
+ if (ranges.some((range) => WILDCARD.test(range))) throw new DeptreeError(`${quote(spec)} has a wildcard before a number, which npm's releases read otherwise`, where)
41
+ if (!host.reuse || type !== 'peerOptional' || target === undefined) continue
42
+ const { version } = target.startsWith('link:') ? lockfile.importers[target.slice(5)] : lockfile.packages[target]
43
+ if (!ranges.some((range) => validRange(range, true) !== null && satisfies(version ?? '', range, true))) {
44
+ throw new DeptreeError(`${quote(spec)} is an optional peer the lockfile does not meet, which npm 10 resolves again`, where)
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ // Every URL is checked before any is fetched.
51
+ async function fetchAll(nodes, host) {
52
+ const tarballs = new Map()
53
+ for (const node of nodes) {
54
+ const tarball = registryTarball(node.pkg, whereOf(node))
55
+ const key = `${tarball.name}@${tarball.version} ${tarball.integrity}`
56
+ if (!tarballs.has(key)) tarballs.set(key, { tarball, where: whereOf(node), nodes: [] })
57
+ tarballs.get(key).nodes.push(node)
58
+ }
59
+ const fetched = new Map()
60
+ await eachConcurrently(tarballs.values(), async ({ tarball, where, nodes: copies }) => {
61
+ const pkg = { ...await fetchNpmPackage(tarball, where, host.ratio ? checkRatio : undefined), integrity: tarball.integrity }
62
+ for (const node of copies) fetched.set(node, pkg)
63
+ }, ({ where }) => where)
64
+ return { fetched, tarballs: tarballs.size }
65
+ }
66
+
67
+ // npm 10 makes every package's directory before leaving out those the host
68
+ // cannot run, and leaves the directories they were in.
69
+ function residueOf(nodes, skipped) {
70
+ const removed = [...skipped].map((node) => node.location)
71
+ const inRemoved = (dir) => removed.some((location) => dir === location || dir.startsWith(`${location}/`))
72
+ const dirs = new Set()
73
+ for (const location of removed) {
74
+ for (let dir = dirname(location); dir !== '.' && !nodes.has(dir) && !inRemoved(dir); dir = dirname(dir)) dirs.add(dir)
75
+ }
76
+ return dirs
77
+ }
78
+
79
+ function writeTree({ lockfile, kept, fetched, changed, residue }) {
80
+ const vfs = new Vfs()
81
+ const stats = { files: 0, bytes: 0, links: 0 }
82
+ for (const node of kept) {
83
+ const { files, dirs } = fetched.get(node)
84
+ const fixed = changed.get(node.location)
85
+ writeFiles(vfs, node.location, { dirs, files: fixed === undefined ? files : new Map([...files].map(([path, file]) => [path, fixed.get(path) ?? file])) }, stats)
86
+ }
87
+ // checkLinks has each a workspace's, in the project.
88
+ for (const [location, target] of Object.entries(lockfile.links)) {
89
+ if (!isInside(target)) throw new DeptreeError('links out of the project', whereOf({ location }))
90
+ writeLink(vfs, location, relative(`/${dirname(location)}`, `/${target}`))
91
+ stats.links++
92
+ }
93
+ for (const dir of residue) makeDirs(vfs, dir)
94
+ return { vfs, stats }
95
+ }
96
+
97
+ // The lockfile reader refuses what does not parse.
98
+ function rootListsOf(text) {
99
+ try {
100
+ return JSON.parse(text)?.packages?.[''] ?? {}
101
+ } catch {
102
+ return {}
103
+ }
104
+ }
105
+
106
+ export async function buildNpmTree(options) {
107
+ const { host: given, vfs: into } = options ?? {}
108
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
109
+ const host = checkHost(given)
110
+ const folded = host.os === 'darwin'
111
+ const inputs = inputsOf(options ?? {}, folded)
112
+ // Refused before anything is fetched; mount checks again.
113
+ if (into !== undefined) checkNoModules(into, folded)
114
+ const { settings, manifests } = inputs
115
+ const rootEdges = rootEdgesOf(manifests, settings)
116
+ // npm 10 takes the lockfile's flags as written, where it can.
117
+ const recalculated = !host.reuse || recalculates(rootListsOf(inputs.lockfile), rootEdges)
118
+ const lockfile = parseNpmLockfile(inputs.lockfile, { semver: { satisfies, valid, validRange }, legacyPeerDeps: settings.legacyPeerDeps, npm: recalculated ? host.npm : undefined })
119
+ checkManifests({ lockfile, manifests, settings, host, rootEdges })
120
+ checkLinks(lockfile)
121
+ checkSpecs(lockfile, host)
122
+ const nodes = graphOf(lockfile, manifests)
123
+ const skipped = skippedOf(nodes, host, settings)
124
+ const kept = [...nodes.values()].filter((node) => node.kind === 'package' && !skipped.has(node))
125
+ const { fetched, tarballs } = await fetchAll(kept, host)
126
+ const changed = settings.binLinks ? fixBins(kept, fetched) : new Map()
127
+ const residue = host.reuse ? residueOf(nodes, skipped) : new Set()
128
+ const { vfs, stats: written } = writeTree({ lockfile, kept, fetched, changed, residue })
129
+ const packages = Object.keys(lockfile.packages).length
130
+ const stats = { packages, installed: kept.length, skipped: packages - kept.length, tarballs, ...written }
131
+ const installed = kept.map((node) => {
132
+ const { name, version, dev, optional, devOptional, peer } = node.pkg
133
+ return { path: node.location, name, version, integrity: fetched.get(node).integrity, dev, optional, devOptional, peer }
134
+ })
135
+ return { vfs: mount(vfs, into, folded), stats, installed }
136
+ }
@@ -0,0 +1,20 @@
1
+ // What changes the tree between the npm releases supported. `reuse` is npm
2
+ // 10's ci, building on the tree it loaded the lockfile into: lockfile flags
3
+ // as written, optional packages left out after their directories are made,
4
+ // an unmet optional peer resolved again, a workspace's prepare script run.
5
+
6
+ import { DeptreeError, quote } from '../error.js'
7
+
8
+ const SUPPORTED = [[[10, 9, 3], [10, 9, 9]], [[11, 11, 1], [11, 21, 0]]]
9
+
10
+ const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
11
+ const show = ([from, to]) => (compare(from, to) === 0 ? from.join('.') : `${from.join('.')} to ${to.join('.')}`)
12
+
13
+ export function profileOf(npm) {
14
+ const version = /^(\d+)\.(\d+)\.(\d+)$/u.exec(npm)?.slice(1).map(Number)
15
+ if (version === undefined || !SUPPORTED.some(([from, to]) => compare(version, from) >= 0 && compare(version, to) <= 0)) {
16
+ throw new DeptreeError(`npm ${quote(npm)} is not supported: only ${SUPPORTED.map(show).join(', and ')}`, 'host.npm')
17
+ }
18
+ const since = (bound) => compare(version, bound) >= 0
19
+ return { npm, reuse: version[0] === 10, ratio: version[0] === 10 ? since([10, 9, 9]) : since([11, 18, 0]), inert: since([11, 13, 0]), allowScripts: since([11, 16, 0]) }
20
+ }
@@ -1,16 +1,10 @@
1
- // An .npmrc read as the `ini` package reads it for npm and pnpm, as far as
2
- // a key and the text after its `=` go: a line per setting, `#` or `;` in
3
- // front for a comment, `key[]` to add to a list, and a key with no `=`
4
- // set to true. What a value means is left to the setting that reads it,
5
- // which takes it only in a form with one reading (settings.js); a value
6
- // ini would unquote, unescape, cut at a `;` or `#`, or fill in from the
7
- // environment is refused there rather than read two ways. A section, which
8
- // npm reads under a prefix no setting here has, is refused outright.
1
+ // An .npmrc as the `ini` package reads it for npm and pnpm, as far as a key
2
+ // and the text after its `=` go; each settings.js refuses a value ini would
3
+ // unquote, unescape, cut at a `;` or `#`, or fill in from the environment. A
4
+ // section, which npm reads under a prefix no setting here has, is refused.
9
5
 
10
- import { DeptreeError } from '../error.js'
6
+ import { DeptreeError } from './error.js'
11
7
 
12
- // Each setting in the order written: `line` counts from one, and `list`
13
- // says the key was written with `[]`, which is dropped from it.
14
8
  export function parseNpmrc(text) {
15
9
  const settings = []
16
10
  const lines = text.split(/\r\n|\r|\n/u)
package/src/patch.js CHANGED
@@ -1,17 +1,9 @@
1
- // A patch applied to a package's files, as `pnpm patch-commit`
2
- // writes one: a git diff, a `diff --git a/<path> b/<path>` header for each
3
- // file, and unified hunks, a path relative to the package's directory. A
4
- // file is changed, created from /dev/null or deleted; a rename, a copy, a
5
- // change of mode and a binary patch are refused, as is anything else
6
- // between one file's hunks and the next header.
7
- //
8
- // A hunk applies where it says and nowhere else, every line of context and
9
- // every line it removes the same, byte for byte, as the file has there.
10
- // pnpm (@pnpm/patch-package) would also look up to twenty lines away and
11
- // compare lines with their trailing whitespace dropped; a patch that needs
12
- // either is refused here, so a patch applied here leaves the file as pnpm
13
- // would. So is a hunk that inserts after a line and keeps no context,
14
- // which pnpm puts a line early.
1
+ // A patch as `pnpm patch-commit` writes one: a git diff of files changed,
2
+ // created or deleted. A hunk applies where it says, its context and removed
3
+ // lines the same byte for byte. pnpm (@pnpm/patch-package) would also look
4
+ // up to twenty lines away and drop trailing whitespace, and puts a hunk that
5
+ // inserts after a line with no context a line early; a patch that needs any
6
+ // of that is refused, so one applied here leaves the file as pnpm would.
15
7
 
16
8
  import { applyChangeSet, parseDiff } from '@preventive/diff'
17
9
  import { DeptreeError, quote } from './error.js'
@@ -21,22 +13,27 @@ const MODE = /^(?:new|deleted) file mode (100644|100755)$/u
21
13
  const INDEX = /^index [\da-f]+\.\.[\da-f]+(?: 100644| 100755)?$/u
22
14
  const HUNK_LINE = /^(?:@@ |[ +\\-]|$)/u
23
15
 
24
- // The path a header names on both sides, or undefined where the two differ.
25
16
  function pathOf(header) {
26
17
  const rest = header.slice(HEADER.length)
27
18
  const path = rest.slice(0, (rest.length - 3) / 2)
28
19
  return rest === `${path} b/${path}` ? path : undefined
29
20
  }
30
21
 
22
+ // git quotes a path with a control character, and by default one with any
23
+ // other non-ASCII one. Of what it may leave unquoted, a backslash, a
24
+ // separator on Windows, and what reads otherwise than it is written (a line
25
+ // or paragraph separator, a bidirectional control) are refused, as the
26
+ // lockfile reader refuses them in a path.
27
+ const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
28
+
31
29
  function checkPath(path, where) {
32
- if (path === undefined || path.startsWith('"') || path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
30
+ if (path === undefined || path.startsWith('"') || UNSAFE.test(path) || path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
33
31
  throw new DeptreeError('expected a header naming one relative path on both sides', where)
34
32
  }
35
33
  return path
36
34
  }
37
35
 
38
- // One file's header: what happens to the file, and the `---`/`+++` pair
39
- // naming it, which a patch without hunks may leave out.
36
+ // The `---`/`+++` pair may be left out where the file has no hunks.
40
37
  function readHeader(lines, path, where) {
41
38
  let change = 'modify'
42
39
  let mode = 0o644
@@ -57,9 +54,8 @@ function readHeader(lines, path, where) {
57
54
  return { change, mode, body: i }
58
55
  }
59
56
 
60
- // The hunks of one file, each line of them read: parseDiff passes over
61
- // what it does not read, so every line has to be one a hunk holds, and
62
- // every one of those in a hunk.
57
+ // parseDiff passes over what it does not read, so every line is checked to
58
+ // be one a hunk holds, and every one of those to be in a hunk.
63
59
  function readHunks(lines, where) {
64
60
  if (lines.length === 0) return { hunks: [], blocks: [] }
65
61
  if (!lines.every((line) => HUNK_LINE.test(line))) throw new DeptreeError('expected only hunks after the header', where)
@@ -76,8 +72,7 @@ function readHunks(lines, where) {
76
72
  export function parsePatch(text, where) {
77
73
  if (text.includes('\r')) throw new DeptreeError('a carriage return is not supported', where)
78
74
  if (!text.startsWith(HEADER)) throw new DeptreeError(`expected ${quote(HEADER)} first`, where)
79
- const sections = text.split(/\n(?=diff --git )/u)
80
- return sections.map((section) => {
75
+ return text.split(/\n(?=diff --git )/u).map((section) => {
81
76
  const lines = section.split('\n')
82
77
  if (lines.at(-1) === '') lines.pop()
83
78
  const path = checkPath(pathOf(lines[0]), `${where}: ${quote(lines[0])}`)
@@ -87,8 +82,6 @@ export function parsePatch(text, where) {
87
82
  })
88
83
  }
89
84
 
90
- // Holds each hunk to the lines it names in `text`, and hands back what
91
- // applying them makes of it.
92
85
  function applyTo(text, { hunks, blocks, where }) {
93
86
  const records = text.split(/(?<=\n)/u)
94
87
  let end = 0
@@ -121,12 +114,9 @@ function bytesOf(text, where) {
121
114
 
122
115
  const parentsOf = (path) => path.split('/').slice(0, -1).map((_, index, names) => names.slice(0, index + 1).join('/'))
123
116
 
124
- // Applies a parsed patch to a package's files: a Map of each path in the
125
- // package to a file, `{ data, mode }`, or to `{ directory: true }` for a
126
- // directory. A changed file keeps its mode, and a deleted one leaves its
127
- // directory, empty or not, as pnpm leaves them. A file made has the mode
128
- // its header gives, or `createdMode` where given, as pnpm 12 writes one
129
- // plain. Hands back a new Map; the one given is left as it is.
117
+ // `files` maps each path to `{ data, mode }` or `{ directory: true }`. A
118
+ // deleted file leaves its directory, empty or not, as pnpm does; a created
119
+ // one has `createdMode` where given, as pnpm 12 writes one plain.
130
120
  export function applyPatch(files, patch, { createdMode } = {}) {
131
121
  const next = new Map(files)
132
122
  for (const file of patch) {