@preventive/deptree 1.0.0-alpha.4 → 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
package/src/mount.js CHANGED
@@ -1,11 +1,9 @@
1
- // A tree built on its own, mounted into a Vfs the caller already has, at
2
- // its root: the lockfile's directory. Nothing there is written over or
3
- // removed. A node_modules there already, anywhere, is refused, or for
4
- // another tree what its `check` refuses: kept beside the tree, Node would
5
- // read it as the tree's, and removed, it would be the caller's lost;
6
- // neither is safe. Everything is checked before anything is written, so a
7
- // refusal leaves the Vfs as it was.
1
+ // A tree mounted into the caller's Vfs at the lockfile's directory, writing
2
+ // over and removing nothing; Vfs.mount judges it whole first, so a refusal
3
+ // leaves the Vfs as it was. A node_modules there already is refused: kept,
4
+ // Node would read it as the tree's, and removed, the caller's would be lost.
8
5
 
6
+ import { VfsError } from '@preventive/vfs'
9
7
  import { basename, dirname } from '@preventive/vfs/path.js'
10
8
  import { DeptreeError, quote } from './error.js'
11
9
 
@@ -14,8 +12,6 @@ export const fold = (name) => name.normalize('NFD').toLowerCase()
14
12
 
15
13
  const where = (path) => `vfs[${quote(path)}]`
16
14
 
17
- // Refuses a Vfs that holds a node_modules, or, where names are `folded`, a
18
- // name that is one there.
19
15
  export function checkNoModules(vfs, folded) {
20
16
  for (const { path } of vfs.walk('/')) {
21
17
  const name = basename(path)
@@ -25,47 +21,102 @@ export function checkNoModules(vfs, folded) {
25
21
  }
26
22
  }
27
23
 
28
- function typeAt(vfs, path) {
24
+ function checkCollisions(vfs) {
25
+ const [clash] = vfs.collisions(fold)
26
+ if (clash !== undefined) throw new DeptreeError(`${quote(clash.names[0])} and ${quote(clash.names[1])} are one name on macOS`, quote(clash.path))
27
+ }
28
+
29
+ // A path within a directory: no segment of it empty, `.` or `..`.
30
+ export const isInside = (path) => path !== '' && path.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..')
31
+
32
+ const asRefusal = (error, what, path) => {
33
+ if (error instanceof VfsError) return new DeptreeError(`cannot be ${what}: ${error.message}`, quote(path), { cause: error })
34
+ return error
35
+ }
36
+
37
+ // Each builder holds what a tarball names and where a package goes to that
38
+ // first, and makes no link where a package is written after. What is made
39
+ // is held to it again, so that one slip puts nothing out of the tree or the
40
+ // package's directory. A directory: a place within the tree, each one on
41
+ // the way made where its parent is, or there already and no link. `real`
42
+ // keeps the directories found so, as a package's files share them.
43
+ export function makeDirs(vfs, path, real = new Set()) {
44
+ if (!isInside(path)) throw new DeptreeError('is not a place within the tree', quote(path))
45
+ let at = ''
46
+ for (const segment of path.split('/')) {
47
+ at = `${at}/${segment}`
48
+ if (real.has(at)) continue
49
+ if (vfs.isSymlink(at)) throw new DeptreeError('would be written through a link', quote(at.slice(1)))
50
+ try {
51
+ if (!vfs.isDirectory(at)) vfs.mkdir(at)
52
+ } catch (error) {
53
+ throw asRefusal(error, 'made', at.slice(1))
54
+ }
55
+ real.add(at)
56
+ }
57
+ return `/${path}`
58
+ }
59
+
60
+ // A file: a path within the package's directory, in a directory found as
61
+ // above, and no link at the path itself.
62
+ export function checkWrite(vfs, root, path, real) {
63
+ const at = `/${root}/${path}`
64
+ if (!isInside(root) || !isInside(path)) throw new DeptreeError('is not a path within the package', quote(at.slice(1)))
65
+ const parent = dirname(at)
66
+ if (!real.has(parent)) {
67
+ if (vfs.realpath(parent) !== parent) throw new DeptreeError('would be written through a link', quote(at.slice(1)))
68
+ real.add(parent)
69
+ }
70
+ if (vfs.isSymlink(at)) throw new DeptreeError('would be written through a link', quote(at.slice(1)))
71
+ return at
72
+ }
73
+
74
+ // A link at `path`, a place within the tree under directories it spells,
75
+ // to `target`, as given.
76
+ export function writeLink(vfs, path, target) {
77
+ if (!isInside(path)) throw new DeptreeError('is not a place within the tree', quote(path))
78
+ if (path.includes('/')) makeDirs(vfs, dirname(path))
29
79
  try {
30
- return vfs.lstat(path).type
80
+ vfs.symlink(target, `/${path}`)
31
81
  } catch (error) {
32
- if (error.code === 'ENOENT') return undefined
33
- throw error
82
+ throw asRefusal(error, 'made', path)
34
83
  }
35
84
  }
36
85
 
37
- // Moves `tree` into `target`: each directory of the tree is one there
38
- // already or is made, and each file and link is written where nothing is,
39
- // and where names are `folded`, none beside a name it would be one with.
40
- // Each file is taken out of `tree` as it is written.
41
- export function mount(tree, target, folded, check = checkNoModules) {
42
- check(target, folded)
43
- // The tree's entries, parents first, each with what is there already;
44
- // under a directory that is not there, nothing is.
45
- const absent = new Set()
46
- const entries = []
47
- for (const { path, type } of tree.walk('/')) {
48
- if (path === '/') continue
49
- const parent = dirname(path)
50
- const existing = absent.has(parent) ? undefined : typeAt(target, path)
51
- if (existing === undefined && type === 'directory') absent.add(path)
52
- entries.push({ path, type, existing })
53
- if (existing !== undefined && (type !== 'directory' || existing !== 'directory')) {
54
- throw new DeptreeError(`a ${existing} is there already, where the tree has a ${type}`, where(path))
55
- }
56
- if (!folded || existing !== undefined || absent.has(parent)) continue
57
- const name = basename(path)
58
- const clash = target.readdir(parent).find((other) => fold(other) === fold(name))
59
- if (clash !== undefined) throw new DeptreeError(`${quote(clash)} is there already, which is one name with ${quote(name)} on macOS`, where(path))
86
+ // `root` is the package's directory in the tree, without a leading `/`.
87
+ export function writeFiles(vfs, root, { dirs, files }, stats, skip = () => false) {
88
+ const real = new Set()
89
+ makeDirs(vfs, root, real)
90
+ for (const dir of dirs) {
91
+ if (skip(dir)) continue
92
+ if (!isInside(dir)) throw new DeptreeError('is not a path within the package', quote(`${root}/${dir}`))
93
+ makeDirs(vfs, `${root}/${dir}`, real)
60
94
  }
61
- for (const { path, type, existing } of entries) {
62
- if (type === 'directory') {
63
- if (existing === undefined) target.mkdir(path)
64
- } else if (type === 'symlink') {
65
- target.symlink(tree.readlink(path), path)
66
- } else {
67
- target.writeFile(path, tree.readFile(path), { mode: tree.lstat(path).mode })
68
- tree.unlink(path)
95
+ for (const [path, file] of files) {
96
+ if (skip(path)) continue
97
+ const at = checkWrite(vfs, root, path, real)
98
+ try {
99
+ vfs.writeFile(at, file.data, { mode: file.mode })
100
+ } catch (error) {
101
+ throw asRefusal(error, 'written', `${root}/${path}`)
69
102
  }
103
+ stats.files++
104
+ stats.bytes += file.data.length
105
+ }
106
+ }
107
+
108
+ // `target` with `tree` in it, or `tree` where there is none; on macOS, two
109
+ // names that are one there are refused first. A clash is refused by what is
110
+ // there; at the root, a path there is the tree's too. The tree's bytes are
111
+ // shared with `target`, not copied.
112
+ export function mount(tree, target, folded, check = checkNoModules) {
113
+ if (folded) checkCollisions(tree)
114
+ if (target === undefined) return tree
115
+ check(target, folded)
116
+ const clash = (path, [there]) => {
117
+ if (there !== path) throw new DeptreeError(`${quote(basename(there))} is there already, which is one name with ${quote(basename(path))} on macOS`, where(path))
118
+ throw new DeptreeError(`a ${target.lstat(path).type} is there already, where the tree has a ${tree.lstat(path).type}`, where(path))
70
119
  }
120
+ target.mount(tree, '/', { clash, fold: folded ? fold : undefined })
121
+ return target
71
122
  }
@@ -0,0 +1,71 @@
1
+ // What bin-links does to the packages' files, the .bin links aside. Bins
2
+ // come from the lockfile; in a node_modules, the first package to claim a
3
+ // name links it, by Intl.Collator('en') on paths, as npm sorts its nodes,
4
+ // even where its target is missing. A linked target is made 0o755, its
5
+ // first line's CRLF made LF where that is a shebang in the first 2048 bytes.
6
+
7
+ import { basename, dirname, join } from '@preventive/vfs/path.js'
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { isModules } from '../tarball.js'
10
+
11
+ const collator = new Intl.Collator('en')
12
+
13
+ // npm-normalize-package-bin.
14
+ function binsOf(bin) {
15
+ const bins = new Map()
16
+ for (const [key, target] of Object.entries(bin)) {
17
+ const name = join('/', basename(key.replace(/[\\:]/gu, '/'))).slice(1)
18
+ const path = join('/', target.replace(/\\/gu, '/')).slice(1)
19
+ if (name !== '' && path !== '') bins.set(name, path.replace(/\/$/u, ''))
20
+ }
21
+ return bins
22
+ }
23
+
24
+ function modulesOf(location) {
25
+ const parent = dirname(location)
26
+ return basename(parent) === 'node_modules' ? parent : dirname(parent)
27
+ }
28
+
29
+ const decoder = new TextDecoder('utf-8', { fatal: true })
30
+
31
+ // bin-links rewrites the file as UTF-8, which it has to be here.
32
+ function fixed({ data }, where) {
33
+ const newline = data.subarray(0, 2048).indexOf(0x0a)
34
+ if (data[0] !== 0x23 || data[1] !== 0x21 || newline < 4 || data[newline - 1] !== 0x0d) return { data, mode: 0o755 }
35
+ try {
36
+ decoder.decode(data)
37
+ } catch {
38
+ throw new DeptreeError('a bin with a CRLF shebang that is not UTF-8, which npm rewrites with replacement characters, is not supported', where)
39
+ }
40
+ const unix = new Uint8Array(data.length - 1)
41
+ unix.set(data.subarray(0, newline - 1))
42
+ unix.set(data.subarray(newline), newline - 1)
43
+ return { data: unix, mode: 0o755 }
44
+ }
45
+
46
+ // The files linking changes, by each package's location.
47
+ export function fixBins(nodes, fetched) {
48
+ const seen = new Set()
49
+ const changed = new Map()
50
+ for (const node of nodes.toSorted((a, b) => collator.compare(a.location, b.location))) {
51
+ const { location, pkg } = node
52
+ const { files, dirs } = fetched.get(node)
53
+ const where = `packages[${quote(location)}].bin`
54
+ for (const [name, path] of binsOf(pkg.bin)) {
55
+ const link = `${modulesOf(location)}/.bin/${name}`
56
+ if (seen.has(link)) continue
57
+ seen.add(link)
58
+ const segments = path.split('/')
59
+ if (isModules(segments[0])) throw new DeptreeError(`${quote(path)} is in the package's own node_modules, where npm installs its dependencies, which is not supported`, where)
60
+ if (segments.slice(1).some((_, i) => files.has(segments.slice(0, i + 1).join('/')))) throw new DeptreeError(`${quote(path)} runs through a file, which npm fails on`, where)
61
+ const file = files.get(path)
62
+ if (file === undefined) {
63
+ if (!dirs.has(path)) continue
64
+ throw new DeptreeError(`${quote(path)} is a directory, which is not supported`, where)
65
+ }
66
+ if (!changed.has(location)) changed.set(location, new Map())
67
+ changed.get(location).set(path, fixed(file, where))
68
+ }
69
+ }
70
+ return changed
71
+ }
@@ -0,0 +1,92 @@
1
+ // npm-install-checks' checkPlatform and checkEngine, and what npm leaves out
2
+ // for them: an optional package the host cannot run, with its optionalSet.
3
+
4
+ import { satisfies } from '@preventive/upstream/semver.js'
5
+ import { DeptreeError, quote } from '../error.js'
6
+
7
+ // npm-install-checks' checkList.
8
+ function takes(value, list) {
9
+ const values = typeof list === 'string' ? [list] : list
10
+ if (values.length === 1 && values[0] === 'any') return true
11
+ const negated = (entry) => entry.startsWith('!')
12
+ if (values.includes(`!${value}`)) return false
13
+ return values.some((entry) => !negated(entry) && entry === value) || values.every(negated)
14
+ }
15
+
16
+ function listOf(pkg, key, at) {
17
+ const list = pkg[key]
18
+ if (!list || typeof list === 'string' || (Array.isArray(list) && list.every((entry) => typeof entry === 'string'))) return list || undefined
19
+ throw new DeptreeError('expected a string or a sequence of strings, which npm fails without', `${at}.${key}`)
20
+ }
21
+
22
+ // A libc fails a host with none, whatever it names.
23
+ export function checkPlatform(pkg, host, at) {
24
+ for (const key of ['os', 'cpu', 'libc']) {
25
+ const list = listOf(pkg, key, at)
26
+ if (list !== undefined && (host[key] === undefined || !takes(host[key], list))) return `its ${key}, ${quote(JSON.stringify(list))}, is not the host's`
27
+ }
28
+ return undefined
29
+ }
30
+
31
+ export function checkEngine(pkg, host) {
32
+ const { engines } = pkg
33
+ if (!engines) return undefined
34
+ const options = { includePrerelease: true }
35
+ if (engines.node && !satisfies(`v${host.node}`, engines.node, options)) return `its engines.node, ${quote(String(engines.node))}, does not take Node ${host.node}`
36
+ if (engines.npm && !satisfies(host.npm, engines.npm, options)) return `its engines.npm, ${quote(String(engines.npm))}, does not take npm ${host.npm}`
37
+ return undefined
38
+ }
39
+
40
+ // Arborist's gatherDepSet.
41
+ function gatherDepSet(set, follow) {
42
+ const deps = new Set(set)
43
+ for (const node of deps) for (const edge of node.edgesOut) if (follow(edge)) deps.add(edge.to)
44
+ let changed = true
45
+ while (changed && deps.size > 0) {
46
+ changed = false
47
+ for (const dep of deps) {
48
+ if (dep.edgesIn.some((edge) => !deps.has(edge.from) && follow(edge))) {
49
+ changed = true
50
+ deps.delete(dep)
51
+ }
52
+ }
53
+ }
54
+ return deps
55
+ }
56
+
57
+ // Arborist's optionalSet: npm 10 gathers by edges that are not optional,
58
+ // npm 11 by those out of the first set, from 11.13 not from a node an
59
+ // earlier set left out.
60
+ function optionalSet(node, host, skipped) {
61
+ const set = new Set([node])
62
+ for (const member of set) for (const edge of member.edgesIn) if (!edge.optional) set.add(edge.from)
63
+ return gatherDepSet(set, host.reuse ? (edge) => !edge.optional : (edge) => !set.has(edge.to) && !(host.inert && skipped.has(edge.from)))
64
+ }
65
+
66
+ const whereOf = (node) => `packages[${quote(node.location)}]`
67
+
68
+ // npm 11 checks optional packages in inventory order, passing over one an
69
+ // earlier set took; npm 10 checks them all as it extracts. What is in the
70
+ // node_modules of a node left out goes with it.
71
+ export function skippedOf(nodes, host, settings) {
72
+ const skipped = new Set()
73
+ for (const node of nodes.values()) {
74
+ if (node.kind !== 'package') continue
75
+ const where = whereOf(node)
76
+ if (!node.pkg.optional) {
77
+ const platform = checkPlatform(node.manifest, host, where)
78
+ if (platform !== undefined) throw new DeptreeError(`${platform}, and it is not optional, which npm fails on`, where)
79
+ const engine = settings.engineStrict ? checkEngine(node.manifest, host) : undefined
80
+ if (engine !== undefined) throw new DeptreeError(`${engine}, and it is not optional, which npm fails on with engine-strict`, where)
81
+ continue
82
+ }
83
+ if (!host.reuse && skipped.has(node)) continue
84
+ if (checkEngine(node.manifest, host) === undefined && checkPlatform(node.manifest, host, where) === undefined) continue
85
+ for (const member of optionalSet(node, host, skipped)) skipped.add(member)
86
+ }
87
+ for (const node of skipped) {
88
+ if (node.kind !== 'package') throw new DeptreeError('left out with an optional package the host cannot run, which is not supported', node.kind === 'link' ? whereOf(node) : `importers[${quote(node.location)}]`)
89
+ }
90
+ const under = (node) => node.parent !== undefined && (skipped.has(nodes.get(node.parent)) || under(nodes.get(node.parent)))
91
+ return new Set([...nodes.values()].filter((node) => skipped.has(node) || under(node)))
92
+ }
@@ -0,0 +1,52 @@
1
+ // The root's devEngines, as npm-install-checks' checkDevEngines reads them
2
+ // before an install. The os version npm takes from the kernel is unknown.
3
+
4
+ import { satisfies, validRange } from '@preventive/upstream/semver.js'
5
+ import { DeptreeError, quote } from '../error.js'
6
+
7
+ const ENGINES = new Set(['packageManager', 'runtime', 'cpu', 'libc', 'os'])
8
+ const PROPERTIES = new Set(['name', 'version', 'onFail'])
9
+ const ON_FAIL = new Set(['ignore', 'warn', 'error', 'download'])
10
+
11
+ const isMapping = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
12
+
13
+ function matches(wanted, current, at) {
14
+ const fail = (detail) => {
15
+ throw new DeptreeError(`${detail}, which npm fails on`, at)
16
+ }
17
+ if (!isMapping(wanted)) fail('expected a mapping')
18
+ const unknown = Object.keys(wanted).find((key) => !PROPERTIES.has(key))
19
+ if (unknown !== undefined) fail(`${quote(unknown)} is not a field npm knows`)
20
+ if (typeof wanted.name !== 'string') fail('expected a name')
21
+ if (typeof current.name !== 'string') fail('the host has none')
22
+ if ('onFail' in wanted && !ON_FAIL.has(wanted.onFail)) fail(`expected onFail to be one of ${[...ON_FAIL].join(', ')}`)
23
+ if (wanted.name !== current.name) return false
24
+ if (!('version' in wanted)) return true
25
+ if (typeof wanted.version !== 'string') fail('expected a version')
26
+ if (current.version === undefined) {
27
+ if (at.endsWith('.os')) throw new DeptreeError('a version of the os, which npm takes from the kernel, is not known here', at)
28
+ fail('the host has no version of it')
29
+ }
30
+ return validRange(wanted.version) ? satisfies(current.version, wanted.version) : wanted.version === current.version
31
+ }
32
+
33
+ export function checkDevEngines(devEngines, host, at) {
34
+ if (devEngines === undefined) return
35
+ if (!isMapping(devEngines)) throw new DeptreeError('expected a mapping, which npm fails without', at)
36
+ const current = {
37
+ cpu: { name: host.cpu },
38
+ libc: { name: host.libc },
39
+ os: { name: host.os },
40
+ packageManager: { name: 'npm', version: host.npm },
41
+ runtime: { name: 'node', version: `v${host.node}` },
42
+ }
43
+ for (const [engine, wanted] of Object.entries(devEngines)) {
44
+ if (!ENGINES.has(engine)) throw new DeptreeError(`${quote(engine)} is not an engine npm knows, which it fails on`, at)
45
+ const dependencies = [wanted].flat()
46
+ const where = `${at}.${engine}`
47
+ const matched = dependencies.map((dependency) => matches(dependency, current[engine], where)).some(Boolean)
48
+ if (dependencies.length === 0 || matched) continue
49
+ const onFail = dependencies.at(-1).onFail || 'error'
50
+ if (onFail === 'error' || onFail === 'download') throw new DeptreeError(`the host's ${engine} is not one it takes, which npm fails on`, where)
51
+ }
52
+ }
@@ -0,0 +1,68 @@
1
+ // The lockfile's tree as Arborist holds it, for optionalSet to walk.
2
+
3
+ import { DeptreeError, quote } from '../error.js'
4
+
5
+ const IN_NODE_MODULES = /^(?:(.+)\/)?node_modules\/(?:@[^/]+\/)?[^/]+$/u
6
+
7
+ function parentOf(location, nodes) {
8
+ const found = IN_NODE_MODULES.exec(location)
9
+ if (found !== null) return found[1] ?? ''
10
+ const segments = location.split('/')
11
+ while (segments.pop() !== undefined) {
12
+ const dir = segments.join('/')
13
+ if (dir === '' || nodes.get(dir)?.kind === 'importer') return dir
14
+ }
15
+ return ''
16
+ }
17
+
18
+ // A node's children by their names, folded, as npm's CaseInsensitiveMap
19
+ // holds them and the lockfile reader resolves an edge.
20
+ const childKey = (parent, name) => `${parent}\n${name.toLowerCase()}`
21
+
22
+ function childrenOf(nodes) {
23
+ const children = new Map()
24
+ for (const { location } of nodes.values()) {
25
+ const found = IN_NODE_MODULES.exec(location)
26
+ if (found !== null) children.set(childKey(found[1] ?? '', location.slice(location.lastIndexOf('node_modules/') + 'node_modules/'.length)), nodes.get(location))
27
+ }
28
+ return children
29
+ }
30
+
31
+ // The link an edge to `target` is met by, the first of its name up the tree,
32
+ // held to lead where the lockfile reader found it to.
33
+ function linkOf(from, name, target, { nodes, children, links }) {
34
+ for (let location = from.location; location !== undefined; location = nodes.get(location).parent) {
35
+ const node = children.get(childKey(location, name))
36
+ if (node === undefined) continue
37
+ if (node.kind !== 'link' || `link:${links[node.location]}` !== target) break
38
+ return node
39
+ }
40
+ throw new DeptreeError(`its ${quote(name)} is not met by the link to ${quote(target.slice('link:'.length))} the lockfile reader found`, quote(from.location))
41
+ }
42
+
43
+ // Packages in lockfile order, which npm checks them in. npm reads the
44
+ // project's and workspaces' package.json in place of their entries.
45
+ export function graphOf(lockfile, manifests) {
46
+ const nodes = new Map()
47
+ const add = (location, kind, pkg) => nodes.set(location, { location, kind, pkg, parent: undefined, edgesOut: [], edgesIn: [] })
48
+ add('', 'root', lockfile.importers['.'])
49
+ for (const [dir, importer] of Object.entries(lockfile.importers)) if (dir !== '.') add(dir, 'importer', importer)
50
+ for (const [location, pkg] of Object.entries(lockfile.packages)) add(location, 'package', pkg)
51
+ for (const location of Object.keys(lockfile.links)) add(location, 'link', undefined)
52
+ for (const node of nodes.values()) {
53
+ if (node.kind !== 'root') node.parent = parentOf(node.location, nodes)
54
+ node.manifest = node.kind === 'link' ? undefined : manifests.get(node.location || '.') ?? node.pkg
55
+ }
56
+ const tree = { nodes, children: childrenOf(nodes), links: lockfile.links }
57
+ for (const node of nodes.values()) {
58
+ for (const [name, { type, target }] of Object.entries(node.pkg?.edges ?? {})) {
59
+ if (target === undefined) continue
60
+ const to = target.startsWith('link:') ? linkOf(node, name, target, tree) : nodes.get(target)
61
+ if (to === undefined) throw new DeptreeError(`its ${quote(name)} is met by ${quote(target)}, which the lockfile does not have`, quote(node.location))
62
+ const edge = { type, optional: type === 'optional' || type === 'peerOptional', from: node, to }
63
+ node.edgesOut.push(edge)
64
+ to.edgesIn.push(edge)
65
+ }
66
+ }
67
+ return nodes
68
+ }
@@ -0,0 +1,80 @@
1
+ // The host, and the files `npm ci` reads, given or read from the project.
2
+
3
+ import { valid } from '@preventive/upstream/semver.js'
4
+ import { DeptreeError, quote } from '../error.js'
5
+ import { walkWorkspaces } from '../glob.js'
6
+ import { readManifest, readManifests } from '../manifest.js'
7
+ import { checkProject, readText, typeOf } from '../project.js'
8
+ import { readSettings } from './settings.js'
9
+ import { profileOf } from './versions.js'
10
+
11
+ const LIBCS = new Set(['glibc', 'musl'])
12
+
13
+ export function checkHost(host) {
14
+ if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with npm, node, os and cpu, and libc on Linux')
15
+ for (const key of ['npm', 'node', 'os', 'cpu']) {
16
+ if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
17
+ }
18
+ if (valid(host.node) !== host.node) throw new DeptreeError(`${quote(host.node)} is not an exact version`, 'host.node')
19
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: npm links bins there with shims, and workspaces with junctions', 'host.os')
20
+ if (host.os === 'linux' ? !LIBCS.has(host.libc) : host.libc !== undefined) {
21
+ throw new TypeError(host.os === 'linux' ? 'host.libc must be glibc or musl on Linux' : 'host.libc must be left out but on Linux')
22
+ }
23
+ return { ...profileOf(host.npm), node: host.node, os: host.os, cpu: host.cpu, libc: host.libc }
24
+ }
25
+
26
+ // As @npmcli/map-workspaces reads them; the lockfile reader refuses one
27
+ // that negates.
28
+ function globsOf(root) {
29
+ const { workspaces = [] } = root
30
+ const globs = Array.isArray(workspaces?.packages) ? workspaces.packages : workspaces
31
+ if (!Array.isArray(globs) || globs.some((glob) => typeof glob !== 'string')) throw new DeptreeError('expected a sequence of globs, which npm fails without', 'manifests["."].workspaces')
32
+ return globs.map((glob) => glob.replace(/^\.?\/+/u, ''))
33
+ }
34
+
35
+ // As map-workspaces globs, ignoring node_modules, and on macOS case.
36
+ function findWorkspaces(project, globs, nocase) {
37
+ return walkWorkspaces(project, globs, { manager: 'npm', fold: nocase ? (path) => path.toLowerCase() : undefined, skip: (name) => name === 'node_modules' })
38
+ }
39
+
40
+ const where = (dir) => `manifests[${quote(dir)}]`
41
+
42
+ function readManifestAt(project, dir) {
43
+ const text = readText(project, dir === '.' ? '/package.json' : `/${dir}/package.json`, where(dir))
44
+ if (text === undefined) throw new DeptreeError('the project has no package.json at its root', where(dir))
45
+ return readManifest(text, where(dir))
46
+ }
47
+
48
+ export function findNpmWorkspaces(options) {
49
+ const { project, os } = options ?? {}
50
+ checkProject(project)
51
+ return ['.', ...findWorkspaces(project, globsOf(readManifestAt(project, '.')), os === 'darwin')]
52
+ }
53
+
54
+ const LOCKFILE = 'lockfile must be the text of package-lock.json, or left out with a project given to read it from'
55
+
56
+ function readProject(project, nocase) {
57
+ if (typeOf(project, '/npm-shrinkwrap.json', false) !== undefined) throw new DeptreeError('an npm-shrinkwrap.json, which npm reads in place of package-lock.json, is not supported', 'npm-shrinkwrap.json')
58
+ const lockfile = readText(project, '/package-lock.json')
59
+ if (lockfile === undefined) throw new DeptreeError('the project has no package-lock.json, which npm ci cannot do without')
60
+ const manifests = new Map([['.', readManifestAt(project, '.')]])
61
+ for (const dir of findWorkspaces(project, globsOf(manifests.get('.')), nocase)) manifests.set(dir, readManifestAt(project, dir))
62
+ return { lockfile, manifests, settings: readSettings(readText(project, '/.npmrc', '.npmrc')) }
63
+ }
64
+
65
+ export function inputsOf(options, nocase) {
66
+ const { lockfile, manifests, npmrc, project } = options
67
+ if (lockfile === undefined) {
68
+ if (project === undefined) throw new TypeError(LOCKFILE)
69
+ checkProject(project)
70
+ for (const [name, value] of Object.entries({ manifests, npmrc })) {
71
+ if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: both are read from project`)
72
+ }
73
+ return readProject(project, nocase)
74
+ }
75
+ if (project !== undefined) throw new TypeError('project must be left out where lockfile is given')
76
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
77
+ if (manifests === null || typeof manifests !== 'object') throw new TypeError('manifests must map each project\'s directory to its package.json')
78
+ if (npmrc !== undefined && typeof npmrc !== 'string') throw new TypeError('npmrc must be a string, or left out')
79
+ return { lockfile, manifests: readManifests(manifests), settings: readSettings(npmrc) }
80
+ }