@preventive/deptree 1.0.0-alpha.0 → 1.0.0-alpha.10

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 +321 -0
  8. package/npm.js +7 -0
  9. package/package.json +93 -11
  10. package/pnpm.d.ts +422 -60
  11. package/pnpm.js +3 -8
  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 +128 -39
  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 +57 -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 +207 -327
  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 +47 -81
  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 +97 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +37 -51
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +140 -130
  53. package/src/pnpm/local.js +105 -34
  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 +20 -53
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +194 -0
  61. package/src/pnpm/patches.js +21 -28
  62. package/src/pnpm/projects.js +150 -101
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +85 -93
  65. package/src/pnpm/tree.js +234 -188
  66. package/src/pnpm/uptodate.js +17 -29
  67. package/src/pnpm/workspace.js +210 -53
  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 -125
  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,73 +1,230 @@
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`, less anything under node_modules or bower_components.
6
- // Without `packages`, or without pnpm-workspace.yaml, the root is the only
7
- // project. pnpm finds them on disk; here they are what is given, and each
8
- // has to be one pnpm would find. Those it would find and are not given
9
- // cannot be seen here, and have to be given: pnpm refuses a frozen install
10
- // for one the lockfile has no importer for, and installs every one.
11
- //
12
- // A glob is read as tinyglobby reads it, normalized as a path first, as
13
- // far as `*` and `**` go: `*` any run of characters in one directory's
14
- // name, `**` a whole name for any number of directories, neither taking a
15
- // name that starts with a dot, which only a glob that spells it takes; `!`
16
- // in front leaves out what it takes, wherever it is in the list. Anything
17
- // else a glob can say — `?`, a class, a brace, an extglob, an escape — is
18
- // refused, and so is a glob reaching outside the workspace's directory.
19
- // pnpm 11 leaves out what a `!` glob takes with micromatch too, a name
20
- // starting with a dot and all.
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.
21
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
- // tinyglobby's path.posix.normalize of a glob: empty and `.` names
28
- // dropped, and `..` taking the name before it with it.
29
- function normalizeGlob(glob, where) {
30
- const names = []
31
- for (const name of glob.split('/')) {
32
- if (name === '' || name === '.') continue
33
- if (name !== '..') names.push(name)
34
- else if (names.length === 0) throw new DeptreeError(`${quote(glob)} reaches outside the workspace's directory, which is not supported`, where)
35
- else names.pop()
36
- }
37
- return names
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) }
38
20
  }
39
21
 
40
- // A name's pattern: `*` any run of characters, but not a leading dot
41
- // unless `dot`.
42
- const NAME = (name, dot) => `${name.startsWith('*') && !dot ? '(?!\\.)' : ''}${name.split('*').map(escape).join('[^/]*')}`
43
- // `**`: any number of names, none with a leading dot unless `dot`, each
44
- // with its `/`.
45
- const GLOBSTAR = (dot) => `(?:${dot ? '' : '(?!\\.)'}[^/]+/)*`
46
-
22
+ // A glob normalized as tinyglobby does, as `**` or a pattern per name.
47
23
  function compile(glob, where, dot) {
48
- const names = normalizeGlob(`${glob}/package.json`, where)
24
+ const path = normalize(`./${glob}/package.json`)
25
+ if (path.startsWith('../')) throw new DeptreeError(`${quote(glob)} reaches outside the workspace's directory, which is not supported`, where)
26
+ const names = path.split('/')
49
27
  if (glob === '' || glob.startsWith('/') || UNSUPPORTED.test(glob) || glob.includes('!') || names.some((name) => name !== '**' && name.includes('**'))) {
50
28
  throw new DeptreeError(`${quote(glob)} is not supported: only \`*\`, \`**\` as a whole name and a leading \`!\` are`, where)
51
29
  }
52
- // The last name is package.json, which a `/` never follows.
53
- const source = names.map((name, index) => (name === '**' ? GLOBSTAR(dot) : `${NAME(name, dot)}${index === names.length - 1 ? '' : '/'}`)).join('')
54
- return new RegExp(`^${source}$`, 'u')
30
+ return { names: names.map((name) => (name === '**' ? name : compileName(name, dot))), dot, raw: names }
55
31
  }
56
32
 
57
- // `ids` are the projects' directories, `.` the root; `packages` the globs,
58
- // or undefined; `major` pnpm's major version.
59
- export function checkWorkspace(ids, packages, major = 10) {
33
+ const takes = (glob, names) => reach(glob.names, names, glob.dot).at(-1)
34
+
35
+ // tinyglobby's partial matcher: a `**` that takes no name is not tried, so a
36
+ // name with a leading dot a `**` stands before is never walked into.
37
+ function enters({ names: glob, dot }, names) {
38
+ for (const [i, name] of names.entries()) {
39
+ if (i === glob.length) return false
40
+ if (glob[i] === '**') return dot || !name.startsWith('.')
41
+ if (!glob[i].test(name)) return false
42
+ }
43
+ return true
44
+ }
45
+
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).
49
+ function compileAll(packages, major) {
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 = []
55
+ for (const glob of packages ?? []) {
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: [],
66
+ }
67
+ }
68
+
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) {
60
94
  const where = 'pnpm-workspace.yaml: packages'
61
- const globs = (packages ?? []).map((glob) => {
62
- const exclude = glob.startsWith('!')
63
- return { exclude, regexp: compile(exclude ? glob.slice(1) : glob, where, exclude && major >= 11) }
64
- })
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 }))
157
+ const ignored = (names) => IGNORED.some((glob) => takes(glob, names))
158
+
159
+ const underLeftOut = (names) => names.some((name) => LEFT_OUT.includes(name))
160
+
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)
163
+
164
+ export function checkWorkspace(ids, packages, major = 10) {
165
+ const globs = compileAll(packages, major)
65
166
  for (const id of ids) {
66
167
  if (id === '.') continue
67
- const path = `${id}/package.json`
68
- const taken = globs.some(({ exclude, regexp }) => !exclude && regexp.test(path)) && !globs.some(({ exclude, regexp }) => exclude && regexp.test(path))
69
- if (!taken || id.split('/').includes('bower_components')) {
168
+ const names = id.split('/')
169
+ if (!names.every((_, i) => globs.walked(names.slice(0, i + 1))) || !globs.taken([...names, 'package.json'])) {
70
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)}]`)
71
171
  }
72
172
  }
73
173
  }
174
+
175
+ // The importer keys @preventive/lockfile takes for a project.
176
+ export function checkProjectId(id, where) {
177
+ if (!isInside(id) || UNSAFE.test(id) || /^[A-Za-z]:/u.test(id)) {
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)
179
+ }
180
+ }
181
+
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.
186
+ const MANIFESTS = ['package.json', 'package.json5', 'package.yaml']
187
+ const MANIFESTS_9 = ['package.json5', 'package.yaml', 'package.json']
188
+
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) {
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
+ }
198
+ const ids = []
199
+ const pending = [{ names: [] }]
200
+ while (pending.length > 0) {
201
+ const { names, link } = pending.pop()
202
+ const dir = names.join('/')
203
+ const entries = project.readdir(`/${dir}`)
204
+ const found = names.length === 0 || globs.taken([...names, 'package.json']) ? manifestOf(project, globs, names, entries) : undefined
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'))
206
+ if (found !== undefined) {
207
+ const file = [...names, found].join('/')
208
+ if (project.lstat(`/${file}`).type === 'symlink') throw linkedManifest(file)
209
+ if (found !== 'package.json') throw new DeptreeError(`pnpm reads this project's ${found}, which is not supported`, quote(file))
210
+ if (link !== undefined) throw new DeptreeError(`pnpm finds a project through this link, ${quote(dir)}, which is not supported`, quote(link))
211
+ if (names.length > 0) {
212
+ checkProjectId(dir, quote(dir))
213
+ ids.push(dir)
214
+ }
215
+ }
216
+ for (const entry of entries) {
217
+ const at = [...names, entry]
218
+ if (!globs.walked(at)) continue
219
+ const path = at.join('/')
220
+ const { type } = project.lstat(`/${path}`)
221
+ const linked = type === 'symlink' && typeOf(project, `/${path}`) === 'directory'
222
+ if (type !== 'directory' && !linked) continue
223
+ if (entry === 'node_modules') throw new DeptreeError('pnpm-workspace.yaml\'s packages walk into this node_modules, which is not supported', quote(path))
224
+ if (!linked) pending.push({ names: at, link })
225
+ else if (link === undefined) pending.push({ names: at, link: path })
226
+ else throw new DeptreeError(`a link to a directory in one tinyglobby follows, ${quote(path)}, is not supported`, quote(link))
227
+ }
228
+ }
229
+ return ['.', ...major >= 12 ? ids.sort(byNames) : ids.sort()]
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
+ }
@@ -0,0 +1,83 @@
1
+ // The dependencies folder `soldeer install` makes from a soldeer.lock.
2
+
3
+ import { utf8fromStringLoose } from '@exodus/bytes/utf8.js'
4
+ import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
5
+ import { getZip } from '@preventive/upstream/soldeer.js'
6
+ import { Vfs } from '@preventive/vfs'
7
+ import { eachConcurrently } from '../concurrent.js'
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { checkNoDir, fold, makeDirs, mount, writeFiles } from '../mount.js'
10
+ import { configOf } from './config.js'
11
+ import { checkoutOf, githubRepoOf } from './git.js'
12
+ import { checkHost, inputsOf } from './inputs.js'
13
+ import { extractZip } from './zip.js'
14
+
15
+ // What the registry takes, as @preventive/upstream/soldeer.js checks a name
16
+ // and version, which Soldeer's sanitize_filename leaves as they are on Unix.
17
+ const NAME = /^(?=.{3,100}$)[@\da-z][\da-z-]*[\da-z]$/u
18
+ const VERSION = /^(?=.{1,128}$)[\dA-Za-z][\w.+-]*$/u
19
+ // A folder sanitize_filename leaves as it is on Unix: none of the characters
20
+ // it replaces, and at most 255 bytes, past which it cuts the name short.
21
+ const isKept = (folder) => !/[/?<>\\:*|"\p{Cc}]/u.test(folder) && utf8fromStringLoose(folder).length <= 255
22
+
23
+ const GITHUB = 'github must be a GitHub client from createClient, which a git dependency is fetched through'
24
+
25
+ const checkNoDependencies = checkNoDir('dependencies', 'a dependencies folder')
26
+
27
+ const about = (name) => `dependencies[${quote(name)}]`
28
+
29
+ function checkDependency({ type, name, version, git, folder }, config) {
30
+ const where = about(name)
31
+ if (type === 'private') throw new DeptreeError('a private dependency, which the registry hands out to those signed in alone, is not supported', where)
32
+ if (type === 'git') {
33
+ if (githubRepoOf(git) === undefined) throw new DeptreeError(`a git dependency from ${quote(git)}, not a GitHub repository over https or ssh, is not supported`, where)
34
+ if (!isKept(folder)) throw new DeptreeError(`its folder, ${quote(folder)}, is one Soldeer names otherwise, which is not supported`, where)
35
+ return
36
+ }
37
+ if (config.dependencies?.[name]?.url !== undefined) throw new DeptreeError('a dependency from a URL of its own, rather than the registry, is not supported', where)
38
+ if (!NAME.test(name)) throw new DeptreeError('a name the registry does not take', where)
39
+ if (!VERSION.test(version)) throw new DeptreeError(`${quote(version)} is a version the registry does not take`, where)
40
+ }
41
+
42
+ function dependenciesOf(lock, config, folded) {
43
+ const dependencies = Object.values(lock.dependencies).map((dependency) => ({ ...dependency, folder: `${dependency.name}-${dependency.version}` }))
44
+ for (const dependency of dependencies) checkDependency(dependency, config)
45
+ const key = (folder) => (folded ? fold(folder) : folder)
46
+ const folders = new Set(dependencies.map(({ folder }) => key(folder)))
47
+ for (const { type, name, folder } of dependencies) {
48
+ if (type === 'http' && folders.has(key(`${folder}.zip`))) throw new DeptreeError(`its zip is downloaded as ${quote(`${folder}.zip`)}, a folder Soldeer installs another dependency in`, about(name))
49
+ }
50
+ return dependencies
51
+ }
52
+
53
+ async function fetchAll(dependencies, github) {
54
+ const extracted = new Map()
55
+ await eachConcurrently(dependencies, async ({ type, name, version, checksum, git, rev, folder }) => {
56
+ const where = about(name)
57
+ extracted.set(folder, type === 'git' ? await checkoutOf(github, githubRepoOf(git), rev, where) : await extractZip(await getZip(name, version, checksum), checksum, where))
58
+ }, ({ name }) => about(name))
59
+ return extracted
60
+ }
61
+
62
+ export async function buildSoldeerTree(options) {
63
+ const { host: given, vfs: into, github } = options ?? {}
64
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
65
+ if (github !== undefined && typeof github?.getRepoTarball !== 'function') throw new TypeError(GITHUB)
66
+ const inputs = inputsOf(options ?? {})
67
+ const folded = checkHost(given).os === 'darwin'
68
+ // Refused before anything is fetched; mount checks again.
69
+ if (into !== undefined) checkNoDependencies(into, folded)
70
+ const config = configOf(inputs)
71
+ const dependencies = dependenciesOf(parseSoldeerLockfile(inputs.lockfile, { config }), config, folded)
72
+ if (github === undefined && dependencies.some(({ type }) => type === 'git')) throw new TypeError(GITHUB)
73
+ const extracted = await fetchAll(dependencies, github)
74
+ const vfs = new Vfs()
75
+ makeDirs(vfs, 'dependencies')
76
+ const stats = { dependencies: dependencies.length, files: 0, bytes: 0, links: 0 }
77
+ // In the lockfile's order, whatever order the fetches finished in.
78
+ for (const { folder } of dependencies) {
79
+ writeFiles(vfs, `dependencies/${folder}`, extracted.get(folder), stats)
80
+ }
81
+ const installed = dependencies.map(({ type, name, version, checksum, git, rev, folder }) => ({ path: `dependencies/${folder}`, name, version, ...(type === 'git' ? { git, rev, commit: rev } : { checksum }) }))
82
+ return { vfs: mount(vfs, into, folded, checkNoDependencies), stats, installed }
83
+ }