@preventive/deptree 1.0.0-alpha.1 → 1.0.0-alpha.11

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 (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +325 -0
  8. package/npm.js +7 -0
  9. package/package.json +92 -11
  10. package/pnpm.d.ts +401 -81
  11. package/pnpm.js +4 -9
  12. package/soldeer.d.ts +235 -0
  13. package/soldeer.js +6 -0
  14. package/src/cargo/crate.js +183 -0
  15. package/src/cargo/inputs.js +81 -0
  16. package/src/cargo/members.js +90 -0
  17. package/src/cargo/registry.js +65 -0
  18. package/src/cargo/tree.js +125 -0
  19. package/src/cargo/workspace.js +177 -0
  20. package/src/concurrent.js +32 -0
  21. package/src/error.js +8 -10
  22. package/src/glob.js +55 -0
  23. package/src/hash.js +51 -16
  24. package/src/manifest.js +52 -0
  25. package/src/matcher.js +60 -10
  26. package/src/mount.js +124 -42
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +96 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +202 -322
  41. package/src/pnpm/checks.js +8 -35
  42. package/src/pnpm/commands.js +230 -0
  43. package/src/pnpm/filename.js +19 -16
  44. package/src/pnpm/frozen.js +29 -73
  45. package/src/pnpm/gitignore.js +138 -0
  46. package/src/pnpm/glob.js +65 -0
  47. package/src/pnpm/graph.js +26 -34
  48. package/src/pnpm/hoist.js +96 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +26 -31
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +123 -124
  53. package/src/pnpm/local.js +95 -40
  54. package/src/pnpm/minimatch.js +319 -0
  55. package/src/pnpm/nm-hoist-graph.js +299 -0
  56. package/src/pnpm/nm-hoist.js +149 -0
  57. package/src/pnpm/npm-packlist.js +217 -0
  58. package/src/pnpm/overrides.js +11 -51
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +176 -81
  61. package/src/pnpm/patches.js +18 -25
  62. package/src/pnpm/projects.js +132 -89
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +74 -95
  65. package/src/pnpm/tree.js +216 -237
  66. package/src/pnpm/uptodate.js +16 -28
  67. package/src/pnpm/workspace.js +152 -126
  68. package/src/project.js +56 -0
  69. package/src/soldeer/config.js +63 -0
  70. package/src/soldeer/git.js +52 -0
  71. package/src/soldeer/inputs.js +30 -0
  72. package/src/soldeer/tree.js +83 -0
  73. package/src/soldeer/zip.js +121 -0
  74. package/src/tarball.js +123 -131
  75. package/src/yarn1/bins.js +28 -0
  76. package/src/yarn1/compat.js +67 -0
  77. package/src/yarn1/hoist.js +249 -0
  78. package/src/yarn1/inputs.js +83 -0
  79. package/src/yarn1/manifest.js +64 -0
  80. package/src/yarn1/package.js +206 -0
  81. package/src/yarn1/peers.js +51 -0
  82. package/src/yarn1/requests.js +74 -0
  83. package/src/yarn1/resolve.js +289 -0
  84. package/src/yarn1/settings.js +95 -0
  85. package/src/yarn1/tree.js +219 -0
  86. package/yarn1.d.ts +368 -0
  87. package/yarn1.js +7 -0
  88. package/src/pnpm/npmrc.js +0 -31
  89. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -1,32 +1,21 @@
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.
1
+ // Refuses a lockfile a frozen install would refuse as out of date with the
2
+ // settings (@pnpm/lockfile.settings-checker's getOutdatedLockfileSetting),
3
+ // naming the setting as pnpm names it. pnpm 9 holds the lockfile to neither the
4
+ // catalogs nor dedupePeers.
16
5
 
17
6
  import { normalize } from '@preventive/vfs/path.js'
18
7
  import { DeptreeError, difference, quote } from '../error.js'
19
- import { sha256Hex } from '../hash.js'
8
+ import { md5Base32, sha256Hex } from '../hash.js'
20
9
  import { sameSpecifier } from './frozen.js'
10
+ import { catalogEntry } from './overrides.js'
21
11
  import { checkPatchUse, checkPeerPatches } from './patches.js'
22
12
 
23
13
  const outdated = (name, detail) => new DeptreeError(`${detail}, which a frozen install refuses`, name)
24
14
 
25
15
  const SIDES = ['the lockfile', 'the settings']
26
16
 
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) {
17
+ // `hashes` is { hash, path } by selector, `byHash` { text, path } by hash.
18
+ async function hashPatches(configured, given, major) {
30
19
  const texts = new Map()
31
20
  for (const [key, text] of given) {
32
21
  const path = normalize(key)
@@ -41,7 +30,9 @@ async function hashPatches(configured, given) {
41
30
  named.add(path)
42
31
  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
32
  const text = texts.get(path)
44
- const hash = await sha256Hex(text.replaceAll('\r\n', '\n'), `patches[${quote(path)}]`)
33
+ const normalized = text.replaceAll('\r\n', '\n')
34
+ const where = `patches[${quote(path)}]`
35
+ const hash = major < 10 ? md5Base32(normalized, where) : await sha256Hex(normalized, where)
45
36
  hashes[selector] = { hash, path }
46
37
  if (!byHash.has(hash)) byHash.set(hash, { text, path })
47
38
  }
@@ -58,14 +49,11 @@ function checkPatches(locked, hashes, major) {
58
49
  if (detail !== undefined) throw outdated('patchedDependencies', `the patches differ: ${detail}`)
59
50
  }
60
51
 
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
52
  export async function checkUpToDate(lockfile, settings, overrides, given, major) {
65
- const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given)
66
- for (const [name, catalog] of Object.entries(lockfile.catalogs)) {
53
+ const { hashes, byHash } = await hashPatches(settings.patchedDependencies, given, major)
54
+ for (const [name, catalog] of major < 10 ? [] : Object.entries(lockfile.catalogs)) {
67
55
  for (const [alias, { specifier }] of Object.entries(catalog)) {
68
- const configured = settings.catalogs[name]?.[alias]
56
+ const configured = catalogEntry(settings.catalogs, name, alias)
69
57
  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
58
  }
71
59
  }
@@ -79,9 +67,9 @@ export async function checkUpToDate(lockfile, settings, overrides, given, major)
79
67
  checkPatches(lockfile.patchedDependencies, hashes, major)
80
68
  const locked = lockfile.settings
81
69
  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`)
70
+ if (major >= 10 && Boolean(locked.dedupePeers) !== settings.dedupePeers) throw outdated('settings.dedupePeers', `dedupePeers is ${Boolean(locked.dedupePeers)} in the lockfile`)
83
71
  if ((locked.peersSuffixMaxLength ?? 1000) !== settings.peersSuffixMaxLength) throw outdated('settings.peersSuffixMaxLength', `peersSuffixMaxLength is ${locked.peersSuffixMaxLength ?? 'left at 1000'} in the lockfile`)
84
- checkPatchUse(lockfile, hashes)
72
+ checkPatchUse(lockfile, hashes, major)
85
73
  if (major >= 11) checkPeerPatches(lockfile, hashes)
86
74
  return byHash
87
75
  }
@@ -1,36 +1,25 @@
1
- // Which directories pnpm 10 takes for a workspace's projects, all of them
2
- // under one lockfile: the root, always, and each directory whose
3
- // package.json a glob of pnpm-workspace.yaml's `packages` takes, as
4
- // @pnpm/fs.find-packages globs for them with tinyglobby — `<glob>/
5
- // package.{json,yaml,json5}`, less anything under node_modules or
6
- // bower_components. Without `packages`, or without pnpm-workspace.yaml,
7
- // the root is the only project. pnpm finds them on disk: findProjects
8
- // finds them so in the directories it is given, and checkWorkspace holds
9
- // the lockfile's importers to them.
10
- //
11
- // A glob is read as tinyglobby reads it, normalized as a path first, as
12
- // far as `*` and `**` go: `*` any run of characters in one directory's
13
- // name, `**` a whole name for any number of directories, neither taking a
14
- // name that starts with a dot, which only a glob that spells it takes; `!`
15
- // in front leaves out what it takes, wherever it is in the list. Anything
16
- // else a glob can say — `?`, a class, a brace, an extglob, an escape — is
17
- // refused, and so is a glob reaching outside the workspace's directory.
18
- // pnpm 11 leaves out what a `!` glob takes with micromatch too, a name
19
- // starting with a dot and all.
20
-
21
- import { normalize } from '@preventive/vfs/path.js'
1
+ // The directories pnpm takes for a workspace's projects: the root, and each
2
+ // whose package.json a glob of pnpm-workspace.yaml's `packages` takes, as
3
+ // @pnpm/fs.find-packages globs for them with tinyglobby (pnpm 9: fast-glob), or
4
+ // as pnpm 12 walks (wax). pnpm 11 matches `!` globs with micromatch, dotted
5
+ // names and all.
6
+
7
+ import { compareNames, normalize } from '@preventive/vfs/path.js'
22
8
  import { DeptreeError, quote } from '../error.js'
23
- import { escape } from '../matcher.js'
9
+ import { reach, wildcard } from '../matcher.js'
10
+ import { UNSAFE, isInside } from '../mount.js'
11
+ import { typeOf } from '../project.js'
24
12
 
25
13
  const UNSUPPORTED = /[?[\]{}()\\]/u
26
14
 
27
- // A name's pattern: `*` any run of characters, line terminators among
28
- // them, but not a leading dot unless `dot`.
29
- const NAME = (name, dot) => new RegExp(`^${name.startsWith('*') && !dot ? '(?!\\.)' : ''}${name.split('*').map(escape).join('[^/]*')}$`, 'u')
15
+ // `*` takes line terminators too, and a leading dot only with `dot`.
16
+ function compileName(name, dot) {
17
+ const matches = wildcard(name)
18
+ const undotted = name.startsWith('*') && !dot
19
+ return { test: (entry) => !(undotted && entry.startsWith('.')) && matches(entry) }
20
+ }
30
21
 
31
- // A glob as the names of the paths it takes, normalized as tinyglobby
32
- // does: each `**`, or the pattern of one name; `dot` whether `**` takes a
33
- // name with a leading dot.
22
+ // A glob normalized as tinyglobby does, as `**` or a pattern per name.
34
23
  function compile(glob, where, dot) {
35
24
  const path = normalize(`./${glob}/package.json`)
36
25
  if (path.startsWith('../')) throw new DeptreeError(`${quote(glob)} reaches outside the workspace's directory, which is not supported`, where)
@@ -38,40 +27,12 @@ function compile(glob, where, dot) {
38
27
  if (glob === '' || glob.startsWith('/') || UNSUPPORTED.test(glob) || glob.includes('!') || names.some((name) => name !== '**' && name.includes('**'))) {
39
28
  throw new DeptreeError(`${quote(glob)} is not supported: only \`*\`, \`**\` as a whole name and a leading \`!\` are`, where)
40
29
  }
41
- return { names: names.map((name) => (name === '**' ? name : NAME(name, dot))), dot }
42
- }
43
-
44
- // Which places in a glob the path of `names` leads to: for each index,
45
- // whether the glob's names before it take the path, a name at a time, in
46
- // time the glob's length for each and with no recursion, however many
47
- // `**` it has. A `**` may take no name, so reaching one reaches the next.
48
- function reach({ names: glob, dot }, names) {
49
- let here = Array.from({ length: glob.length + 1 }, (_, g) => g === 0)
50
- let next = Array.from({ length: glob.length + 1 }, () => false)
51
- const onward = (places) => {
52
- for (let g = 0; g < glob.length; g++) if (places[g] && glob[g] === '**') places[g + 1] = true
53
- }
54
- onward(here)
55
- for (const name of names) {
56
- next.fill(false)
57
- for (let g = 0; g < glob.length; g++) {
58
- if (!here[g]) continue
59
- if (glob[g] !== '**') next[g + 1] ||= glob[g].test(name)
60
- else if (dot || !name.startsWith('.')) next[g] = true
61
- }
62
- onward(next)
63
- ;[here, next] = [next, here]
64
- }
65
- return here
30
+ return { names: names.map((name) => (name === '**' ? name : compileName(name, dot))), dot, raw: names }
66
31
  }
67
32
 
68
- // Whether a glob takes the path of `names`.
69
- const takes = (glob, names) => reach(glob, names)[glob.names.length]
33
+ const takes = (glob, names) => reach(glob.names, names, glob.dot).at(-1)
70
34
 
71
- // Whether tinyglobby walks into the directory at `names` for a glob, as
72
- // its partial matcher has it: name by name, each has to be taken by the
73
- // glob's name in the same place, until a `**` there takes one, which
74
- // takes whatever is below it. A `**` that takes none is not tried, so a
35
+ // tinyglobby's partial matcher: a `**` that takes no name is not tried, so a
75
36
  // name with a leading dot a `**` stands before is never walked into.
76
37
  function enters({ names: glob, dot }, names) {
77
38
  for (const [i, name] of names.entries()) {
@@ -82,91 +43,169 @@ function enters({ names: glob, dot }, names) {
82
43
  return true
83
44
  }
84
45
 
85
- // `packages`, the globs or undefined, as the globs that take and those
86
- // that leave out; `major` pnpm's major version.
46
+ // A manifest in a directory tinyglobby walks into is not ignored for what
47
+ // find-packages ignores; pnpm 12 drops it whatever the globs say. `wild` is
48
+ // whether a glob with a `*` takes it (manifestOf).
87
49
  function compileAll(packages, major) {
88
- const globs = { include: [], exclude: [] }
50
+ if (major < 10) return compile9(packages)
51
+ const twelve = major >= 12
52
+ const [enters_, ignored_, dropped] = twelve ? [enters12, underLeftOut, underLeftOut] : [enters, ignored, () => false]
53
+ const include = []
54
+ const exclude = []
89
55
  for (const glob of packages ?? []) {
90
- const exclude = glob.startsWith('!')
91
- globs[exclude ? 'exclude' : 'include'].push(compile(exclude ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', exclude && major >= 11))
56
+ const negative = glob.startsWith('!')
57
+ const compiled = compile(negative ? glob.slice(1) : glob, 'pnpm-workspace.yaml: packages', negative && major >= 11)
58
+ ;(negative ? exclude : include).push({ ...compiled, wild: twelve && glob.includes('*') })
59
+ }
60
+ return {
61
+ walked: (names) => include.some((glob) => enters_(glob, names)) && !ignored_(names),
62
+ taken: takenBy(include, exclude, dropped),
63
+ wild: (names) => include.some((glob) => glob.wild && takes(glob, names)),
64
+ manifests: MANIFESTS,
65
+ through: [],
92
66
  }
93
- return globs
94
67
  }
95
68
 
96
- // What find-packages leaves out, as tinyglobby reads it, which does not
97
- // take a name with a leading dot for `**`: what is under node_modules or
98
- // bower_components.
99
- const IGNORED = ['node_modules', 'bower_components'].map((name) => ({ names: ['**', NAME(name, false), '**'], dot: false }))
69
+ const takenBy = (include, exclude, dropped) => (names) => include.some((glob) => takes(glob, names)) && !exclude.some((glob) => takes(glob, names)) && !dropped(names)
70
+
71
+ const startsWith = (names, start) => start.length <= names.length && start.every((name, i) => names[i] === name)
72
+
73
+ // fast-glob's partial matcher: past the names before its first `**`, any.
74
+ function partial({ names: glob, raw }, names) {
75
+ const star = raw.indexOf('**')
76
+ if (star === -1 && glob.length <= names.length) return false
77
+ if (star !== -1 && names.length > star) return true
78
+ return names.every((name, i) => glob[i].test(name))
79
+ }
80
+
81
+ const isDynamic = (glob) => glob.raw.some((name) => name.includes('*'))
82
+
83
+ // pnpm 9 globs with fast-glob 3: a glob with no `*` it looks up where it
84
+ // leads, and one with a `*` it walks for from the names before that
85
+ // (`base`), from the top for all of them where one has none there. Under
86
+ // a base it walks into every directory its globs may reach (`partial`),
87
+ // those with a leading dot among them, but where the ignore globs take it
88
+ // with `**` taking no leading dot, or where a `!` glob takes it whole;
89
+ // and takes a manifest a glob takes and no `!` glob, nor an ignore glob,
90
+ // with `**` and `*` taking leading dots. It reads every manifest a
91
+ // directory has, so one but package.json is the one refused (MANIFESTS_9),
92
+ // and fails on a glob that leads through a file (`through`).
93
+ function compile9(packages) {
94
+ const where = 'pnpm-workspace.yaml: packages'
95
+ const include = []
96
+ const exclude = []
97
+ const excludeWhole = []
98
+ for (const glob of packages ?? []) {
99
+ if (glob.startsWith('!')) {
100
+ exclude.push(compile(glob.slice(1), where, true))
101
+ excludeWhole.push(compile(glob.slice(1), where, false))
102
+ } else include.push(compile(glob, where, false))
103
+ }
104
+ const dynamic = include.filter(isDynamic)
105
+ const baseOf = (glob) => glob.raw.slice(0, glob.raw.findIndex((name) => name.includes('*')))
106
+ const groups = Map.groupBy(dynamic, (glob) => baseOf(glob).join('/'))
107
+ const tasks = groups.has('') ? [{ base: [], globs: dynamic }] : [...groups.values()].map((globs) => ({ base: baseOf(globs[0]), globs }))
108
+ const skipped = (names) => ignored(names) || (MANIFESTS.includes(names.at(-1)) && excludeWhole.some((glob) => takes(glob, [...names.slice(0, -1), 'package.json'])))
109
+ // A task walks into a directory only where it walked into its parent; each
110
+ // answer is kept for the walk.
111
+ const reacher = ({ base, globs }) => {
112
+ const known = new Map()
113
+ const reaches = (names) => {
114
+ if (names.length <= base.length) return names.length === base.length && startsWith(names, base)
115
+ const key = names.join('/')
116
+ if (!known.has(key)) known.set(key, reaches(names.slice(0, -1)) && globs.some((glob) => partial(glob, names)) && !skipped(names))
117
+ return known.get(key)
118
+ }
119
+ return reaches
120
+ }
121
+ const reachers = tasks.map(reacher)
122
+ const through = [...tasks.map((task) => task.base), ...include.filter((glob) => !isDynamic(glob)).map((glob) => glob.raw.slice(0, -1))]
123
+ return {
124
+ walked: (names) => through.some((path) => startsWith(path, names)) || reachers.some((reaches) => reaches(names)),
125
+ taken: takenBy(include, exclude, underLeftOut),
126
+ wild: () => false,
127
+ manifests: MANIFESTS_9,
128
+ through,
129
+ }
130
+ }
131
+
132
+ // The first of `globs.manifests` that is a file; pnpm 12 reads the first there
133
+ // where a `wild` glob takes the directory, failing where it is not a file.
134
+ function manifestOf(project, globs, names, entries) {
135
+ for (const name of globs.manifests) {
136
+ if (!entries.includes(name)) continue
137
+ const type = typeOf(project, `/${[...names, name].join('/')}`)
138
+ if (type === 'file') return name
139
+ if (type !== undefined && globs.wild([...names, 'package.json'])) throw new DeptreeError(`pnpm 12 reads this as a manifest, and fails on it as a ${type}`, quote([...names, name].join('/')))
140
+ }
141
+ return undefined
142
+ }
143
+
144
+ // Two paths in the order of their names, as pnpm 12 has them.
145
+ function byNames(a, b) {
146
+ const x = a.split('/')
147
+ const y = b.split('/')
148
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return compareNames(x[i], y[i])
149
+ return x.length - y.length
150
+ }
151
+
152
+ // find-packages leaves out what is under these, by globs whose `**`, as
153
+ // tinyglobby reads them, takes no name with a leading dot; as fast-glob
154
+ // reads them for a manifest, any (underLeftOut).
155
+ const LEFT_OUT = ['node_modules', 'bower_components']
156
+ const IGNORED = LEFT_OUT.map((name) => ({ names: ['**', compileName(name, false), '**'], dot: false }))
100
157
  const ignored = (names) => IGNORED.some((glob) => takes(glob, names))
101
158
 
102
- // Whether the globs take the manifest at `names`. What find-packages
103
- // ignores it is not ignored for, in a directory tinyglobby walks into.
104
- const taken = ({ include, exclude }, names) => include.some((glob) => takes(glob, names)) && !exclude.some((glob) => takes(glob, names))
159
+ const underLeftOut = (names) => names.some((name) => LEFT_OUT.includes(name))
105
160
 
106
- // Whether tinyglobby walks into the directory at `names`, which it does
107
- // through a link to one too.
108
- const walked = ({ include }, names) => include.some((glob) => enters(glob, names)) && !ignored(names)
161
+ // pnpm 12 walks into a directory a glob's names before its last may take.
162
+ const enters12 = (glob, names) => reach(glob.names, names, glob.dot).slice(0, -1).some(Boolean)
109
163
 
110
- // `ids` are the projects' directories, `.` the root; `packages` the globs,
111
- // or undefined; `major` pnpm's major version. pnpm finds a project where
112
- // tinyglobby walks into each directory down to it, and the globs take its
113
- // manifest.
114
164
  export function checkWorkspace(ids, packages, major = 10) {
115
165
  const globs = compileAll(packages, major)
116
166
  for (const id of ids) {
117
167
  if (id === '.') continue
118
168
  const names = id.split('/')
119
- if (!names.every((_, i) => walked(globs, names.slice(0, i + 1))) || !taken(globs, [...names, 'package.json'])) {
169
+ if (!names.every((_, i) => globs.walked(names.slice(0, i + 1))) || !globs.taken([...names, 'package.json'])) {
120
170
  throw new DeptreeError(`pnpm-workspace.yaml's packages ${packages === undefined ? 'are not set' : 'do not take this directory'}, so pnpm would not install it as a project`, `importers[${quote(id)}]`)
121
171
  }
122
172
  }
123
173
  }
124
174
 
125
- // Of what @preventive/lockfile holds an importer's key to, what a project
126
- // under the lockfile's directory has to be: its path from there, in normal
127
- // form, with no drive letter, and no control, bidirectional or backslash
128
- // character, which the lockfile could not name it by.
129
- const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
175
+ // The importer keys @preventive/lockfile takes for a project.
130
176
  export function checkProjectId(id, where) {
131
- if (id.split('/').some((name) => name === '' || name === '.' || name === '..' || UNSAFE.test(name)) || /^[A-Za-z]:/u.test(id)) {
177
+ if (!isInside(id) || UNSAFE.test(id) || /^[A-Za-z]:/u.test(id)) {
132
178
  throw new DeptreeError('expected a directory under the lockfile\'s, by its path from there in normal form, as a lockfile can key an importer', where)
133
179
  }
134
180
  }
135
181
 
136
- // The names pnpm reads a project's manifest by, the first of them there
137
- // winning.
182
+ export const linkedManifest = (file) => new DeptreeError('a link pnpm would read a project\'s manifest through is not supported', quote(file))
183
+
184
+ // pnpm reads the first of these a project has; pnpm 9 each, so one but
185
+ // package.json is named first.
138
186
  const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
187
+ const MANIFESTS_9 = ['package.json5', 'package.yaml', 'package.json']
139
188
 
140
- // The directories of the projects pnpm `major` finds by the globs of
141
- // `packages` in the workspace at the root of `vfs`: `.`, the root, then
142
- // the rest in order. Every directory tinyglobby walks into is read, and no
143
- // other, a link to one followed as it follows it. A manifest is a file, or
144
- // a link to one; a link that leads nowhere, or to a directory, is none.
145
- // Refused, as not read here: a root with no manifest, which pnpm takes
146
- // for no project; a project, the root among them, whose manifest is
147
- // package.json5, package.yaml or a link; a project found
148
- // through a link, and a link to a directory in one followed, which is not
149
- // followed; a project in a directory a lockfile could not key its
150
- // importer by; and a node_modules tinyglobby walks into, which it does
151
- // only under a directory with a leading dot, as what is installed there
152
- // is no project buildPnpmTree builds.
153
- export function findProjects(vfs, packages, major = 10) {
189
+ // Every directory tinyglobby walks into is read, and no other. It walks into
190
+ // a node_modules only under a directory with a leading dot, which is
191
+ // refused, as what is installed there is no project buildPnpmTree builds.
192
+ export function findProjects(project, packages, major = 10) {
154
193
  const globs = compileAll(packages, major)
194
+ for (const path of globs.through) {
195
+ const end = path.findIndex((_, i) => typeOf(project, `/${path.slice(0, i + 1).join('/')}`) === 'file')
196
+ if (end !== -1) throw new DeptreeError('a glob leads through this file, which pnpm 9 fails on', quote(path.slice(0, end + 1).join('/')))
197
+ }
155
198
  const ids = []
156
- // The directories left to read, by their names, and the link each is
157
- // reached through, if any: a stack, not recursion, however deep the tree.
158
199
  const pending = [{ names: [] }]
159
200
  while (pending.length > 0) {
160
201
  const { names, link } = pending.pop()
161
202
  const dir = names.join('/')
162
- const entries = vfs.readdir(`/${dir}`)
163
- const found = names.length === 0 || taken(globs, [...names, 'package.json'])
164
- ? MANIFESTS.find((name) => entries.includes(name) && typeOf(vfs, `/${[...names, name].join('/')}`) === 'file')
165
- : undefined
203
+ const entries = project.readdir(`/${dir}`)
204
+ const found = names.length === 0 || globs.taken([...names, 'package.json']) ? manifestOf(project, globs, names, entries) : undefined
166
205
  if (names.length === 0 && found === undefined) throw new DeptreeError('pnpm takes a workspace with no manifest at its root for one with no root project, which is not supported', quote('package.json'))
167
206
  if (found !== undefined) {
168
207
  const file = [...names, found].join('/')
169
- if (vfs.lstat(`/${file}`).type === 'symlink') throw new DeptreeError('a link pnpm would read a project\'s manifest through is not supported', quote(file))
208
+ if (project.lstat(`/${file}`).type === 'symlink') throw linkedManifest(file)
170
209
  if (found !== 'package.json') throw new DeptreeError(`pnpm reads this project's ${found}, which is not supported`, quote(file))
171
210
  if (link !== undefined) throw new DeptreeError(`pnpm finds a project through this link, ${quote(dir)}, which is not supported`, quote(link))
172
211
  if (names.length > 0) {
@@ -176,10 +215,10 @@ export function findProjects(vfs, packages, major = 10) {
176
215
  }
177
216
  for (const entry of entries) {
178
217
  const at = [...names, entry]
179
- if (!walked(globs, at)) continue
218
+ if (!globs.walked(at)) continue
180
219
  const path = at.join('/')
181
- const { type } = vfs.lstat(`/${path}`)
182
- const linked = type === 'symlink' && typeOf(vfs, `/${path}`) === 'directory'
220
+ const { type } = project.lstat(`/${path}`)
221
+ const linked = type === 'symlink' && typeOf(project, `/${path}`) === 'directory'
183
222
  if (type !== 'directory' && !linked) continue
184
223
  if (entry === 'node_modules') throw new DeptreeError('pnpm-workspace.yaml\'s packages walk into this node_modules, which is not supported', quote(path))
185
224
  if (!linked) pending.push({ names: at, link })
@@ -187,18 +226,5 @@ export function findProjects(vfs, packages, major = 10) {
187
226
  else throw new DeptreeError(`a link to a directory in one tinyglobby follows, ${quote(path)}, is not supported`, quote(link))
188
227
  }
189
228
  }
190
- return ['.', ...ids.sort()]
191
- }
192
-
193
- // What `path` leads to, links followed; nothing, where it leads nowhere:
194
- // to no entry, through a file, or round a loop of links. Any other
195
- // failure is thrown.
196
- const NOWHERE = new Set(['ENOENT', 'ENOTDIR', 'ELOOP'])
197
- function typeOf(vfs, path) {
198
- try {
199
- return vfs.stat(path).type
200
- } catch (error) {
201
- if (NOWHERE.has(error?.code)) return undefined
202
- throw error
203
- }
229
+ return ['.', ...major >= 12 ? ids.sort(byNames) : ids.sort()]
204
230
  }
package/src/project.js ADDED
@@ -0,0 +1,56 @@
1
+ // The project, the lockfile's directory, as a Vfs or anything with its
2
+ // methods, by paths from `/`; it is only read, and only where a builder says.
3
+
4
+ import { utf8toString } from '@exodus/bytes/utf8.js'
5
+ import { DeptreeError, quote } from './error.js'
6
+
7
+ export function checkProject(project) {
8
+ if (['readdir', 'lstat', 'stat', 'readFile'].some((name) => typeof project?.[name] !== 'function')) {
9
+ throw new TypeError('project must be a Vfs, or have its readdir, lstat, stat and readFile')
10
+ }
11
+ }
12
+
13
+ const NOWHERE = new Set(['ENOENT', 'ENOTDIR', 'ELOOP'])
14
+ export function typeOf(project, path, follow = true) {
15
+ try {
16
+ return (follow ? project.stat(path) : project.lstat(path)).type
17
+ } catch (error) {
18
+ if (NOWHERE.has(error?.code)) return undefined
19
+ throw error
20
+ }
21
+ }
22
+
23
+ // `bytes` as text, refused with `detail` where they are not UTF-8. A BOM is
24
+ // kept, as in text handed in, for the reader to drop as pnpm does.
25
+ export function decodeUtf8(bytes, detail, where) {
26
+ try {
27
+ return utf8toString(bytes)
28
+ } catch {
29
+ throw new DeptreeError(detail, where)
30
+ }
31
+ }
32
+
33
+ export function readBytes(project, path) {
34
+ const bytes = project.readFile(path)
35
+ if (!(bytes instanceof Uint8Array)) throw new TypeError('project.readFile must give back bytes')
36
+ return bytes
37
+ }
38
+
39
+ export function readText(project, path, where) {
40
+ const type = typeOf(project, path)
41
+ if (type === undefined) return undefined
42
+ if (type !== 'file') throw new DeptreeError(`${quote(path.slice(1))} is a ${type}, not a file`, where)
43
+ return decodeUtf8(readBytes(project, path), `${quote(path.slice(1))} is not UTF-8`, where)
44
+ }
45
+
46
+ // The checks each manager's checkHost and inputsOf make alike.
47
+ export function checkHostKeys(host, keys, wanted) {
48
+ if (host === null || typeof host !== 'object') throw new TypeError(`host must be an object with ${wanted}`)
49
+ for (const key of keys) if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
50
+ }
51
+ export function checkLeftOut(values, all = 'both') {
52
+ for (const [name, value] of Object.entries(values)) if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: ${all} are read from project`)
53
+ }
54
+ export function checkTexts(values) {
55
+ for (const [name, value] of Object.entries(values)) if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
56
+ }
@@ -0,0 +1,63 @@
1
+ // The config Soldeer 0.12 reads: foundry.toml where it has a [dependencies]
2
+ // table, else soldeer.toml where there is no foundry.toml.
3
+
4
+ import { TomlError, isInlineTable, parseToml } from '@preventive/lockfile/toml.js'
5
+ import { DeptreeError } from '../error.js'
6
+
7
+ const isTable = (value) => typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === null
8
+ // A table toml_edit gives as one, from a header or a dotted key, not inline:
9
+ // Soldeer reads no dependencies from that, and fails on it for a profile.
10
+ const isTableItem = (value) => isTable(value) && !isInlineTable(value)
11
+
12
+ function parse(text, file) {
13
+ try {
14
+ return parseToml(text)
15
+ } catch (error) {
16
+ if (error instanceof TomlError) throw new DeptreeError(`not TOML read here: ${error.message}`, file, { cause: error })
17
+ throw error
18
+ }
19
+ }
20
+
21
+ // update_config_libs, which expects each of these to be what it adds where
22
+ // it is not there, and panics on another.
23
+ function checkLibs(doc) {
24
+ const { profile } = doc
25
+ if (profile === undefined) return
26
+ if (!isTableItem(profile)) throw new DeptreeError('not a table, which Soldeer fails on', 'foundry.toml: profile')
27
+ const defaults = profile.default
28
+ if (defaults === undefined) return
29
+ if (!isTableItem(defaults)) throw new DeptreeError('not a table, which Soldeer fails on', 'foundry.toml: profile.default')
30
+ const { libs } = defaults
31
+ if (libs !== undefined && (!Array.isArray(libs) || isTableItem(libs[0]))) throw new DeptreeError('not an array, which Soldeer fails on', 'foundry.toml: profile.default.libs')
32
+ }
33
+
34
+ const BOOLEANS = ['remappings_generate', 'remappings_regenerate', 'remappings_version', 'recursive_deps']
35
+
36
+ // read_soldeer_config's SoldeerConfig, by serde; unknown fields passed over.
37
+ function checkSettings(settings, file) {
38
+ if (settings === undefined) return
39
+ const where = `${file}: soldeer`
40
+ if (!isTable(settings)) throw new DeptreeError('not a table, which Soldeer fails on', where)
41
+ for (const key of BOOLEANS) {
42
+ if (settings[key] !== undefined && typeof settings[key] !== 'boolean') throw new DeptreeError('not true or false, which Soldeer fails on', `${where}.${key}`)
43
+ }
44
+ if (settings.remappings_prefix !== undefined && typeof settings.remappings_prefix !== 'string') throw new DeptreeError('not a string, which Soldeer fails on', `${where}.remappings_prefix`)
45
+ if (![undefined, 'txt', 'config'].includes(settings.remappings_location)) throw new DeptreeError('not "txt" or "config", which Soldeer fails on', `${where}.remappings_location`)
46
+ if (settings.recursive_deps === true) throw new DeptreeError('has Soldeer install what each dependency depends on too, which is not supported', `${where}.recursive_deps`)
47
+ }
48
+
49
+ const ASKS = 'Soldeer asks which file to make its config, which is not supported'
50
+
51
+ export function configOf({ foundry, soldeer }) {
52
+ if (foundry === undefined && soldeer === undefined) throw new DeptreeError(`neither foundry.toml nor soldeer.toml is there, so ${ASKS}`)
53
+ const file = foundry === undefined ? 'soldeer.toml' : 'foundry.toml'
54
+ const config = parse(foundry ?? soldeer, file)
55
+ if (foundry === undefined) {
56
+ if (config.dependencies !== undefined && !isTableItem(config.dependencies)) throw new DeptreeError('not a table, which Soldeer reads no dependencies from, is not supported', 'soldeer.toml: dependencies')
57
+ } else {
58
+ if (!isTableItem(config.dependencies)) throw new DeptreeError(`no [dependencies] table, so ${ASKS}`, file)
59
+ checkLibs(config)
60
+ }
61
+ checkSettings(config.soldeer, file)
62
+ return config
63
+ }
@@ -0,0 +1,52 @@
1
+ // A git dependency as Soldeer 0.12 installs it, `git clone` and then `git
2
+ // checkout` of the lockfile's rev, from GitHub's tarball of that commit's
3
+ // tree instead: the files a checkout writes, without the .git it clones.
4
+
5
+ import { decompress } from '@preventive/archive/compression.js'
6
+ import { ArchiveError, unpack } from '@preventive/archive/tar.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { MAX_BYTES } from '../tarball.js'
9
+ import { isGit } from './zip.js'
10
+
11
+ // A GitHub repository as git takes its URL over the protocols Soldeer has
12
+ // it allow, https and ssh, `.git` after it or not, the scheme and host in
13
+ // any case: https://github.com/<repo>, ssh://git@github.com/<repo> and
14
+ // git@github.com:<repo>. The owner and name are as GitHub takes them.
15
+ const REPO = String.raw`(?<repo>(?=[\dA-Za-z-]{1,39}\/)[\dA-Za-z](?:-?[\dA-Za-z])*\/[\w.-]{1,100}?)(?:\.git)?`
16
+ const URL_FORM = new RegExp(String.raw`^(?:(?i:https):\/\/|(?i:ssh):\/\/git@)(?i:github\.com)\/${REPO}\/?$`, 'u')
17
+ const SCP_FORM = new RegExp(String.raw`^git@(?i:github\.com):${REPO}$`, 'u')
18
+
19
+ export function githubRepoOf(url) {
20
+ const repo = (URL_FORM.exec(url) ?? SCP_FORM.exec(url))?.groups.repo
21
+ return repo === undefined || /\/\.\.?$/u.test(repo) ? undefined : repo
22
+ }
23
+
24
+ // GitHub's tarball, which upstream holds to the tree GitHub names for the
25
+ // commit, files, symlinks and the submodules it shows as empty directories
26
+ // alike. Unpacked as a checkout with umask 0o022 writes it: directories
27
+ // 0o755, files 0o644 or 0o755 by the bit git keeps, symlinks as symlinks.
28
+ export async function checkoutOf(github, repo, rev, where) {
29
+ const bytes = await github.getRepoTarball({ repo, sha: rev })
30
+ let entries
31
+ try {
32
+ entries = unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES }))
33
+ } catch (error) {
34
+ if (error instanceof ArchiveError) throw new DeptreeError(`its tarball from GitHub cannot be read: ${error.message}`, where, { cause: error })
35
+ throw error
36
+ }
37
+ const top = entries[0]?.name.split('/')[0]
38
+ const dirs = new Set()
39
+ const files = new Map()
40
+ const links = new Map()
41
+ for (const entry of entries) {
42
+ if (entry.name === top) continue
43
+ if (!entry.name.startsWith(`${top}/`)) throw new Error('unreachable: an entry outside the one top directory upstream holds the tarball to')
44
+ const path = entry.name.slice(top.length + 1)
45
+ if (path.split('/').some(isGit)) throw new DeptreeError('a path with a .git in it, which git refuses to check out', `${where}: ${quote(path)}`)
46
+ if (entry.type === 'directory') dirs.add(path)
47
+ else if (entry.type === 'symlink') links.set(path, entry.linkname)
48
+ else if (entry.type === 'file') files.set(path, { data: entry.data, mode: entry.mode & 0o100 ? 0o755 : 0o644 })
49
+ else throw new Error(`unreachable: a ${entry.type} in a tarball of a git tree`)
50
+ }
51
+ return { dirs, files, links }
52
+ }
@@ -0,0 +1,30 @@
1
+ // What buildSoldeerTree takes, as text or read from the project's root.
2
+
3
+ import { DeptreeError, quote } from '../error.js'
4
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText } from '../project.js'
5
+
6
+ export function checkHost(host) {
7
+ checkHostKeys(host, ['soldeer', 'os'], 'soldeer and os')
8
+ if (host.soldeer !== '0.12.0') throw new DeptreeError(`Soldeer ${quote(host.soldeer)} is not supported: only Soldeer 0.12.0 is`, 'host.soldeer')
9
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: Soldeer names folders otherwise there', 'host.os')
10
+ return { soldeer: host.soldeer, os: host.os }
11
+ }
12
+
13
+ const LOCKFILE = 'lockfile must be the soldeer.lock text, or left out where project is given'
14
+
15
+ export function inputsOf(options) {
16
+ const { lockfile, foundry, soldeer, project } = options
17
+ if (lockfile === undefined) {
18
+ if (project === undefined) throw new TypeError(LOCKFILE)
19
+ checkProject(project)
20
+ checkLeftOut({ foundry, soldeer }, 'all')
21
+ const lock = readText(project, '/soldeer.lock', 'soldeer.lock')
22
+ if (lock === undefined) throw new DeptreeError('the project has no soldeer.lock, without which Soldeer resolves each dependency anew')
23
+ const foundryText = readText(project, '/foundry.toml', 'foundry.toml')
24
+ return { lockfile: lock, foundry: foundryText, soldeer: foundryText === undefined ? readText(project, '/soldeer.toml', 'soldeer.toml') : undefined }
25
+ }
26
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
27
+ if (project !== undefined) throw new TypeError('project must be left out where lockfile is given')
28
+ checkTexts({ foundry, soldeer })
29
+ return { lockfile, foundry, soldeer }
30
+ }