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

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 (79) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +41 -12
  5. package/pnpm.d.ts +158 -25
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +60 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +60 -10
  15. package/src/mount.js +104 -44
  16. package/src/npm/bins.js +54 -0
  17. package/src/npm/compat.js +97 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +75 -0
  21. package/src/npm/manifests.js +130 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/npmrc.js +24 -0
  28. package/src/patch.js +22 -41
  29. package/src/pnpm/bins.js +152 -131
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +53 -96
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +29 -75
  34. package/src/pnpm/gitignore.js +139 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +68 -61
  38. package/src/pnpm/hoisted.js +234 -0
  39. package/src/pnpm/hook.js +26 -31
  40. package/src/pnpm/inputs.js +73 -56
  41. package/src/pnpm/install.js +85 -131
  42. package/src/pnpm/local.js +21 -40
  43. package/src/pnpm/minimatch.js +319 -0
  44. package/src/pnpm/nm-hoist-graph.js +299 -0
  45. package/src/pnpm/nm-hoist.js +149 -0
  46. package/src/pnpm/npm-packlist.js +217 -0
  47. package/src/pnpm/overrides.js +11 -51
  48. package/src/pnpm/package.js +121 -0
  49. package/src/pnpm/packlist.js +169 -109
  50. package/src/pnpm/patches.js +18 -25
  51. package/src/pnpm/projects.js +63 -107
  52. package/src/pnpm/readers.js +63 -83
  53. package/src/pnpm/settings.js +64 -100
  54. package/src/pnpm/tree.js +197 -169
  55. package/src/pnpm/uptodate.js +16 -28
  56. package/src/pnpm/workspace.js +124 -133
  57. package/src/project.js +57 -0
  58. package/src/soldeer/config.js +8 -24
  59. package/src/soldeer/inputs.js +5 -15
  60. package/src/soldeer/tree.js +22 -60
  61. package/src/soldeer/zip.js +17 -36
  62. package/src/tarball.js +55 -140
  63. package/src/yarn1/bins.js +9 -19
  64. package/src/yarn1/compat.js +9 -28
  65. package/src/yarn1/hoist.js +53 -68
  66. package/src/yarn1/inputs.js +19 -61
  67. package/src/yarn1/manifest.js +8 -23
  68. package/src/yarn1/package.js +24 -63
  69. package/src/yarn1/peers.js +8 -15
  70. package/src/yarn1/requests.js +19 -37
  71. package/src/yarn1/resolve.js +36 -113
  72. package/src/yarn1/settings.js +15 -43
  73. package/src/yarn1/tree.js +67 -91
  74. package/yarn1.d.ts +34 -5
  75. package/yarn1.js +1 -8
  76. package/src/pnpm/npmrc.js +0 -31
  77. package/src/pnpm/project.js +0 -97
  78. package/src/yarn1/glob.js +0 -52
  79. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -1,30 +1,23 @@
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.
1
+ // yarn 1's PackageHoister (package-hoister.js), quirks and all: a prepass
2
+ // seeds at the top, of several versions of a package, the one most others
3
+ // depend on, and a level's requests go by pattern, then those with peers,
4
+ // which a check meant to put them after their peers always puts last.
5
+ // Departs from yarn only in leaving out nohoist, --focus and --flat, refused
6
+ // before it runs, and yarn's record of each step; in comparing `loc` where
7
+ // yarn compares cache paths, and references where it compares manifests;
8
+ // and in reachedBut, its own.
14
9
 
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
- }
10
+ import { DeptreeError, quote } from '../error.js'
11
+
12
+ // yarn's prepass recurses down every chain of dependencies, as this one
13
+ // does, keeping each one's ancestry: a chain deeper than this is refused
14
+ // before it runs out of stack, or of memory.
15
+ const DEEPEST = 1000
16
+
17
+ const sortAlpha = (a, b) => (a < b ? -1 : a > b ? 1 : 0)
23
18
 
24
19
  const implode = (parts) => parts.join('#')
25
20
 
26
- // `patterns` resolve.js's, each pattern to its reference; `peersOf` a
27
- // reference's peers' names, from its package.json.
28
21
  export class Hoister {
29
22
  constructor(patterns, peersOf) {
30
23
  this.patterns = patterns
@@ -48,27 +41,16 @@ export class Hoister {
48
41
 
49
42
  // resolver.dedupePatterns: the first pattern of each package.
50
43
  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
- })
44
+ return [...Map.groupBy(patterns, (pattern) => this.resolved(pattern)).values()].map(([first]) => first)
58
45
  }
59
46
 
60
47
  seed(patterns) {
61
48
  this.prepass(patterns)
62
49
  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
- }
50
+ while (this.levelQueue.length > 0) {
51
+ let queue = this.levelQueue.sort(([a], [b]) => sortAlpha(a, b))
69
52
  this.levelQueue = []
70
- queue = queue.sort(([a], [b]) => sortAlpha(a, b))
71
- let sorted = []
53
+ const sorted = []
72
54
  const available = new Set()
73
55
  let changed = true
74
56
  while (queue.length > 0 && changed) {
@@ -84,27 +66,20 @@ export class Hoister {
84
66
  } else queue.push(item)
85
67
  }
86
68
  }
87
- sorted = sorted.concat(queue)
88
- for (const [pattern, parent] of sorted) {
69
+ for (const [pattern, parent] of sorted.concat(queue)) {
89
70
  const info = this.seedOne(pattern, { isDirectRequire: false, parent })
90
71
  if (info) this.hoist(info)
91
72
  }
92
73
  }
74
+ this.propagateRequired()
93
75
  }
94
76
 
95
77
  seedOne(pattern, { isDirectRequire, parent }) {
96
78
  const ref = this.resolved(pattern)
97
- let parentParts = []
79
+ if (parent && !this.tree.get(parent.key)) return null
98
80
  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)
81
+ const isRequired = !isIncompatible && (isDirectRequire || parent?.isRequired === true)
82
+ const parts = (parent?.parts ?? []).concat(ref.name)
108
83
  const key = implode(parts)
109
84
  const info = { key, parts, ref, isDirectRequire, isRequired, isIncompatible }
110
85
  this.tree.set(key, info)
@@ -115,8 +90,9 @@ export class Hoister {
115
90
 
116
91
  propagateRequired() {
117
92
  const toVisit = [...this.tree.values()].filter((info) => info.isRequired)
118
- while (toVisit.length > 0) {
119
- const info = toVisit.shift()
93
+ // In yarn's order, but by index, as shift() copies a long array.
94
+ for (let i = 0; i < toVisit.length; i++) {
95
+ const info = toVisit[i]
120
96
  for (const dependency of info.ref.dependencies) {
121
97
  const found = this.lookupDependency(info, dependency)
122
98
  if (found && !found.isRequired && !found.isIncompatible) {
@@ -127,6 +103,25 @@ export class Hoister {
127
103
  }
128
104
  }
129
105
 
106
+ // Not yarn's: the places reached from `asked`, peers included, by requests
107
+ // whose `kind` (`dev` or `optional`) is not set, past none the host cannot
108
+ // run; every other place is reached by dev, or optional, dependencies alone.
109
+ reachedBut(kind, asked) {
110
+ const queue = [{ parts: [], ref: { asked } }]
111
+ const reached = new Set()
112
+ while (queue.length > 0) {
113
+ const info = queue.pop()
114
+ for (const dep of info.ref.asked) {
115
+ if (dep[kind]) continue
116
+ const found = this.lookupDependency(info, dep.pattern)
117
+ if (found === null || found.isIncompatible || reached.has(found)) continue
118
+ reached.add(found)
119
+ queue.push(found)
120
+ }
121
+ }
122
+ return reached
123
+ }
124
+
130
125
  lookupDependency(info, pattern) {
131
126
  const ref = this.resolved(pattern)
132
127
  for (let i = info.parts.length; i >= 0; i--) {
@@ -154,16 +149,9 @@ export class Hoister {
154
149
  if (taint && taint.ref.loc !== info.ref.loc) break
155
150
  }
156
151
  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
- }
152
+ while (parts.length > 0 && !peers.some((peer) => this.tree.get(implode(parts.concat(peer))))) {
161
153
  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)) {
154
+ if (this.tree.get(checkKey) || (key !== checkKey && this.tainted.has(checkKey))) {
167
155
  stepUp = true
168
156
  break
169
157
  }
@@ -171,12 +159,10 @@ export class Hoister {
171
159
  }
172
160
  parts.push(name)
173
161
  const isValidPosition = (candidate) => {
174
- if (candidate.length <= 0) return false
175
162
  const candidateKey = implode(candidate)
176
- const existing = this.tree.get(candidateKey)
177
- if (existing && existing.ref.loc === info.ref.loc) return true
163
+ if (this.tree.get(candidateKey)?.ref.loc === info.ref.loc) return true
178
164
  const taint = this.tainted.get(candidateKey)
179
- return !(taint && taint.ref.loc !== info.ref.loc)
165
+ return !taint || taint.ref.loc === info.ref.loc
180
166
  }
181
167
  if (!isValidPosition(parts)) stepUp = true
182
168
  while (stepUp && stack.length > 0) {
@@ -214,6 +200,7 @@ export class Hoister {
214
200
  const add = (pattern, ancestry, ancestryPatterns) => {
215
201
  const ref = this.resolved(pattern)
216
202
  if (ancestry.includes(ref)) return
203
+ if (ancestry.length === DEEPEST) throw new DeptreeError(`a chain of more than ${DEEPEST} dependencies is not supported`, quote(pattern))
217
204
  let visitedPattern = visited.get(pattern)
218
205
  if (visitedPattern) {
219
206
  for (const visit of visitedPattern) visitAdd(visit.ref, visit.ancestry, visit.pattern)
@@ -248,9 +235,7 @@ export class Hoister {
248
235
  }
249
236
  }
250
237
 
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.
238
+ // As in yarn, leaves out `aggregator` and what stayed directly beneath it.
254
239
  flatten(aggregator) {
255
240
  const flat = []
256
241
  for (const [key, info] of this.tree) {
@@ -1,17 +1,13 @@
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.
1
+ // What buildYarn1Tree takes, as text or read from the project as yarn does.
4
2
 
5
3
  import { valid } from '@preventive/upstream/semver.js'
6
4
  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'
5
+ import { readManifest, readManifests } from '../manifest.js'
6
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText, typeOf } from '../project.js'
7
+ import { walkWorkspaces } from '../glob.js'
8
+ import { globsOf } from './manifest.js'
10
9
  import { readSettings } from './settings.js'
11
10
 
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
11
  function yarnOf(yarn, root) {
16
12
  if (yarn !== undefined && (typeof yarn !== 'string' || yarn === '')) throw new TypeError('host.yarn must be a non-empty string, or left out')
17
13
  const { packageManager } = root
@@ -29,48 +25,24 @@ function yarnOf(yarn, root) {
29
25
  }
30
26
 
31
27
  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
- }
28
+ checkHostKeys(host, ['node', 'os', 'cpu'], 'node, os and cpu, and yarn where it is not pinned')
36
29
  if (valid(host.node) !== host.node) throw new DeptreeError(`${quote(host.node)} is not an exact version`, 'host.node')
37
30
  if (host.os === 'win32') throw new DeptreeError('Windows is not supported: yarn links bins there with shims, and workspaces with junctions', 'host.os')
38
31
  return { yarn: yarnOf(host.yarn, root), node: host.node, os: host.os, cpu: host.cpu }
39
32
  }
40
33
 
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
34
  const yarnJson = 'a yarn.json, which yarn reads as a manifest too, is not supported'
44
35
 
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.
36
+ // As yarn's resolveWorkspaces finds them.
50
37
  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()
38
+ return walkWorkspaces(project, globs, {
39
+ manager: 'yarn',
40
+ enter: (path, name, taken, manifest) => {
41
+ if (name === 'node_modules' && manifest) throw new DeptreeError('yarn would read this node_modules as a workspace, which is not supported', quote(path))
42
+ if (name !== 'node_modules' && taken && typeOf(project, `/${path}/yarn.json`) !== undefined) throw new DeptreeError(yarnJson, quote(`${path}/yarn.json`))
43
+ return name !== 'node_modules'
44
+ },
45
+ })
74
46
  }
75
47
 
76
48
  function readRoot(project) {
@@ -80,8 +52,6 @@ function readRoot(project) {
80
52
  return readManifest(text, 'manifests["."]')
81
53
  }
82
54
 
83
- // The directories of the projects yarn installs in `project`: `.`, then
84
- // each workspace's, as buildYarn1Tree takes their package.json given.
85
55
  export function findYarn1Workspaces(options) {
86
56
  const { project } = options ?? {}
87
57
  checkProject(project)
@@ -90,17 +60,12 @@ export function findYarn1Workspaces(options) {
90
60
 
91
61
  const LOCKFILE = 'lockfile must be the text of yarn.lock, or left out with a project given to read it from'
92
62
 
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
63
  export function inputsOf(options) {
97
64
  const { lockfile, manifests, yarnrc, npmrc, project } = options
98
65
  if (project !== undefined) checkProject(project)
99
66
  if (lockfile === undefined) {
100
67
  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
- }
68
+ checkLeftOut({ manifests, yarnrc, npmrc })
104
69
  const text = readText(project, '/yarn.lock')
105
70
  if (text === undefined) throw new DeptreeError('the project has no yarn.lock, which a frozen install cannot do without')
106
71
  const read = new Map([['.', readRoot(project)]])
@@ -108,18 +73,11 @@ export function inputsOf(options) {
108
73
  read.set(dir, readManifest(readText(project, `/${dir}/package.json`, `manifests[${quote(dir)}]`), `manifests[${quote(dir)}]`))
109
74
  }
110
75
  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 }
76
+ return { lockfile: text, manifests: read, settings: readSettings({ yarnrc: readText(project, '/.yarnrc'), npmrc: readText(project, '/.npmrc') }), project }
114
77
  }
115
78
  if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
116
79
  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
- }
80
+ checkTexts({ yarnrc, npmrc })
120
81
  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 }
82
+ return { lockfile, manifests: readManifests(manifests), settings, project }
125
83
  }
@@ -1,17 +1,9 @@
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.
1
+ // A package.json as yarn 1's util/normalize-manifest reads it.
5
2
 
6
3
  import { DeptreeError, quote } from '../error.js'
7
4
 
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 '*'.
5
+ // yarn's cleanDependencies: a name in several of these lists is kept in the
6
+ // first, at its first range that is neither '' nor '*'.
15
7
  export function cleanDependencies(manifest) {
16
8
  const kinds = ['optionalDependencies', 'dependencies', 'devDependencies'].filter((kind) => manifest[kind] !== null && typeof manifest[kind] === 'object')
17
9
  const ranges = new Map()
@@ -32,10 +24,7 @@ export function cleanDependencies(manifest) {
32
24
  return manifest
33
25
  }
34
26
 
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.
27
+ // The lists as normalize-manifest leaves them, a `//` key, a comment, dropped.
39
28
  const LISTS = ['resolutions', 'devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']
40
29
  export function fixLists(manifest) {
41
30
  const fixed = { ...manifest }
@@ -50,16 +39,12 @@ export function fixLists(manifest) {
50
39
  return cleanDependencies(fixed)
51
40
  }
52
41
 
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, ''))
42
+ export function globsOf({ workspaces }) {
43
+ return (Array.isArray(workspaces) ? workspaces : workspaces?.packages ?? []).map((glob) => String(glob).replace(/^(?:\.\/)+|\/+$/gu, ''))
58
44
  }
59
45
 
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.
46
+ // What normalize-manifest fails on in the root's name and version, which
47
+ // the lockfile reader does not read; and what of the root is not followed.
63
48
  const NAME = /[/@\s+%:]/u
64
49
  const validName = (name) => !NAME.test(name) && encodeURIComponent(name) === name
65
50
  export function checkRoot(root) {
@@ -1,35 +1,18 @@
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.
1
+ // A registry package as yarn 1 installs it, each mode given 0o644 and masked
2
+ // by a 0o022 umask as yarn's tarball fetcher does with tar-fs. Held to more
3
+ // than yarn holds it to: what npm packs, every entry under one directory,
4
+ // none in its own node_modules (npm packs those only for bundled
5
+ // dependencies), and a package.json of the lockfile's name and version.
16
6
 
17
7
  import { normalize } from '@preventive/vfs/path.js'
18
8
  import { DeptreeError, quote } from '../error.js'
19
9
  import { sha1Hex } from '../hash.js'
20
- import { REGISTRY, fetchTarball, sameBytes, tarballUrl } from '../tarball.js'
21
- import { readManifest } from './manifest.js'
10
+ import { readManifest } from '../manifest.js'
11
+ import { fetchTarball, fromMirror, isModules, ownTarball, sameFile, withDirs } from '../tarball.js'
22
12
 
23
13
  const UMASK = 0o022
24
14
 
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.
15
+ // Paths as tar-fs with `strip: 1` writes them: `.`, `..` and `//` folded.
33
16
  function entriesOf(entries, where) {
34
17
  const files = new Map()
35
18
  const dirs = new Set()
@@ -40,7 +23,7 @@ function entriesOf(entries, where) {
40
23
  if (top !== undefined && first !== top) throw new DeptreeError('the tarball has entries under more than one directory', where)
41
24
  top = first
42
25
  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)
26
+ if (isModules(path.split('/')[0])) 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
27
  if (entry.type === 'directory') {
45
28
  if (path !== '') dirs.add(path)
46
29
  continue
@@ -49,38 +32,25 @@ function entriesOf(entries, where) {
49
32
  if (path === '') throw new DeptreeError(`${quote(entry.storedName)} is a file at the top of the tarball`, where)
50
33
  const file = { data: entry.data, mode: (entry.mode | 0o644) & ~UMASK & 0o777 }
51
34
  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)
35
+ if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(path)} is in the tarball twice`, where)
53
36
  files.set(path, file)
54
37
  }
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 }
38
+ return withDirs(files, where, dirs)
61
39
  }
62
40
 
63
41
  const decoder = new TextDecoder('utf-8', { fatal: true })
64
42
 
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.
43
+ // `name` is the one fetched, as an `npm:` alias asks for it.
68
44
  export function registryTarball(entry, name, where) {
69
45
  const { resolution } = entry
70
46
  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 }
47
+ const url = resolution.type === 'tarball' ? fromMirror(resolution.tarball) : resolution.tarball
48
+ return ownTarball(url, name, entry.version, resolution.integrity, where)
77
49
  }
78
50
 
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) {
51
+ export async function fetchYarnPackage({ name, version, integrity }, where) {
82
52
  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)
53
+ const sha1 = await sha1Hex(bytes)
84
54
  const { files, dirs } = entriesOf(entries, where)
85
55
  const file = files.get('package.json')
86
56
  if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
@@ -92,32 +62,25 @@ export async function fetchYarnPackage({ name, version, integrity, sha1 }, where
92
62
  }
93
63
  const manifest = readManifest(text, `${where}: package.json`)
94
64
  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.
65
+ // As yarn's fetcher leaves the package in its cache (base-fetcher.js): each
66
+ // bin's target chmod 755, and a .bin made for the links.
99
67
  const bins = binsOf(manifest, { files, dirs })
100
68
  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
69
  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)
70
+ if (isModules(target.split('/')[0])) throw new DeptreeError(`its bin ${quote(target)} is in its own node_modules, where yarn installs its dependencies, which is not supported`, where)
103
71
  const script = files.get(target.replace(/\/$/u, ''))
104
72
  if (script !== undefined) script.mode = 0o755
105
73
  }
106
- return { files, dirs, manifest }
74
+ return { files, dirs, manifest, sha1, hasBins: bins.size > 0 }
107
75
  }
108
76
 
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.
77
+ // Bins as yarn's normalize-manifest reads them, targets normalized as Node's
78
+ // path.normalize does it, a trailing `/` kept.
116
79
  const VALID_BIN_KEYS = /^(?!\.{0,2}$)[a-z0-9._-]+$/iu
117
80
 
118
81
  const outside = (path) => path.startsWith('/') || path === '..' || path.startsWith('../')
119
82
 
120
- export function binsOf(manifest, { files, dirs }) {
83
+ function binsOf(manifest, { files, dirs }) {
121
84
  let { bin } = manifest
122
85
  if (typeof manifest.name === 'string' && typeof bin === 'string' && bin.length > 0) bin = { [manifest.name.replace(/^@[^/]+\//u, '')]: bin }
123
86
  const bins = new Map()
@@ -136,13 +99,11 @@ export function binsOf(manifest, { files, dirs }) {
136
99
  if (outside(dir)) throw new DeptreeError(`directories.bin, ${quote(binDir)}, is outside the package, which is not supported`, quote(manifest.name))
137
100
  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
101
  const prefix = dir === '.' ? '' : `${dir}/`
139
- const names = new Set()
140
102
  for (const path of [...files.keys(), ...dirs]) {
141
103
  if (!path.startsWith(prefix)) continue
142
104
  const [first] = path.slice(prefix.length).split('/')
143
- if (first !== '' && !first.startsWith('.')) names.add(first)
105
+ if (first !== '' && !first.startsWith('.')) bins.set(first, `${prefix}${first}`)
144
106
  }
145
- for (const name of names) bins.set(name, `${prefix}${name}`)
146
107
  }
147
108
  return bins
148
109
  }
@@ -1,15 +1,11 @@
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.
1
+ // yarn 1's resolvePeerModules (package-linker.js), run before it hoists: a
2
+ // peer is looked for along the shortest chain of names the package was asked
3
+ // for by, and the nearest in range added; where none is, yarn only warns.
6
4
 
7
5
  import { compareVersions, valid, validRange } from '@preventive/upstream/semver.js'
8
6
 
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.
7
+ // yarn's util/semver.js: semver's prerelease rule ignored, and `<x` with no
8
+ // prerelease read as `<x-0`, so `<2.0.0` takes no 2.0.0-rc.1.
13
9
  const OPERATORS = /^(<=|>=|<|>|=)?(.*)$/u
14
10
 
15
11
  export function satisfiesWithPrereleases(version, range, loose = false) {
@@ -24,12 +20,9 @@ export function satisfiesWithPrereleases(version, range, loose = false) {
24
20
  }))
25
21
  }
26
22
 
27
- // `resolved` is resolve.js's; `manifests` each reference's package.json,
28
- // by reference, as fetched or as the workspace has it.
29
23
  export function resolvePeers(resolved, manifests) {
30
24
  const { patterns, byName } = resolved
31
- for (const ref of new Set(patterns.values())) {
32
- const manifest = manifests.get(ref)
25
+ for (const [ref, manifest] of manifests) {
33
26
  const peers = manifest?.peerDependencies
34
27
  if (!peers) continue
35
28
  const chain = ref.requests.map((request) => request.parentNames ?? []).sort((a, b) => a.length - b.length)[0]
@@ -47,12 +40,12 @@ export function resolvePeers(resolved, manifests) {
47
40
  let found
48
41
  for (const candidate of new Set((byName.get(name) ?? []).map((pattern) => patterns.get(pattern)))) {
49
42
  const d = distance(candidate)
50
- if (Number.isFinite(d) && d < best && (range === '*' || satisfiesWithPrereleases(candidate.version, range, true))) {
43
+ if (d < best && (range === '*' || satisfiesWithPrereleases(candidate.version, range, true))) {
51
44
  best = d
52
45
  found = candidate
53
46
  }
54
47
  }
55
- if (found !== undefined) ref.dependencies.push(...found.patterns)
48
+ if (found !== undefined) ref.asked.push(...found.patterns.map((pattern) => ({ pattern, optional: false, dev: false })))
56
49
  }
57
50
  }
58
51
  }