@preventive/deptree 1.0.0-alpha.4 → 1.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +36 -10
  5. package/pnpm.d.ts +116 -22
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +64 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +59 -10
  15. package/src/mount.js +95 -44
  16. package/src/npm/bins.js +71 -0
  17. package/src/npm/compat.js +92 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +80 -0
  21. package/src/npm/manifests.js +138 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/{pnpm/npmrc.js → npmrc.js} +5 -11
  28. package/src/patch.js +21 -31
  29. package/src/pnpm/bins.js +32 -103
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +49 -86
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +27 -70
  34. package/src/pnpm/gitignore.js +137 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +65 -55
  38. package/src/pnpm/hook.js +26 -31
  39. package/src/pnpm/inputs.js +67 -40
  40. package/src/pnpm/install.js +72 -115
  41. package/src/pnpm/local.js +21 -40
  42. package/src/pnpm/minimatch.js +328 -0
  43. package/src/pnpm/npm-packlist.js +221 -0
  44. package/src/pnpm/overrides.js +10 -49
  45. package/src/pnpm/package.js +120 -0
  46. package/src/pnpm/packlist.js +168 -109
  47. package/src/pnpm/patches.js +18 -25
  48. package/src/pnpm/projects.js +63 -107
  49. package/src/pnpm/readers.js +46 -55
  50. package/src/pnpm/settings.js +60 -97
  51. package/src/pnpm/tree.js +134 -149
  52. package/src/pnpm/uptodate.js +16 -28
  53. package/src/pnpm/workspace.js +122 -131
  54. package/src/project.js +41 -0
  55. package/src/soldeer/config.js +8 -24
  56. package/src/soldeer/inputs.js +2 -5
  57. package/src/soldeer/tree.js +20 -56
  58. package/src/soldeer/zip.js +17 -36
  59. package/src/tarball.js +38 -142
  60. package/src/yarn1/bins.js +9 -19
  61. package/src/yarn1/compat.js +9 -28
  62. package/src/yarn1/hoist.js +53 -68
  63. package/src/yarn1/inputs.js +16 -51
  64. package/src/yarn1/manifest.js +8 -23
  65. package/src/yarn1/package.js +24 -63
  66. package/src/yarn1/peers.js +8 -15
  67. package/src/yarn1/requests.js +19 -37
  68. package/src/yarn1/resolve.js +35 -111
  69. package/src/yarn1/settings.js +14 -41
  70. package/src/yarn1/tree.js +67 -91
  71. package/yarn1.d.ts +30 -2
  72. package/yarn1.js +1 -8
  73. package/src/pnpm/project.js +0 -97
  74. package/src/yarn1/glob.js +0 -52
  75. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -1,59 +1,25 @@
1
- // What yarn 1's resolver makes of a lockfile it installs frozen
2
- // (package-resolver.js, package-request.js): a reference for each package,
3
- // with the requests that led to it and the patterns that name it, and its
4
- // dependencies as the patterns it asks for. Which request makes a package's
5
- // reference, and so whose names its own requests carry, turns on the order
6
- // yarn resolves requests in, which this follows as yarn runs them:
7
- //
8
- // - the top-level requests one after another, each with all it leads to
9
- // before the next: resolutions' patterns, then the root's dependencies,
10
- // devDependencies and optionalDependencies, then the workspace
11
- // aggregator, then the workspaces the root does not depend on;
12
- // - beneath one, every request at once, each taking as many turns of the
13
- // microtask queue as its resolver does before it checks for a package
14
- // of its name and version already resolved, by its resolver, as
15
- // TURNS has them; one that finds none makes
16
- // the reference and starts its own requests, in its place in the queue;
17
- // one that finds one waits, and is added to it once all are resolved;
18
- // - a request a resolution applies to is given the resolution's package,
19
- // as no request at all, or once all are resolved, where the
20
- // resolution's own pattern is not yet;
21
- // - a request of a tag first asks the filesystem whether the tag is a
22
- // directory of the project, which yarn would install instead, and so
23
- // waits for every other request to be done: one alone is checked then,
24
- // and two at once, which the filesystem answers in no set order, are
25
- // refused.
26
- //
27
- // A range that is no semver range, a dist-tag or an `npm:` alias, never
28
- // finds a package of its version, so each request of one makes a reference
29
- // of its own, the last of which its pattern names.
1
+ // yarn 1's resolver (package-resolver.js, package-request.js) on a frozen
2
+ // lockfile. Which request makes a reference, and so whose names its requests
3
+ // carry, turns on yarn's order: top-level requests run one after another.
30
4
 
31
5
  import { satisfies, validRange } from '@preventive/upstream/semver.js'
32
6
  import { DeptreeError, quote } from '../error.js'
33
- import { matchesGlob } from './glob.js'
7
+ import { matchesGlob } from '../glob.js'
34
8
 
35
- // The turns of the microtask queue a request takes before its check, by
36
- // its resolver.
9
+ // Beneath a top-level request, all run at once, each taking these microtask
10
+ // turns, by its resolver, before it checks for a package of its version.
37
11
  const TURNS = { registry: 5, workspace: 3 }
38
12
 
39
13
  // yarn's normalizePattern.
40
14
  export function splitPattern(pattern) {
41
15
  const scoped = pattern.startsWith('@')
42
- const parts = (scoped ? pattern.slice(1) : pattern).split('@')
43
- let name = parts.shift()
44
- let range = 'latest'
45
- const hasVersion = parts.length > 0 && parts.join('@') !== ''
46
- if (parts.length > 0) range = parts.join('@') || '*'
47
- if (scoped) name = `@${name}`
48
- return { name, range, hasVersion }
16
+ const [name, ...parts] = (scoped ? pattern.slice(1) : pattern).split('@')
17
+ const version = parts.join('@')
18
+ return { name: scoped ? `@${name}` : name, range: parts.length === 0 ? 'latest' : version || '*', hasVersion: version !== '' }
49
19
  }
50
20
 
51
- // How yarn's registry resolver reads a range before it looks the pattern
52
- // up (normalizeRange): a semver range, and one with a `:`, an `npm:` alias
53
- // among them, as it is; a tag, any other, as a directory first. One that
54
- // names another source, a URL, a path or a git host, goes to another of
55
- // yarn's resolvers, which are not followed; it is refused, as is any other
56
- // with a `:` or an `@`, and a tag that is not a plain name.
21
+ // yarn's normalizeRange: any range but a semver range or one with a `:`,
22
+ // such as an `npm:` alias, is a tag.
57
23
  const TAG = /^[\w~-][\w.~-]*$/u
58
24
  function kindOf(range, where) {
59
25
  if (validRange(range)) return 'range'
@@ -62,24 +28,16 @@ function kindOf(range, where) {
62
28
  throw new DeptreeError('only a semver range, an npm: alias or a tag is supported', where)
63
29
  }
64
30
 
65
- // What a request's package asks for, as yarn asks, in its order: its
66
- // dependencies, then its optional ones, then, a workspace's, its dev ones;
67
- // each by its pattern, `name@range`, optional or not, dev or not. A
68
- // lockfile entry's are the lockfile reader's targets, which are their
69
- // patterns; one it links to a workspace has lost its range, and is
70
- // refused.
31
+ // What a package asks for, in yarn's order. A lockfile entry's are patterns;
32
+ // one the lockfile reader links to a workspace has lost its range.
71
33
  function asked(info, where) {
72
34
  const workspace = info.kind === 'workspace'
73
35
  const lists = workspace ? info.workspace.manifest : info.entry
74
36
  const kinds = [['dependencies', false, false], ['optionalDependencies', true, false], ...workspace ? [['devDependencies', false, true]] : []]
75
- const out = []
76
- for (const [kind, optional, dev] of kinds) {
77
- for (const [name, value] of Object.entries(lists[kind] ?? {})) {
78
- if (!workspace && value.startsWith('link:')) throw new DeptreeError(`its dependency on ${quote(name)} is a workspace, which is not supported`, where)
79
- out.push({ pattern: workspace ? `${name}@${value}` : value, optional, dev })
80
- }
81
- }
82
- return out
37
+ return kinds.flatMap(([kind, optional, dev]) => Object.entries(lists[kind] ?? {}).map(([name, value]) => {
38
+ if (!workspace && value.startsWith('link:')) throw new DeptreeError(`its dependency on ${quote(name)} is a workspace, which is not supported`, where)
39
+ return { pattern: workspace ? `${name}@${value}` : value, optional, dev }
40
+ }))
83
41
  }
84
42
 
85
43
  // Where yarn's cache keeps a package (generateModuleCachePath), which is
@@ -92,7 +50,6 @@ function locOf({ kind, name, version, entry }) {
92
50
  return `npm\n${name}\n${version}\n${uid !== undefined && uid !== version ? uid : sha1 ?? ''}\n${integrity ? 'integrity' : ''}`
93
51
  }
94
52
 
95
- // The requests yarn resolves, and what they make of the lockfile.
96
53
  class Resolver {
97
54
  constructor({ lockfile, workspaces, rules, isDirectory }) {
98
55
  Object.assign(this, { lockfile, workspaces, rules, isDirectory })
@@ -102,7 +59,6 @@ class Resolver {
102
59
  this.diverted = []
103
60
  }
104
61
 
105
- // A pattern named for a reference.
106
62
  addPattern(pattern, ref) {
107
63
  ref.patterns.push(pattern)
108
64
  this.patterns.set(pattern, ref)
@@ -111,23 +67,13 @@ class Resolver {
111
67
  if (!list.includes(pattern)) list.push(pattern)
112
68
  }
113
69
 
114
- // The workspace a pattern names, where its version is in the range.
115
- workspaceOf(pattern) {
116
- const { name, range } = splitPattern(pattern)
117
- const workspace = this.workspaces.get(name)
118
- return workspace !== undefined && satisfies(workspace.version, range, { loose: true }) ? workspace : undefined
119
- }
120
-
121
- // What a request finds before it checks: a workspace's manifest, or the
122
- // lockfile's entry for the pattern. yarn drops an entry whose version a
123
- // semver range of its pattern does not take (isLockfileEntryOutdated),
124
- // and resolves the pattern anew, which --frozen-lockfile fails on only
125
- // for a top-level one.
70
+ // isLockfileEntryOutdated: yarn resolves anew an entry out of its pattern's
71
+ // range, which --frozen-lockfile fails on only at the top level.
126
72
  infoOf(request) {
127
- const workspace = this.workspaceOf(request.pattern)
128
- if (workspace !== undefined) return { kind: 'workspace', name: workspace.name, version: workspace.version, workspace }
129
- const where = quote(request.pattern)
130
73
  const { name, range, hasVersion } = splitPattern(request.pattern)
74
+ const workspace = this.workspaces.get(name)
75
+ if (workspace !== undefined && satisfies(workspace.version, range, { loose: true })) return { kind: 'workspace', name: workspace.name, version: workspace.version, workspace }
76
+ const where = quote(request.pattern)
131
77
  const tag = kindOf(range, where) === 'tag'
132
78
  const entry = this.lockfile.packages[request.pattern]
133
79
  if (entry === undefined) throw new DeptreeError('yarn would resolve this pattern anew: the lockfile has no entry for it', where)
@@ -137,8 +83,7 @@ class Resolver {
137
83
  return { kind: 'registry', name, version: entry.version, entry, tag }
138
84
  }
139
85
 
140
- // The resolution that applies to a request, by its path; undefined
141
- // where none does, or for a top-level request.
86
+ // No resolution applies to a top-level request.
142
87
  ruleOf({ pattern, parentNames }) {
143
88
  if (parentNames === undefined) return undefined
144
89
  const { name } = splitPattern(pattern)
@@ -147,15 +92,13 @@ class Resolver {
147
92
  }
148
93
 
149
94
  exactMatch(name, version) {
150
- for (const pattern of this.byName.get(name) ?? []) {
151
- const ref = this.patterns.get(pattern)
152
- if (ref.version === version) return ref
153
- }
154
- return undefined
95
+ return this.byName.get(name)?.map((pattern) => this.patterns.get(pattern)).find((ref) => ref.version === version)
155
96
  }
156
97
 
157
- // A request's check: given the package of its name and version, or made
158
- // the reference, its own requests handed back.
98
+ // Waits where a package of its name and version is resolved already; else
99
+ // makes the reference and hands back its own requests. A tag or an alias
100
+ // never finds one, so each request of one makes a reference of its own,
101
+ // the last of which its pattern names.
159
102
  check(request, info) {
160
103
  const { name, range } = splitPattern(request.pattern)
161
104
  const solved = validRange(range) ? info.version : range
@@ -172,29 +115,22 @@ class Resolver {
172
115
  workspace: info.workspace,
173
116
  patterns: [],
174
117
  requests: [request],
175
- dependencies: [],
118
+ asked: asked(info, quote(request.pattern)),
176
119
  optional: request.optional,
177
120
  }
178
121
  this.addPattern(request.pattern, ref)
179
122
  const parentNames = [...request.parentNames ?? [], name]
180
- const children = []
181
- for (const dep of asked(info, quote(request.pattern))) {
182
- ref.dependencies.push(dep.pattern)
183
- children.push({ pattern: dep.pattern, parentNames, optional: dep.optional || (!dep.dev && request.optional) })
184
- }
185
- return children
123
+ return ref.asked.map((dep) => ({ pattern: dep.pattern, parentNames, optional: dep.optional || (!dep.dev && request.optional) }))
186
124
  }
187
125
 
188
- // A request a resolution applies to, given the resolution's package.
189
126
  divert(request, rule) {
190
127
  const target = this.patterns.get(rule.pattern)
191
128
  if (target === undefined) throw new DeptreeError(`the resolution ${quote(rule.path)} applies to it, and yarn never resolves ${quote(rule.pattern)}`, quote(request.pattern))
192
129
  this.addPattern(request.pattern, target)
193
130
  }
194
131
 
195
- // A request about to start: given the resolution's package where one
196
- // applies, or else timed for its check. Where yarn has not resolved the
197
- // resolution's own pattern yet, the request waits until all else is.
132
+ // Given the resolution's package where one applies, or else timed for its
133
+ // check; a tag's request waits, never counting down, for answer().
198
134
  start(request) {
199
135
  const rule = this.ruleOf(request)
200
136
  if (rule !== undefined) {
@@ -206,8 +142,6 @@ class Resolver {
206
142
  return { request, info, left: info.tag ? Infinity : TURNS[info.kind] }
207
143
  }
208
144
 
209
- // The one request of a tag left waiting, once every other is done, let
210
- // on to its check; refused where the tag is a directory, or might be.
211
145
  answer(waiting) {
212
146
  if (waiting.length > 1) throw new DeptreeError(`yarn resolves these in the order the filesystem answers it, which is not set: ${waiting.map(({ request }) => quote(request.pattern)).join(', ')}`)
213
147
  const [strand] = waiting
@@ -220,8 +154,7 @@ class Resolver {
220
154
  return [strand]
221
155
  }
222
156
 
223
- // A turn of the microtask queue: each request whose turn it is checked,
224
- // the requests it makes started where it stood.
157
+ // A microtask turn: the requests a check makes start where it stood.
225
158
  turn(strands) {
226
159
  const next = []
227
160
  for (const strand of strands) {
@@ -231,7 +164,6 @@ class Resolver {
231
164
  return next
232
165
  }
233
166
 
234
- // A top-level request, and all it leads to.
235
167
  run(request) {
236
168
  let strands = [this.start(request)].filter(Boolean)
237
169
  while (strands.length > 0) {
@@ -240,8 +172,7 @@ class Resolver {
240
172
  }
241
173
  }
242
174
 
243
- // resolveToExistingVersion: each waiting request, in turn, added to the
244
- // package of its version; then each a resolution applies to that waited.
175
+ // yarn's resolveToExistingVersion for the delayed, then the diverted.
245
176
  settle() {
246
177
  for (const request of this.delayed) {
247
178
  const { name } = splitPattern(request.pattern)
@@ -254,16 +185,9 @@ class Resolver {
254
185
  }
255
186
  }
256
187
 
257
- // `lockfile` as @preventive/lockfile's parseYarn1Lockfile reads it;
258
- // `workspaces` by name, in the order yarn finds them, each with its
259
- // directory, cleaned version and manifest, the aggregator among them;
260
- // `rules` the root's resolutions; `top` the top-level requests in order;
261
- // `isDirectory(tag)` whether the project has a `<tag>/package.json`, or
262
- // undefined where that is not known.
263
188
  export function resolve({ top, ...options }) {
264
189
  const resolver = new Resolver(options)
265
190
  for (const request of top) resolver.run(request)
266
191
  resolver.settle()
267
- const { patterns, byName } = resolver
268
- return { patterns, byName }
192
+ return { patterns: resolver.patterns, byName: resolver.byName }
269
193
  }
@@ -1,31 +1,14 @@
1
1
  // The project's .yarnrc and .npmrc, as far as yarn 1 reads them for an
2
- // install. Two settings are followed as yarn follows them:
3
- //
4
- // - ignore-engines: by a flag, `--ignore-engines` or
5
- // `--install.ignore-engines`, where its value is true; or as an option,
6
- // the .yarnrc's where it has one, else the .npmrc's, where its value is
7
- // truthy, as yarn reads it: a quoted "false" is;
8
- // - ignore-platform: by a flag alone; yarn reads the option, and does not
9
- // act on it.
10
- //
11
- // Of the options, yarn reads each by its name from the .yarnrc, or else
12
- // the .npmrc (config.getOption): those that change the tree are refused
13
- // rather than followed — ignore-optional, production, bin-links, the
14
- // workspaces' switches and the like — and so is yarn-path, which has
15
- // another yarn run, and global-folder, which, where it is the project's
16
- // own directory, has yarn read its package.json files otherwise; one yarn reads only for where it fetches from, how,
17
- // and what it keeps, or reads for no install at all, as most of npm's,
18
- // is passed over, as the tree is held to the lockfile's integrities
19
- // whatever serves it. A `--` line of .yarnrc is a flag yarn adds to its
20
- // command line, for every command or, with one before a dot, for that one:
21
- // one that does not change the tree is passed over, and any other is
22
- // refused, whichever command it is for.
2
+ // install, the .yarnrc's options over the .npmrc's. ignore-platform is
3
+ // followed only as a flag, as yarn reads the option and does not act on it.
4
+ // Options that change the tree are refused; the rest are for where and how
5
+ // yarn fetches, and the tree is held to the lockfile's integrities. A `--`
6
+ // line of .yarnrc is a flag yarn adds to its command line.
23
7
 
24
8
  import { DeptreeError, quote } from '../error.js'
25
- import { parseNpmrc } from '../pnpm/npmrc.js'
9
+ import { parseNpmrc } from '../npmrc.js'
26
10
 
27
- // Flags passed over, by name: of those yarn 1.22 takes, the ones that do
28
- // not change the tree.
11
+ // yarn 1.22's flags that do not change the tree.
29
12
  const PASSED = new Set([
30
13
  'verbose', 'silent', 'json', 'har', 'emoji', 'no-emoji', 'progress', 'no-progress', 'non-interactive', 'no-node-version-check',
31
14
  'offline', 'prefer-offline', 'registry', 'proxy', 'https-proxy', 'network-concurrency', 'network-timeout', 'otp', 'mutex',
@@ -33,39 +16,31 @@ const PASSED = new Set([
33
16
  'check-files', 'pure-lockfile', 'frozen-lockfile', 'audit', 'disable-pnp',
34
17
  ])
35
18
 
36
- // Options yarn reads that change the tree, by name: of all yarn 1.22
37
- // reads by config.getOption, and yarn-path, which it reads first. Where
38
- // global-folder is the project's directory, as a relative one in its
39
- // .yarnrc may be, yarn reads no package.json with validate(), which drops
40
- // a name listed twice from all but one of its lists.
19
+ // Of the options yarn 1.22 reads by config.getOption, those that change the
20
+ // tree, and yarn-path, which runs another yarn. global-folder may be the
21
+ // project's directory, where yarn reads no package.json with validate(),
22
+ // which drops a name listed twice from all but one of its lists.
41
23
  const REFUSED = new Set([
42
24
  'ignore-optional', 'production', 'bin-links', 'workspaces-experimental', 'workspaces-nohoist-experimental', 'plugnplay-override',
43
25
  'yarn-link-file-dependencies', 'enable-meta-folder', 'experimental-pack-script-packages-in-mirror', 'global-folder', 'yarn-path',
44
26
  'yarnPath',
45
27
  ])
46
28
 
47
- // Settings followed, by name.
48
29
  const FOLLOWED = new Set(['ignore-engines', 'ignore-platform'])
49
30
 
50
- // A flag's command, `*` for every one, and its name; undefined for an
51
- // option.
52
31
  function flagOf(key) {
53
32
  const match = /^--(?:(.*?)\.)?(.*)$/u.exec(key)
54
33
  return match === null ? undefined : { command: match[1] ?? '*', name: match[2] }
55
34
  }
56
35
 
57
- // A setting, flag or option, that is not followed: refused where it may
58
- // change the tree.
59
36
  function check(key, where) {
60
37
  const flag = flagOf(key)
61
38
  if (flag === undefined ? REFUSED.has(key) : !PASSED.has(flag.name)) throw new DeptreeError(`${quote(key)} is a setting not supported here: it may change what yarn installs`, where)
62
39
  }
63
40
 
64
- // .yarnrc as yarn's parser reads it, as far as a line of a key and a value
65
- // goes, each bare or quoted as JSON writes it; anything else is refused.
66
- // Each setting by its key, the last line of a key the one yarn keeps, with
67
- // its value where it is a bare true or false, or a quoted string, as yarn
68
- // reads those; undefined for any other, or none.
41
+ // .yarnrc as yarn's parser reads it, as far as a key and a value per line
42
+ // go, each bare or quoted as JSON writes it. The last line of a key wins; a
43
+ // bare value but true or false, or none, is undefined.
69
44
  const TOKEN = /"(?:[^"\\]|\\.)*"|[^\s"]+/gu
70
45
 
71
46
  function unquote(token, what, where) {
@@ -94,8 +69,6 @@ function readYarnrc(text) {
94
69
  return settings
95
70
  }
96
71
 
97
- // What the install follows of the .yarnrc and the .npmrc, either of them
98
- // left out where there is none: { ignoreEngines, ignorePlatform }.
99
72
  export function readSettings({ yarnrc, npmrc }) {
100
73
  const flags = new Set()
101
74
  let option
package/src/yarn1/tree.js CHANGED
@@ -1,25 +1,15 @@
1
- // A node_modules tree as yarn 1 installs it from yarn.lock, frozen and with
2
- // scripts ignored: `yarn install --frozen-lockfile --ignore-scripts`, into a
3
- // directory with no node_modules yet. The lockfile is resolved as yarn
4
- // resolves it (resolve.js), each package's peers looked for as yarn looks
5
- // (peers.js), each package left out that the host cannot run and that is
6
- // optional (compat.js), and the tree laid out as yarn hoists it (hoist.js):
7
- // each package's files copied where it lands, as yarn's fetcher leaves
8
- // them, each bin's target executable, and each workspace linked where it
9
- // lands.
10
- //
11
- // Not written: bins themselves (node_modules/.bin), yarn's own
12
- // .yarn-integrity, and anything a script would build.
1
+ // A node_modules tree as `yarn install --frozen-lockfile --ignore-scripts`
2
+ // makes it in a directory with no node_modules yet. Not written:
3
+ // node_modules/.bin, yarn's .yarn-integrity, and anything a script builds.
13
4
 
14
5
  import { parseYarn1Lockfile } from '@preventive/lockfile/yarn1.js'
15
- import { Vfs, VfsError } from '@preventive/vfs'
16
- import { dirname, relative } from '@preventive/vfs/path.js'
6
+ import { Vfs } from '@preventive/vfs'
7
+ import { compareNames, dirname, relative } from '@preventive/vfs/path.js'
17
8
  import { clean, satisfies, valid, validRange } from '@preventive/upstream/semver.js'
18
9
  import { eachConcurrently } from '../concurrent.js'
19
10
  import { DeptreeError, quote } from '../error.js'
20
- import { checkNoModules, mount } from '../mount.js'
21
- import { checkCollisions } from '../pnpm/checks.js'
22
- import { typeOf } from '../pnpm/project.js'
11
+ import { checkNoModules, isInside, makeDirs, mount, writeFiles, writeLink } from '../mount.js'
12
+ import { typeOf } from '../project.js'
23
13
  import { checkBinLinks } from './bins.js'
24
14
  import { incompatibility } from './compat.js'
25
15
  import { Hoister } from './hoist.js'
@@ -30,49 +20,32 @@ import { resolvePeers } from './peers.js'
30
20
  import { AGGREGATOR, aggregatorOf, rulesOf, topRequests, workspacesOf } from './requests.js'
31
21
  import { resolve, splitPattern } from './resolve.js'
32
22
 
33
- // What a refusal of a reference is about: the first pattern of it.
34
23
  const whereOf = (ref) => quote(ref.patterns[0])
35
24
 
36
25
  // The basenames yarn's copy passes over, wherever they are in a package.
37
26
  const IGNORED = new Set(['.bin', '.yarn-metadata.json', '.yarn-tarball.tgz'])
38
27
  const skipped = (path) => path.split('/').some((segment) => IGNORED.has(segment))
39
28
 
40
- // The name a registry reference is fetched by: what its first pattern's
41
- // `npm:` alias asks for, or its own.
42
29
  function fetchedName(ref) {
43
30
  const { range } = splitPattern(ref.patterns[0])
44
- if (!range.startsWith('npm:')) return ref.name
45
- return splitPattern(range.slice(4)).name
31
+ return range.startsWith('npm:') ? splitPattern(range.slice(4)).name : ref.name
46
32
  }
47
33
 
48
- // Each registry reference's files and package.json, a few at a time,
49
- // every tarball's URL checked before any is fetched.
50
34
  async function fetchAll(refs) {
51
35
  const fetched = new Map()
52
- const tarballs = refs.map((ref) => {
53
- const where = whereOf(ref)
54
- return { ref, where, tarball: registryTarball(ref.entry, fetchedName(ref), where) }
55
- })
56
- await eachConcurrently(tarballs, async ({ ref, where, tarball }) => {
57
- try {
58
- fetched.set(ref, await fetchYarnPackage(tarball, where))
59
- } catch (error) {
60
- throw error instanceof DeptreeError ? error : new DeptreeError(error.message, where, { cause: error })
61
- }
62
- })
36
+ const tarballs = refs.map((ref) => ({ ref, tarball: registryTarball(ref.entry, fetchedName(ref), whereOf(ref)) }))
37
+ await eachConcurrently(tarballs, async ({ ref, tarball }) => {
38
+ fetched.set(ref, { ...await fetchYarnPackage(tarball, whereOf(ref)), integrity: tarball.integrity })
39
+ }, ({ ref }) => whereOf(ref))
63
40
  return fetched
64
41
  }
65
42
 
66
- // Where the hoister puts a package, from the lockfile's directory, as
67
- // yarn's flat tree has it: under the aggregator, in the workspace's own
68
- // node_modules.
43
+ // Under the aggregator, a package goes in its workspace's node_modules.
69
44
  function locationOf(names, workspaces) {
70
45
  if (names[0] === AGGREGATOR) return `${workspaces.get(names[1]).dir}/node_modules/${names.slice(2).join('/node_modules/')}`
71
46
  return `node_modules/${names.join('/node_modules/')}`
72
47
  }
73
48
 
74
- // The lockfile resolved as yarn resolves it for the project: the
75
- // workspaces, the root's patterns, and resolve.js's result.
76
49
  function resolveProject(inputs, host) {
77
50
  const lockfile = parseYarn1Lockfile(inputs.lockfile, { manifests: Object.fromEntries(inputs.manifests), semver: { clean, satisfies, valid, validRange } })
78
51
  const manifests = new Map([...inputs.manifests].map(([dir, manifest]) => [dir, fixLists(manifest)]))
@@ -80,24 +53,20 @@ function resolveProject(inputs, host) {
80
53
  const workspaces = workspacesOf(manifests)
81
54
  if (workspaces.size > 0) workspaces.set(AGGREGATOR, aggregatorOf(root, workspaces))
82
55
  const rules = rulesOf(root)
83
- const { requests, patterns } = topRequests(root, workspaces, rules)
56
+ const { requests, asked } = topRequests(root, workspaces, rules)
84
57
  const reason = incompatibility(root, host, 'manifests["."]', inputs.settings)
85
58
  if (reason !== undefined) throw new DeptreeError(reason, 'manifests["."]')
86
59
  const { project } = inputs
87
60
  const isDirectory = project === undefined ? () => undefined : (tag) => typeOf(project, `/${tag}/package.json`) !== undefined
88
- return { workspaces, topPatterns: patterns, resolved: resolve({ lockfile, workspaces, rules, top: requests, isDirectory }) }
61
+ return { workspaces, asked, resolved: resolve({ lockfile, workspaces, rules, top: requests, isDirectory }) }
89
62
  }
90
63
 
91
- // Every package fetched, as yarn fetches each before it checks any, and
92
- // read; then each the host cannot run left out where it is optional, and
93
- // refused where it is not, as yarn fails on it. By reference, each one's
94
- // package.json as yarn reads it, a workspace's its own.
64
+ // As in yarn, every package is fetched before any is checked, in the order
65
+ // its resolver hands them over. Of two its cache keeps in one place, only the
66
+ // first is fetched; the rest keep their lockfile entry as package.json, with
67
+ // no peers, bins, platforms or engines, and the first's files, and their
68
+ // URL's sha1 is held to the first's tarball.
95
69
  async function fetchChecked(resolved, host, settings) {
96
- // What yarn's resolver hands its fetcher, in its order: each reference
97
- // its patterns name, once. Of those its cache keeps in one place, two of
98
- // one package, the fetcher fetches the first and passes over the rest,
99
- // whose package.json stays their lockfile entry's: no peers, bins,
100
- // platforms or engines; their files are the first's.
101
70
  const order = [...new Set(resolved.patterns.values())]
102
71
  const first = new Map()
103
72
  for (const ref of order) if (ref.kind === 'registry' && !first.has(ref.loc)) first.set(ref.loc, ref)
@@ -107,7 +76,10 @@ async function fetchChecked(resolved, host, settings) {
107
76
  let manifest = ref.workspace?.manifest
108
77
  if (ref.kind === 'registry') {
109
78
  const head = first.get(ref.loc)
79
+ const { sha1 } = ref.entry.resolution
80
+ if (sha1 !== undefined && fetched.get(head).sha1 !== sha1) throw new DeptreeError(`the tarball's sha1 is not ${sha1}`, whereOf(ref))
110
81
  fetched.set(ref, fetched.get(head))
82
+ ref.hasBins = head === ref && fetched.get(ref).hasBins
111
83
  manifest = head === ref ? fixLists(fetched.get(ref).manifest) : { name: ref.name, version: ref.version }
112
84
  }
113
85
  const bundled = manifest.bundleDependencies ?? manifest.bundledDependencies
@@ -123,64 +95,70 @@ async function fetchChecked(resolved, host, settings) {
123
95
  return { packages: first.size, fetched, manifestOf }
124
96
  }
125
97
 
126
- // The tree as yarn hoists it, flat: each package by where it goes, in the
127
- // order yarn sorts them, by the absolute paths it compares, all under the
128
- // lockfile's directory.
129
- function layout({ resolved, manifestOf, topPatterns, workspaces }) {
98
+ // Sorted as yarn's linker sorts its absolute paths, all under one directory,
99
+ // by localeCompare in Node's locale; that changes nothing written, as a link
100
+ // sorts before what is beneath it in any locale.
101
+ function layout({ resolved, manifestOf, asked, workspaces }) {
130
102
  resolvePeers(resolved, manifestOf)
103
+ for (const ref of manifestOf.keys()) ref.dependencies = ref.asked.map(({ pattern }) => pattern)
131
104
  const hoister = new Hoister(resolved.patterns, (ref) => Object.keys(manifestOf.get(ref)?.peerDependencies ?? {}))
132
- hoister.seed(topPatterns)
105
+ hoister.seed(asked.map(({ pattern }) => pattern))
133
106
  const flat = hoister.flatten(workspaces.size > 0 ? AGGREGATOR : undefined)
134
107
  const placed = flat.map(({ names, info }) => ({ loc: locationOf(names, workspaces), info }))
135
- return placed.sort((a, b) => a.loc.localeCompare(b.loc))
108
+ return { placed: placed.sort((a, b) => a.loc.localeCompare(b.loc)), hoister }
136
109
  }
137
110
 
138
- // Where a path in the tree really is: through each workspace link on its
139
- // way, `links` by where each is to its target, in the order they are made.
111
+ // Where `path` really is, through each link in `links`, in the order made.
140
112
  function realOf(links, path) {
141
113
  for (const [link, target] of links) if (path === link || path.startsWith(`${link}/`)) path = target + path.slice(link.length)
142
114
  return path
143
115
  }
144
116
 
145
- // Each package copied where it goes, and each workspace linked: where a
146
- // package goes beneath a workspace's link, it is copied through the link,
147
- // into the workspace's own node_modules. `links` each link, by where it
148
- // is, to its target; `locations` each reference's copies, where they
149
- // really are.
117
+ // A package beneath a workspace's link is copied through it, so two of the
118
+ // hoister's places may be one real path, which `copies` maps to both.
150
119
  function writeTree(placed, fetched) {
151
120
  const vfs = new Vfs()
152
- vfs.mkdir('/node_modules', { recursive: true })
121
+ makeDirs(vfs, 'node_modules')
153
122
  const links = new Map()
154
123
  const locations = new Map()
155
- let files = 0
156
- let bytes = 0
124
+ const copies = new Map()
125
+ const left = new Map()
126
+ for (const { info: { ref } } of placed) {
127
+ if (ref.kind === 'registry') left.set(fetched.get(ref), (left.get(fetched.get(ref)) ?? 0) + 1)
128
+ }
129
+ const letGo = (pkg) => Object.assign(pkg, { files: undefined, dirs: undefined })
130
+ for (const pkg of new Set(fetched.values())) if (!left.has(pkg)) letGo(pkg)
131
+ const counted = { files: 0, bytes: 0 }
157
132
  for (const { loc, info } of placed) {
158
133
  const { ref } = info
159
134
  const dest = realOf(links, loc)
160
135
  if (!locations.has(ref)) locations.set(ref, [])
161
136
  if (!locations.get(ref).includes(dest)) locations.get(ref).push(dest)
162
137
  if (ref.kind === 'workspace') {
138
+ // readManifests has each workspace in the project.
139
+ if (!isInside(ref.workspace.dir)) throw new DeptreeError('links out of the project', whereOf(ref))
163
140
  links.set(dest, ref.workspace.dir)
164
- vfs.mkdir(`/${dirname(dest)}`, { recursive: true })
165
- vfs.symlink(relative(`/${dirname(dest)}`, `/${ref.workspace.dir}`) || '.', `/${dest}`)
141
+ writeLink(vfs, dest, relative(`/${dirname(dest)}`, `/${ref.workspace.dir}`) || '.')
166
142
  continue
167
143
  }
168
144
  const pkg = fetched.get(ref)
169
- vfs.mkdir(`/${dest}`, { recursive: true })
170
- for (const dir of pkg.dirs) if (!skipped(dir)) vfs.mkdir(`/${dest}/${dir}`, { recursive: true })
171
- for (const [path, file] of pkg.files) {
172
- if (skipped(path)) continue
173
- try {
174
- vfs.writeFile(`/${dest}/${path}`, file.data, { mode: file.mode })
175
- } catch (error) {
176
- if (error instanceof VfsError) throw new DeptreeError(`cannot be written: ${error.message}`, quote(`${dest}/${path}`), { cause: error })
177
- throw error
178
- }
179
- files++
180
- bytes += file.data.length
181
- }
145
+ const earlier = copies.get(dest)
146
+ if (earlier?.[0].ref === ref) earlier.push(info)
147
+ else copies.set(dest, [info])
148
+ writeFiles(vfs, dest, pkg, counted, skipped)
149
+ left.set(pkg, left.get(pkg) - 1)
150
+ if (left.get(pkg) === 0) letGo(pkg)
182
151
  }
183
- return { vfs, links, locations, files, bytes }
152
+ return { vfs, links, locations, copies, ...counted }
153
+ }
154
+
155
+ function listInstalled(copies, fetched, asked, hoister) {
156
+ const prod = hoister.reachedBut('dev', asked)
157
+ const required = hoister.reachedBut('optional', asked)
158
+ return [...copies].map(([path, places]) => {
159
+ const { manifest, integrity } = fetched.get(places[0].ref)
160
+ return { path, name: manifest.name, version: manifest.version, integrity, dev: !places.some((info) => prod.has(info)), optional: !places.some((info) => required.has(info)) }
161
+ }).sort((a, b) => compareNames(a.path, b.path))
184
162
  }
185
163
 
186
164
  export async function buildYarn1Tree(options) {
@@ -192,12 +170,11 @@ export async function buildYarn1Tree(options) {
192
170
  // Refused before anything is fetched; mount checks again.
193
171
  if (into !== undefined) checkNoModules(into, folded)
194
172
  checkRoot(inputs.manifests.get('.'))
195
- const { workspaces, topPatterns, resolved } = resolveProject(inputs, host)
173
+ const { workspaces, asked, resolved } = resolveProject(inputs, host)
196
174
  const { packages, fetched, manifestOf } = await fetchChecked(resolved, host, inputs.settings)
197
- const placed = layout({ resolved, manifestOf, topPatterns, workspaces })
198
- const { vfs, links, locations, files, bytes } = writeTree(placed, fetched)
199
- checkBinLinks({ placed, patterns: resolved.patterns, fetched, manifestOf, locations, realOf: (path) => realOf(links, path) })
200
- if (folded) checkCollisions(vfs)
175
+ const { placed, hoister } = layout({ resolved, manifestOf, asked, workspaces })
176
+ const { vfs, links, locations, copies, files, bytes } = writeTree(placed, fetched)
177
+ checkBinLinks({ placed, patterns: resolved.patterns, locations, realOf: (path) => realOf(links, path) })
201
178
  const stats = {
202
179
  packages,
203
180
  skipped: [...manifestOf.keys()].filter((ref) => ref.incompatible).length,
@@ -206,7 +183,6 @@ export async function buildYarn1Tree(options) {
206
183
  bytes,
207
184
  links: links.size,
208
185
  }
209
- if (into === undefined) return { vfs, stats }
210
- mount(vfs, into, folded)
211
- return { vfs: into, stats }
186
+ const installed = listInstalled(copies, fetched, asked, hoister)
187
+ return { vfs: mount(vfs, into, folded), stats, installed }
212
188
  }