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

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.
@@ -0,0 +1,264 @@
1
+ // yarn 1's PackageHoister (package-hoister.js), as it lays out a
2
+ // node_modules tree: each package seeded beneath what asked for it, a
3
+ // level at a time, and hoisted as high as nothing of its name in the way,
4
+ // and no name reserved by another, lets it go. A prepass first seeds at
5
+ // the top the version of a package that the most others depend on, where
6
+ // several versions are asked for. The order is yarn's, quirks and all:
7
+ // a level's requests sorted by pattern, then those with peers, which a
8
+ // check meant to put them after their peers always puts last.
9
+ //
10
+ // Ported as it is, but for what is refused before it runs: nohoist,
11
+ // --focus and --flat; and the record yarn keeps of each step. Where yarn
12
+ // compares where its cache keeps two packages, this compares their
13
+ // references' `loc`; where it compares two manifests, the references.
14
+
15
+ // yarn's sortAlpha: by UTF-16 code units, then by length.
16
+ function sortAlpha(a, b) {
17
+ const length = Math.min(a.length, b.length)
18
+ for (let i = 0; i < length; i++) {
19
+ if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
20
+ }
21
+ return a.length - b.length
22
+ }
23
+
24
+ const implode = (parts) => parts.join('#')
25
+
26
+ // `patterns` resolve.js's, each pattern to its reference; `peersOf` a
27
+ // reference's peers' names, from its package.json.
28
+ export class Hoister {
29
+ constructor(patterns, peersOf) {
30
+ this.patterns = patterns
31
+ this.peersOf = peersOf
32
+ this.tainted = new Map()
33
+ this.levelQueue = []
34
+ this.tree = new Map()
35
+ }
36
+
37
+ resolved(pattern) {
38
+ const ref = this.patterns.get(pattern)
39
+ if (ref === undefined) throw new Error(`no package for ${pattern}`)
40
+ return ref
41
+ }
42
+
43
+ // A key reserved for a package, unless it is for another already.
44
+ taintKey(key, info) {
45
+ const existing = this.tainted.get(key)
46
+ if (!existing || existing.ref.loc === info.ref.loc) this.tainted.set(key, info)
47
+ }
48
+
49
+ // resolver.dedupePatterns: the first pattern of each package.
50
+ dedupe(patterns) {
51
+ const seen = new Set()
52
+ return patterns.filter((pattern) => {
53
+ const ref = this.resolved(pattern)
54
+ if (seen.has(ref)) return false
55
+ seen.add(ref)
56
+ return true
57
+ })
58
+ }
59
+
60
+ seed(patterns) {
61
+ this.prepass(patterns)
62
+ for (const pattern of this.dedupe(patterns)) this.seedOne(pattern, { isDirectRequire: true })
63
+ while (true) {
64
+ let queue = this.levelQueue
65
+ if (queue.length === 0) {
66
+ this.propagateRequired()
67
+ return
68
+ }
69
+ this.levelQueue = []
70
+ queue = queue.sort(([a], [b]) => sortAlpha(a, b))
71
+ let sorted = []
72
+ const available = new Set()
73
+ let changed = true
74
+ while (queue.length > 0 && changed) {
75
+ changed = false
76
+ const copy = queue
77
+ queue = []
78
+ for (const item of copy) {
79
+ const [pattern] = item
80
+ if (this.peersOf(this.resolved(pattern)).every((peer) => available.has(peer))) {
81
+ sorted.push(item)
82
+ available.add(pattern)
83
+ changed = true
84
+ } else queue.push(item)
85
+ }
86
+ }
87
+ sorted = sorted.concat(queue)
88
+ for (const [pattern, parent] of sorted) {
89
+ const info = this.seedOne(pattern, { isDirectRequire: false, parent })
90
+ if (info) this.hoist(info)
91
+ }
92
+ }
93
+ }
94
+
95
+ seedOne(pattern, { isDirectRequire, parent }) {
96
+ const ref = this.resolved(pattern)
97
+ let parentParts = []
98
+ const isIncompatible = ref.incompatible === true
99
+ let isRequired = isDirectRequire && !isIncompatible
100
+ if (parent) {
101
+ if (!this.tree.get(parent.key)) return null
102
+ if (!isDirectRequire && !isIncompatible && parent.isRequired) isRequired = true
103
+ parentParts = parent.parts
104
+ }
105
+ // A package where the tree has it: by its key, the names from the top
106
+ // down to it joined by `#`.
107
+ const parts = parentParts.concat(ref.name)
108
+ const key = implode(parts)
109
+ const info = { key, parts, ref, isDirectRequire, isRequired, isIncompatible }
110
+ this.tree.set(key, info)
111
+ this.taintKey(key, info)
112
+ for (const dependency of new Set(ref.dependencies)) this.levelQueue.push([dependency, info])
113
+ return info
114
+ }
115
+
116
+ propagateRequired() {
117
+ const toVisit = [...this.tree.values()].filter((info) => info.isRequired)
118
+ while (toVisit.length > 0) {
119
+ const info = toVisit.shift()
120
+ for (const dependency of info.ref.dependencies) {
121
+ const found = this.lookupDependency(info, dependency)
122
+ if (found && !found.isRequired && !found.isIncompatible) {
123
+ found.isRequired = true
124
+ toVisit.push(found)
125
+ }
126
+ }
127
+ }
128
+ }
129
+
130
+ lookupDependency(info, pattern) {
131
+ const ref = this.resolved(pattern)
132
+ for (let i = info.parts.length; i >= 0; i--) {
133
+ const existing = this.tree.get(implode(info.parts.slice(0, i).concat(ref.name)))
134
+ if (existing) return existing
135
+ }
136
+ return null
137
+ }
138
+
139
+ newParts(key, info, parts) {
140
+ let stepUp = false
141
+ const stack = []
142
+ const name = parts.pop()
143
+ for (let i = parts.length - 1; i >= 0; i--) {
144
+ const checkParts = parts.slice(0, i).concat(name)
145
+ const existing = this.tree.get(implode(checkParts))
146
+ if (existing) {
147
+ if (existing.ref.loc === info.ref.loc) {
148
+ if (!existing.isRequired && info.isRequired) existing.isRequired = true
149
+ return { parts: checkParts, duplicate: true }
150
+ }
151
+ break
152
+ }
153
+ const taint = this.tainted.get(implode(checkParts))
154
+ if (taint && taint.ref.loc !== info.ref.loc) break
155
+ }
156
+ const peers = this.peersOf(info.ref)
157
+ hoistLoop: while (parts.length > 0) {
158
+ for (const peer of peers) {
159
+ if (this.tree.get(implode(parts.concat(peer)))) break hoistLoop
160
+ }
161
+ const checkKey = implode(parts.concat(name))
162
+ if (this.tree.get(checkKey)) {
163
+ stepUp = true
164
+ break
165
+ }
166
+ if (key !== checkKey && this.tainted.has(checkKey)) {
167
+ stepUp = true
168
+ break
169
+ }
170
+ stack.push(parts.pop())
171
+ }
172
+ parts.push(name)
173
+ const isValidPosition = (candidate) => {
174
+ if (candidate.length <= 0) return false
175
+ const candidateKey = implode(candidate)
176
+ const existing = this.tree.get(candidateKey)
177
+ if (existing && existing.ref.loc === info.ref.loc) return true
178
+ const taint = this.tainted.get(candidateKey)
179
+ return !(taint && taint.ref.loc !== info.ref.loc)
180
+ }
181
+ if (!isValidPosition(parts)) stepUp = true
182
+ while (stepUp && stack.length > 0) {
183
+ parts.pop()
184
+ parts.push(stack.pop(), name)
185
+ if (isValidPosition(parts)) stepUp = false
186
+ }
187
+ return { parts, duplicate: false }
188
+ }
189
+
190
+ hoist(info) {
191
+ const { key: oldKey, parts: rawParts } = info
192
+ this.tree.delete(oldKey)
193
+ const { parts, duplicate } = this.newParts(oldKey, info, rawParts.slice())
194
+ const newKey = implode(parts)
195
+ // yarn's declareRename: each key it passed over reserved for it.
196
+ if (duplicate || newKey !== oldKey) {
197
+ for (let i = parts.length - 1; i < rawParts.length - 1; i++) this.taintKey(implode(rawParts.slice(0, i).concat(info.ref.name)), info)
198
+ }
199
+ if (duplicate) return
200
+ info.key = newKey
201
+ info.parts = parts
202
+ this.tree.set(newKey, info)
203
+ }
204
+
205
+ prepass(rawPatterns) {
206
+ const patterns = this.dedupe(rawPatterns).sort()
207
+ const visited = new Map()
208
+ const occurrences = Object.create(null)
209
+ const visitAdd = (ref, ancestry, pattern) => {
210
+ const versions = (occurrences[ref.name] ??= Object.create(null))
211
+ const version = (versions[ref.version] ??= { occurrences: new Set(), pattern })
212
+ if (ancestry.length > 0) version.occurrences.add(ancestry.at(-1))
213
+ }
214
+ const add = (pattern, ancestry, ancestryPatterns) => {
215
+ const ref = this.resolved(pattern)
216
+ if (ancestry.includes(ref)) return
217
+ let visitedPattern = visited.get(pattern)
218
+ if (visitedPattern) {
219
+ for (const visit of visitedPattern) visitAdd(visit.ref, visit.ancestry, visit.pattern)
220
+ visitAdd(ref, ancestry, pattern)
221
+ return
222
+ }
223
+ visitAdd(ref, ancestry, pattern)
224
+ for (const dependency of ref.dependencies) add(dependency, ancestry.concat(ref), ancestryPatterns.concat(dependency))
225
+ visitedPattern = visited.get(pattern) ?? []
226
+ visited.set(pattern, visitedPattern)
227
+ visitedPattern.push({ ref, ancestry, pattern })
228
+ for (const ancestryPattern of ancestryPatterns) visited.get(ancestryPattern)?.push({ ref, ancestry, pattern })
229
+ }
230
+ const rootNames = new Set()
231
+ for (const pattern of patterns) {
232
+ rootNames.add(this.resolved(pattern).name)
233
+ add(pattern, [], [])
234
+ }
235
+ for (const name of Object.keys(occurrences).sort()) {
236
+ const versions = occurrences[name]
237
+ if (Object.keys(versions).length === 1 || this.tree.get(name) || rootNames.has(name)) continue
238
+ let mostCount
239
+ let mostPattern
240
+ for (const version of Object.keys(versions).sort()) {
241
+ const { occurrences: occurred, pattern } = versions[version]
242
+ if (!mostCount || occurred.size > mostCount) {
243
+ mostCount = occurred.size
244
+ mostPattern = pattern
245
+ }
246
+ }
247
+ if (mostCount > 1) this.seedOne(mostPattern, { isDirectRequire: false })
248
+ }
249
+ }
250
+
251
+ // The tree, flat: each package required, by the names from the top down
252
+ // to it; one yarn leaves to the aggregator, its workspaces' own place,
253
+ // with them. `aggregator` the aggregator's name, if any.
254
+ flatten(aggregator) {
255
+ const flat = []
256
+ for (const [key, info] of this.tree) {
257
+ if (!info.isRequired) continue
258
+ const names = key.split('#')
259
+ if (aggregator !== undefined && names[0] === aggregator && names.length <= 2) continue
260
+ flat.push({ names, info })
261
+ }
262
+ return flat
263
+ }
264
+ }
@@ -0,0 +1,125 @@
1
+ // What buildYarn1Tree takes, checked: the host yarn would install on, and
2
+ // the files an install reads — given as text, or read from the project
3
+ // (../pnpm/project.js) as yarn reads them from disk.
4
+
5
+ import { valid } from '@preventive/upstream/semver.js'
6
+ import { DeptreeError, quote } from '../error.js'
7
+ import { checkProject, readText, typeOf } from '../pnpm/project.js'
8
+ import { matchesGlob, reachesBelow } from './glob.js'
9
+ import { globsOf, readManifest } from './manifest.js'
10
+ import { readSettings } from './settings.js'
11
+
12
+ // The yarn that installs: host.yarn, or where that is left out, the one
13
+ // the root package.json's packageManager pins, as corepack runs that one;
14
+ // a 1.22.x, the line this follows.
15
+ function yarnOf(yarn, root) {
16
+ if (yarn !== undefined && (typeof yarn !== 'string' || yarn === '')) throw new TypeError('host.yarn must be a non-empty string, or left out')
17
+ const { packageManager } = root
18
+ let pinned
19
+ if (packageManager !== undefined) {
20
+ const match = typeof packageManager === 'string' ? /^([^@]+)@([^+]+)(?:\+.*)?$/u.exec(packageManager) : null
21
+ if (match === null || match[1] !== 'yarn' || valid(match[2]) !== match[2]) throw new DeptreeError(`${quote(String(packageManager))} is not yarn at an exact version, which corepack would run instead`, 'manifests["."].packageManager')
22
+ pinned = match[2]
23
+ }
24
+ const version = yarn ?? pinned
25
+ if (version === undefined) throw new TypeError('host.yarn must be given where the root package.json\'s packageManager pins no yarn')
26
+ if (pinned !== undefined && pinned !== version) throw new DeptreeError(`the project is installed by yarn ${pinned}, which corepack runs, not ${version}`, 'manifests["."].packageManager')
27
+ if (!/^1\.22\.\d+$/u.test(version) || valid(version) !== version) throw new DeptreeError(`yarn ${quote(version)} is not supported: only yarn 1.22.x is`, 'host.yarn')
28
+ return version
29
+ }
30
+
31
+ export function checkHost(host, root) {
32
+ if (host === null || typeof host !== 'object') throw new TypeError('host must be an object with node, os and cpu, and yarn where it is not pinned')
33
+ for (const key of ['node', 'os', 'cpu']) {
34
+ if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
35
+ }
36
+ if (valid(host.node) !== host.node) throw new DeptreeError(`${quote(host.node)} is not an exact version`, 'host.node')
37
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: yarn links bins there with shims, and workspaces with junctions', 'host.os')
38
+ return { yarn: yarnOf(host.yarn, root), node: host.node, os: host.os, cpu: host.cpu }
39
+ }
40
+
41
+ // yarn reads a yarn.json beside each package.json it reads, or in its
42
+ // stead, as the manifest of its own registry.
43
+ const yarnJson = 'a yarn.json, which yarn reads as a manifest too, is not supported'
44
+
45
+ // The directories of the workspaces in `project` as yarn's resolveWorkspaces
46
+ // finds them: each with a package.json that a glob takes, outside
47
+ // node_modules. Every directory a glob may reach is read; a link in one,
48
+ // which node-glob follows or not by where it is, is refused, and so is a
49
+ // node_modules a glob would take, whose package.json yarn would read.
50
+ function findWorkspaces(project, globs) {
51
+ const found = []
52
+ if (globs.length === 0) return found
53
+ const pending = ['']
54
+ while (pending.length > 0) {
55
+ const dir = pending.pop()
56
+ for (const name of project.readdir(`/${dir}`)) {
57
+ const path = dir === '' ? name : `${dir}/${name}`
58
+ const taken = globs.some((glob) => matchesGlob(glob, path))
59
+ if (!taken && !globs.some((glob) => reachesBelow(glob, path))) continue
60
+ const { type } = project.lstat(`/${path}`)
61
+ if (type === 'symlink') throw new DeptreeError('a link where yarn looks for workspaces is not supported', quote(path))
62
+ if (type !== 'directory') continue
63
+ const manifest = taken && typeOf(project, `/${path}/package.json`) !== undefined
64
+ if (name === 'node_modules') {
65
+ if (manifest) throw new DeptreeError('yarn would read this node_modules as a workspace, which is not supported', quote(path))
66
+ continue
67
+ }
68
+ if (taken && typeOf(project, `/${path}/yarn.json`) !== undefined) throw new DeptreeError(yarnJson, quote(`${path}/yarn.json`))
69
+ if (manifest) found.push(path)
70
+ pending.push(path)
71
+ }
72
+ }
73
+ return found.sort()
74
+ }
75
+
76
+ function readRoot(project) {
77
+ const text = readText(project, '/package.json', 'manifests["."]')
78
+ if (text === undefined) throw new DeptreeError('the project has no package.json at its root', 'manifests["."]')
79
+ if (typeOf(project, '/yarn.json') !== undefined) throw new DeptreeError(yarnJson, 'yarn.json')
80
+ return readManifest(text, 'manifests["."]')
81
+ }
82
+
83
+ // The directories of the projects yarn installs in `project`: `.`, then
84
+ // each workspace's, as buildYarn1Tree takes their package.json given.
85
+ export function findYarn1Workspaces(options) {
86
+ const { project } = options ?? {}
87
+ checkProject(project)
88
+ return ['.', ...findWorkspaces(project, globsOf(readRoot(project)))]
89
+ }
90
+
91
+ const LOCKFILE = 'lockfile must be the text of yarn.lock, or left out with a project given to read it from'
92
+
93
+ // The files an install reads, given or read from the project: yarn.lock,
94
+ // each package.json by directory, the root's `.` among them, and what of
95
+ // the .yarnrc and .npmrc the install follows.
96
+ export function inputsOf(options) {
97
+ const { lockfile, manifests, yarnrc, npmrc, project } = options
98
+ if (project !== undefined) checkProject(project)
99
+ if (lockfile === undefined) {
100
+ if (project === undefined) throw new TypeError(LOCKFILE)
101
+ for (const [name, value] of Object.entries({ manifests, yarnrc, npmrc })) {
102
+ if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: both are read from project`)
103
+ }
104
+ const text = readText(project, '/yarn.lock')
105
+ if (text === undefined) throw new DeptreeError('the project has no yarn.lock, which a frozen install cannot do without')
106
+ const read = new Map([['.', readRoot(project)]])
107
+ for (const dir of findWorkspaces(project, globsOf(read.get('.')))) {
108
+ read.set(dir, readManifest(readText(project, `/${dir}/package.json`, `manifests[${quote(dir)}]`), `manifests[${quote(dir)}]`))
109
+ }
110
+ if (typeOf(project, '/.yarnrc.yml') !== undefined) throw new DeptreeError('a .yarnrc.yml, whose yarnPath yarn 1.22 runs in its stead, is not supported', '.yarnrc.yml')
111
+ const rc = readText(project, '/.yarnrc')
112
+ const npm = readText(project, '/.npmrc')
113
+ return { lockfile: text, manifests: read, settings: readSettings({ yarnrc: rc, npmrc: npm }), project }
114
+ }
115
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
116
+ if (manifests === null || typeof manifests !== 'object') throw new TypeError('manifests must map each project\'s directory to its package.json')
117
+ for (const [name, value] of Object.entries({ yarnrc, npmrc })) {
118
+ if (value !== undefined && typeof value !== 'string') throw new TypeError(`${name} must be a string, or left out`)
119
+ }
120
+ const settings = readSettings({ yarnrc, npmrc })
121
+ const read = new Map()
122
+ for (const [dir, text] of manifests instanceof Map ? manifests : Object.entries(manifests)) read.set(dir, readManifest(text, `manifests[${quote(dir)}]`))
123
+ if (!read.has('.')) throw new DeptreeError('the root package.json is not given', 'manifests["."]')
124
+ return { lockfile, manifests: read, settings, project }
125
+ }
@@ -0,0 +1,79 @@
1
+ // A package.json as yarn 1 reads one (util/normalize-manifest): its text
2
+ // parsed, its dependency lists as yarn leaves them, its workspace globs,
3
+ // and what of the root's yarn fails on, or would install otherwise than
4
+ // this follows.
5
+
6
+ import { DeptreeError, quote } from '../error.js'
7
+
8
+ // yarn's readJson reads a package.json as pnpm does: a byte order mark
9
+ // dropped.
10
+ export { readManifest } from '../pnpm/projects.js'
11
+
12
+ // yarn's cleanDependencies: a name in several of the dependency lists kept
13
+ // in the first of optionalDependencies, dependencies and devDependencies,
14
+ // at the first of its ranges that is neither '' nor '*'.
15
+ export function cleanDependencies(manifest) {
16
+ const kinds = ['optionalDependencies', 'dependencies', 'devDependencies'].filter((kind) => manifest[kind] !== null && typeof manifest[kind] === 'object')
17
+ const ranges = new Map()
18
+ for (const kind of kinds) {
19
+ for (const [name, range] of Object.entries(manifest[kind])) if (!ranges.has(name) && range && range !== '*') ranges.set(name, range)
20
+ }
21
+ const seen = new Set()
22
+ for (const kind of kinds) {
23
+ const list = manifest[kind]
24
+ for (const name of Object.keys(list)) {
25
+ if (seen.has(name)) delete list[name]
26
+ else {
27
+ list[name] = ranges.get(name) ?? list[name]
28
+ seen.add(name)
29
+ }
30
+ }
31
+ }
32
+ return manifest
33
+ }
34
+
35
+ // The lists of a package.json this reads, as yarn's normalize-manifest
36
+ // leaves them: a `//` key, a comment, dropped, a value that is not one
37
+ // given as `''`, and a name in several of the dependency lists kept in
38
+ // one (cleanDependencies). A copy; the manifest is left as it is.
39
+ const LISTS = ['resolutions', 'devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']
40
+ export function fixLists(manifest) {
41
+ const fixed = { ...manifest }
42
+ for (const kind of LISTS) {
43
+ const list = manifest[kind]
44
+ if (!list || typeof list !== 'object') continue
45
+ const copy = Array.isArray(list) ? [...list] : { ...list }
46
+ delete copy['//']
47
+ for (const name in copy) copy[name] = copy[name] || ''
48
+ fixed[kind] = copy
49
+ }
50
+ return cleanDependencies(fixed)
51
+ }
52
+
53
+ // The workspace globs of the root, as yarn reads them.
54
+ export function globsOf(root) {
55
+ const value = root.workspaces
56
+ if (value === undefined) return []
57
+ return (Array.isArray(value) ? value : value?.packages ?? []).map((glob) => String(glob).replace(/^(?:\.\/)+|\/+$/gu, ''))
58
+ }
59
+
60
+ // What yarn's normalize-manifest fails on in the root's name and version,
61
+ // which the lockfile reader does not read; and what of the root yarn would
62
+ // install otherwise than this follows.
63
+ const NAME = /[/@\s+%:]/u
64
+ const validName = (name) => !NAME.test(name) && encodeURIComponent(name) === name
65
+ export function checkRoot(root) {
66
+ const { name, version } = root
67
+ for (const [key, value] of Object.entries({ name, version })) {
68
+ if (value && typeof value !== 'string') throw new DeptreeError('not a string, which yarn fails on', `manifests["."].${key}`)
69
+ }
70
+ if (typeof name === 'string') {
71
+ const parts = name.startsWith('@') ? name.slice(1).split('/') : undefined
72
+ const legal = parts === undefined ? validName(name) : parts.length === 2 && parts.every(validName)
73
+ if (name.startsWith('.') || !legal || ['node_modules', 'favicon.ico'].includes(name.toLowerCase())) throw new DeptreeError(`${quote(name)} is a name yarn fails on`, 'manifests["."].name')
74
+ }
75
+ if (root.installConfig?.pnp) throw new DeptreeError('Plug\'n\'Play is not supported', 'manifests["."].installConfig.pnp')
76
+ if (root.flat) throw new DeptreeError('a flat install is not supported', 'manifests["."].flat')
77
+ const nohoist = root.workspaces?.nohoist
78
+ if (Array.isArray(nohoist) && nohoist.length > 0) throw new DeptreeError('nohoist is not supported', 'manifests["."].workspaces.nohoist')
79
+ }
@@ -0,0 +1,148 @@
1
+ // A registry package as yarn 1 installs it: its tarball fetched through
2
+ // @preventive/upstream and held to the lockfile's sha512 integrity, and to
3
+ // the sha1 after the `#` of its URL where there is one, as yarn checks
4
+ // both; unpacked as yarn's tarball fetcher unpacks it, with tar-fs, the
5
+ // first segment of each name dropped, each file's mode with 0o644 added
6
+ // and masked by a umask of 0o022; and its package.json read as yarn's
7
+ // normalize-manifest reads the fields it installs by.
8
+ //
9
+ // Held to more than yarn holds it to: a lockfile's URL of it that is the
10
+ // registry's own, as npm spells it, or that on yarn's mirror; and to what
11
+ // npm packs: a gzipped tarball, every entry under one directory, none in
12
+ // the package's own node_modules, which npm packs only for bundled
13
+ // dependencies, no link of either kind or device, no name twice as two
14
+ // different files; and a package.json for exactly the name and version
15
+ // the lockfile has.
16
+
17
+ import { normalize } from '@preventive/vfs/path.js'
18
+ import { DeptreeError, quote } from '../error.js'
19
+ import { sha1Hex } from '../hash.js'
20
+ import { REGISTRY, fetchTarball, sameBytes, tarballUrl } from '../tarball.js'
21
+ import { readManifest } from './manifest.js'
22
+
23
+ const UMASK = 0o022
24
+
25
+ // yarn's mirror of npm's registry, which serves the same tarballs at the
26
+ // same paths.
27
+ const YARNPKG = 'https://registry.yarnpkg.com/'
28
+
29
+ // Each entry by its path in the package, as tar-fs writes it with
30
+ // `strip: 1`: its first segment dropped, and the rest joined to the
31
+ // package's directory as a path from `/`, so `.`, `..` and empty segments
32
+ // folded; files with their bytes and mode, and directories.
33
+ function entriesOf(entries, where) {
34
+ const files = new Map()
35
+ const dirs = new Set()
36
+ let top
37
+ for (const entry of entries) {
38
+ const slash = entry.storedName.indexOf('/')
39
+ const first = slash === -1 ? entry.storedName : entry.storedName.slice(0, slash)
40
+ if (top !== undefined && first !== top) throw new DeptreeError('the tarball has entries under more than one directory', where)
41
+ top = first
42
+ const path = slash === -1 ? '' : normalize(`/${entry.storedName.slice(slash + 1)}`).slice(1).replace(/\/$/u, '')
43
+ if (path.split('/')[0] === 'node_modules') throw new DeptreeError(`${quote(entry.storedName)} is in the package's own node_modules, where yarn installs its dependencies, which is not supported`, where)
44
+ if (entry.type === 'directory') {
45
+ if (path !== '') dirs.add(path)
46
+ continue
47
+ }
48
+ if (entry.type !== 'file' && entry.type !== 'contiguous-file') throw new DeptreeError(`${quote(entry.storedName)} is a ${entry.type}, which is not supported`, where)
49
+ if (path === '') throw new DeptreeError(`${quote(entry.storedName)} is a file at the top of the tarball`, where)
50
+ const file = { data: entry.data, mode: (entry.mode | 0o644) & ~UMASK & 0o777 }
51
+ const earlier = files.get(path)
52
+ if (earlier !== undefined && !(earlier.mode === file.mode && sameBytes(earlier.data, file.data))) throw new DeptreeError(`${quote(path)} is in the tarball twice`, where)
53
+ files.set(path, file)
54
+ }
55
+ for (const path of files.keys()) {
56
+ const segments = path.split('/')
57
+ for (let i = 1; i < segments.length; i++) dirs.add(segments.slice(0, i).join('/'))
58
+ }
59
+ for (const dir of dirs) if (files.has(dir)) throw new DeptreeError(`${quote(dir)} is both a file and a directory in the tarball`, where)
60
+ return { files, dirs }
61
+ }
62
+
63
+ const decoder = new TextDecoder('utf-8', { fatal: true })
64
+
65
+ // The registry's tarball of a lockfile entry: its name, as an `npm:` alias
66
+ // asks for it; held to be the registry's own URL for that name and
67
+ // version, exactly as npm spells it, yarn's mirror taken for npm's.
68
+ export function registryTarball(entry, name, where) {
69
+ const { resolution } = entry
70
+ if (resolution === undefined) throw new DeptreeError('a directory, by file: or link:, is not supported', where)
71
+ const expected = tarballUrl(name, entry.version)
72
+ const url = resolution.type === 'tarball' && resolution.tarball.startsWith(YARNPKG) ? `${REGISTRY}${resolution.tarball.slice(YARNPKG.length)}` : resolution.tarball
73
+ if (url !== expected) throw new DeptreeError(`only the registry's own tarball of ${name}@${entry.version}, ${expected}, is supported`, where)
74
+ const sha512 = resolution.integrity?.split(' ').find((part) => part.startsWith('sha512-'))
75
+ if (sha512 === undefined) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
76
+ return { name, version: entry.version, integrity: sha512, sha1: resolution.sha1 }
77
+ }
78
+
79
+ // The package's entries, as yarn's fetcher leaves them, and its
80
+ // package.json as parsed.
81
+ export async function fetchYarnPackage({ name, version, integrity, sha1 }, where) {
82
+ const { bytes, entries } = await fetchTarball(name, version, integrity, where)
83
+ if (sha1 !== undefined && await sha1Hex(bytes) !== sha1) throw new DeptreeError(`the tarball's sha1 is not ${sha1}`, where)
84
+ const { files, dirs } = entriesOf(entries, where)
85
+ const file = files.get('package.json')
86
+ if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
87
+ let text
88
+ try {
89
+ text = decoder.decode(file.data)
90
+ } catch {
91
+ throw new DeptreeError('package.json is not UTF-8', where)
92
+ }
93
+ const manifest = readManifest(text, `${where}: package.json`)
94
+ if (manifest.name !== name || manifest.version !== version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
95
+ // As yarn's fetcher leaves the package in its cache, from which it copies
96
+ // it wherever it goes (base-fetcher.js): each bin's target made
97
+ // executable, chmod 755, a trailing `/` of it dropped; and a .bin made
98
+ // for links to them, which it fails to make over a file.
99
+ const bins = binsOf(manifest, { files, dirs })
100
+ if (bins.size > 0 && files.has('.bin')) throw new DeptreeError('.bin is a file, where yarn fails to make a directory for the bins', where)
101
+ for (const target of bins.values()) {
102
+ if (target.split('/')[0] === 'node_modules') throw new DeptreeError(`its bin ${quote(target)} is in its own node_modules, where yarn installs its dependencies, which is not supported`, where)
103
+ const script = files.get(target.replace(/\/$/u, ''))
104
+ if (script !== undefined) script.mode = 0o755
105
+ }
106
+ return { files, dirs, manifest }
107
+ }
108
+
109
+ // A bin's name, and its target as a path in the package, as yarn's
110
+ // normalize-manifest has them: a string `bin` named for the package, its
111
+ // scope dropped; a name that is not valid, or a target outside the
112
+ // package, dropped; with no `bin`, each name in directories.bin but for
113
+ // one with a leading dot. `dirs` and `files` the package's. A target is
114
+ // normalized as Node's path.normalize does it, which is as vfs's does: a
115
+ // trailing `/` kept.
116
+ const VALID_BIN_KEYS = /^(?!\.{0,2}$)[a-z0-9._-]+$/iu
117
+
118
+ const outside = (path) => path.startsWith('/') || path === '..' || path.startsWith('../')
119
+
120
+ export function binsOf(manifest, { files, dirs }) {
121
+ let { bin } = manifest
122
+ if (typeof manifest.name === 'string' && typeof bin === 'string' && bin.length > 0) bin = { [manifest.name.replace(/^@[^/]+\//u, '')]: bin }
123
+ const bins = new Map()
124
+ if (bin !== null && typeof bin === 'object') {
125
+ for (const [key, target] of Object.entries(bin)) {
126
+ if (!VALID_BIN_KEYS.test(key)) continue
127
+ if (typeof target !== 'string') throw new DeptreeError(`its bin ${quote(key)} is not a string, which yarn fails on`, quote(manifest.name))
128
+ const path = normalize(target)
129
+ if (!outside(path)) bins.set(key, path)
130
+ }
131
+ return bins
132
+ }
133
+ const binDir = manifest.directories?.bin
134
+ if (typeof binDir === 'string' && binDir) {
135
+ const dir = normalize(binDir).replace(/(?<=.)\/$/u, '')
136
+ if (outside(dir)) throw new DeptreeError(`directories.bin, ${quote(binDir)}, is outside the package, which is not supported`, quote(manifest.name))
137
+ if (files.has(dir)) throw new DeptreeError(`directories.bin, ${quote(binDir)}, is a file, which yarn fails to read as a directory`, quote(manifest.name))
138
+ const prefix = dir === '.' ? '' : `${dir}/`
139
+ const names = new Set()
140
+ for (const path of [...files.keys(), ...dirs]) {
141
+ if (!path.startsWith(prefix)) continue
142
+ const [first] = path.slice(prefix.length).split('/')
143
+ if (first !== '' && !first.startsWith('.')) names.add(first)
144
+ }
145
+ for (const name of names) bins.set(name, `${prefix}${name}`)
146
+ }
147
+ return bins
148
+ }
@@ -0,0 +1,58 @@
1
+ // yarn 1's resolvePeerModules (package-linker.js), run before it hoists:
2
+ // each package's peers are looked for along the shortest chain of names it
3
+ // was requested by, and the nearest version found there that takes the
4
+ // peer's range is added to its dependencies, by all of that version's
5
+ // patterns. Where none is found, nothing is added, and yarn warns.
6
+
7
+ import { compareVersions, valid, validRange } from '@preventive/upstream/semver.js'
8
+
9
+ // yarn's satisfiesWithPrereleases (util/semver.js): each comparator of a
10
+ // set tested on its own, with no say of semver's over prereleases, and a
11
+ // `<` with no prerelease of its own made a `<` its lowest one, so that
12
+ // `<2.0.0` takes no 2.0.0-rc.1; read off the range as semver normalizes it.
13
+ const OPERATORS = /^(<=|>=|<|>|=)?(.*)$/u
14
+
15
+ export function satisfiesWithPrereleases(version, range, loose = false) {
16
+ const options = { loose }
17
+ const normalized = validRange(range, options)
18
+ if (normalized === null || !version || valid(version, options) === null) return false
19
+ return normalized.split('||').some((set) => set.split(' ').every((comparator) => {
20
+ const [, operator = '=', bound] = OPERATORS.exec(comparator)
21
+ if (bound === '' || bound === '*') return true
22
+ const order = compareVersions(version, operator === '<' && !bound.includes('-') ? `${bound}-0` : bound, options)
23
+ return { '<': order < 0, '<=': order <= 0, '>': order > 0, '>=': order >= 0, '=': order === 0 }[operator]
24
+ }))
25
+ }
26
+
27
+ // `resolved` is resolve.js's; `manifests` each reference's package.json,
28
+ // by reference, as fetched or as the workspace has it.
29
+ export function resolvePeers(resolved, manifests) {
30
+ const { patterns, byName } = resolved
31
+ for (const ref of new Set(patterns.values())) {
32
+ const manifest = manifests.get(ref)
33
+ const peers = manifest?.peerDependencies
34
+ if (!peers) continue
35
+ const chain = ref.requests.map((request) => request.parentNames ?? []).sort((a, b) => a.length - b.length)[0]
36
+ const distance = (other) => {
37
+ let min = Infinity
38
+ for (const request of other.requests) {
39
+ const names = request.parentNames ?? []
40
+ const d = chain.length - names.length
41
+ if (d >= 0 && d < min && names.every((name, i) => name === chain[i])) min = d
42
+ }
43
+ return min
44
+ }
45
+ for (const [name, range] of Object.entries(peers)) {
46
+ let best = Infinity
47
+ let found
48
+ for (const candidate of new Set((byName.get(name) ?? []).map((pattern) => patterns.get(pattern)))) {
49
+ const d = distance(candidate)
50
+ if (Number.isFinite(d) && d < best && (range === '*' || satisfiesWithPrereleases(candidate.version, range, true))) {
51
+ best = d
52
+ found = candidate
53
+ }
54
+ }
55
+ if (found !== undefined) ref.dependencies.push(...found.patterns)
56
+ }
57
+ }
58
+ }