@preventive/deptree 1.0.0-alpha.5 → 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,23 +1,12 @@
1
1
  // A registry zip as Soldeer 0.12 extracts it (download.rs's
2
- // extract_dependency_archive, over the zip crate 8.6): every entry in the
3
- // order the central directory lists them, read with
4
- // @preventive/archive/zip.js, which refuses what it does not read — `..`,
5
- // absolute and backslashed names, zip64, encryption, two different entries
6
- // of one name — where Soldeer would take some of it otherwise; what the two
7
- // would read otherwise and the archive reader takes is refused here.
8
- //
9
- // A name a component of which is `.git`, as Windows reads one — trailing
10
- // dots and spaces dropped, ASCII letters in either case — is passed over,
11
- // with all beneath it; one with a `:` in it is refused, as Soldeer fails on
12
- // it. A directory is made 0o755, whatever the archive says, and so is every
13
- // directory on the way to an entry. A file's mode is its Unix mode as the
14
- // zip crate reads it, without the type, setuid, setgid, sticky and group
15
- // and other write bits, or 0o644 where it reads none; a symlink is a file,
16
- // 0o644, holding its target. Both modes are as a umask of 0o022 leaves
17
- // them.
2
+ // extract_dependency_archive, zip crate 8.6); what the archive reader takes
3
+ // and the two would read otherwise is refused. As a 0o022 umask leaves them,
4
+ // every directory is 0o755, and a file's mode its Unix mode as the zip crate
5
+ // reads it, or 0o644 where it reads none; a symlink is a file of its target.
18
6
 
19
7
  import { ArchiveError, unzip } from '@preventive/archive/zip.js'
20
8
  import { DeptreeError, quote } from '../error.js'
9
+ import { bytesSha256Hex } from '../hash.js'
21
10
 
22
11
  const END = 0x06054b50
23
12
  const CENTRAL = 0x02014b50
@@ -25,8 +14,7 @@ const UTF8 = 0x0800
25
14
  const S_IFLNK = 0o120000
26
15
  const [NTFS, TIMESTAMP, UNICODE_COMMENT, AES] = [0x000a, 0x5455, 0x6375, 0x9901]
27
16
 
28
- // What a zip may extract to, as a tarball may unpack to (../tarball.js):
29
- // the archive reader makes room for what each entry declares.
17
+ // As in ../tarball.js: the archive reader makes room for what entries declare.
30
18
  const MAX_BYTES = 512 * 1024 * 1024
31
19
 
32
20
  // As the archive reader decodes a name: a leading U+FEFF is part of it.
@@ -35,10 +23,8 @@ const encoder = new TextEncoder()
35
23
 
36
24
  const ones = (byte) => [...byte.toString(2)].filter((bit) => bit === '1').length
37
25
 
38
- // Why the zip crate would fail on an entry's extra fields, which it reads
39
- // from the central directory, or undefined: an NTFS field, or an extended
40
- // timestamp, it does not read; or an AES field, which has it decrypt the
41
- // entry, or a Unicode comment field, which it checks, both refused here.
26
+ // Why the zip crate would fail on an entry's extra fields, or undefined; an
27
+ // AES or a Unicode comment field is refused here.
42
28
  function extraRefusal(view, at, length) {
43
29
  for (let pos = at; pos < at + length;) {
44
30
  const id = view.getUint16(pos, true)
@@ -53,10 +39,8 @@ function extraRefusal(view, at, length) {
53
39
  return undefined
54
40
  }
55
41
 
56
- // What the zip crate reads of each entry that the archive reader does not
57
- // hand out, in the central directory's order: the system that made it, its
58
- // flags, its external attributes, its name's bytes. The layout has been
59
- // checked whole by unzip, so each record is where it says.
42
+ // What the zip crate reads of each entry that unzip does not hand out. unzip
43
+ // has checked the layout whole, so each record is where it says.
60
44
  function centralRecords(bytes) {
61
45
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
62
46
  let end = bytes.length - 22
@@ -78,9 +62,7 @@ function centralRecords(bytes) {
78
62
  return records
79
63
  }
80
64
 
81
- // The zip crate's ZipFileData::unix_mode: the upper half of the external
82
- // attributes, by whatever system; else for MS-DOS its directory and
83
- // read-only bits; else for Unix none at all, 0; else nothing.
65
+ // The zip crate's ZipFileData::unix_mode; system 0 is MS-DOS, and 3 Unix.
84
66
  function unixMode({ system, attributes }) {
85
67
  if (attributes === 0) return undefined
86
68
  const upper = attributes >>> 16
@@ -95,9 +77,10 @@ function unixMode({ system, attributes }) {
95
77
  // a component Soldeer holds to `.git`.
96
78
  const isGit = (component) => component.replace(/[. ]+$/u, '').replace(/[A-Z]/gu, (char) => char.toLowerCase()) === '.git'
97
79
 
98
- // The directories and files of the zip, by their paths under the folder
99
- // Soldeer extracts it in, files with their bytes and modes.
100
- export async function extractZip(bytes, where) {
80
+ // getZip has held the zip to its checksum; it is held to it again where it
81
+ // is unpacked.
82
+ export async function extractZip(bytes, checksum, where) {
83
+ if (await bytesSha256Hex(bytes) !== checksum) throw new DeptreeError(`its zip's sha256 is not ${checksum}`, where)
101
84
  let entries
102
85
  try {
103
86
  entries = await unzip(bytes, { limit: MAX_BYTES })
@@ -106,16 +89,14 @@ export async function extractZip(bytes, where) {
106
89
  throw error
107
90
  }
108
91
  const records = centralRecords(bytes)
109
- // The zip crate keys entries by their names' bytes, which unzip has read
110
- // as UTF-8, so by their stored names: of two of one name, the later is
111
- // extracted, where the first was.
92
+ // The zip crate keys entries by their names' bytes, here the stored names:
93
+ // of two of one name, the later is extracted where the first was.
112
94
  const last = new Map()
113
95
  for (const [index, entry] of entries.entries()) {
114
96
  const record = records[index]
115
97
  if (decoder.decode(record.name) !== entry.storedName) throw new Error('unreachable: unzip lists entries out of the central directory\'s order')
116
98
  const here = `${where}: ${quote(entry.storedName)}`
117
99
  if (record.extra !== undefined) throw new DeptreeError(`${record.extra}, which Soldeer fails on`, here)
118
- // The zip crate reads a name not flagged UTF-8 as CP437.
119
100
  if (!(record.flags & UTF8) && record.name.some((byte) => byte >= 0x80)) throw new DeptreeError('a name not flagged UTF-8, which Soldeer reads as CP437, is not supported', here)
120
101
  last.set(entry.storedName, index)
121
102
  }
package/src/tarball.js CHANGED
@@ -1,36 +1,12 @@
1
- // A registry package's files, from its tarball: fetched through
2
- // @preventive/upstream, which reads a cache of its own and npm's before
3
- // the registry and holds what it gets to the integrity it is given, then
4
- // held to that integrity again here, since it is the lockfile's; gunzipped
5
- // and unpacked by @preventive/archive, with every rule of a name that
6
- // holds; and read into files the way pnpm reads them out of a tarball
7
- // (@pnpm/store.cafs): the first segment of each name dropped, whatever it
8
- // is, only files kept, as ones not executable or executable by anyone.
9
- //
10
- // Here it is held to more than pnpm holds it to, to what npm packs: a
11
- // gzipped tarball, every file under one directory, no link of either kind
12
- // or device, which pnpm would pass over or refuse, and no name twice as
13
- // two different files, of which pnpm would keep the later. It has to have
14
- // a package.json, for exactly the name and version the lockfile says, and
15
- // that package.json has to agree with what the lockfile recorded of the
16
- // package's: its os, cpu and libc, whether it has bins, what it bundles.
17
- // And every dependency it asks for, read through pnpm's read-package hook
18
- // as pnpm reads it (hook.js), has to be among each of its snapshots', bundled
19
- // or optional ones aside: a lockfile that leaves one out would leave the
20
- // package to find it wherever it is hoisted, if anywhere. A registry whose
21
- // metadata says other than its tarball does is caught at the same time.
22
- //
23
- // A package is fetched and read once however many snapshots it has, one
24
- // for each set of peers it is resolved with.
1
+ // A registry tarball, fetched through @preventive/upstream, which checks the
2
+ // integrity it is given, and checked again here, as that is the lockfile's.
25
3
 
26
4
  import { decompress } from '@preventive/archive/compression.js'
27
5
  import { unpack } from '@preventive/archive/tar.js'
28
- import { normalize } from '@preventive/vfs/path.js'
29
- import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
30
6
  import { getTarball } from '@preventive/upstream/npm.js'
31
7
  import { DeptreeError, quote } from './error.js'
32
- import { localOf } from './pnpm/overrides.js'
33
8
  import { matchesIntegrity } from './hash.js'
9
+ import { fold } from './mount.js'
34
10
 
35
11
  // What a tarball may unpack to, as upstream bounds what it downloads.
36
12
  const MAX_BYTES = 512 * 1024 * 1024
@@ -39,134 +15,54 @@ export const REGISTRY = 'https://registry.npmjs.org/'
39
15
  // The registry's own URL for a version's tarball, as npm and pnpm spell it.
40
16
  export const tarballUrl = (name, version) => `${REGISTRY}${name}/-/${name.split('/').at(-1)}-${version}.tgz`
41
17
 
42
- // pnpm's name for an entry: past the first `/` of the name as stored,
43
- // folded where it has a `./` in it, a `//` made one.
44
- function nameOf(stored) {
45
- const slash = stored.indexOf('/')
46
- let name = slash === -1 ? stored : stored.slice(slash + 1)
47
- if (name.includes('./')) name = normalize(`/${name}`).slice(1)
48
- return name.replaceAll('//', '/')
49
- }
50
-
51
- export const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
52
- const sameFile = (a, b) => a.mode === b.mode && sameBytes(a.data, b.data)
18
+ // A name and a version that URL holds as they are: ASCII a URL takes
19
+ // unescaped, no part of the name `.` or `..`, and nothing that would end the
20
+ // path. The lockfile reader holds both to more; the URL fetched is held to
21
+ // this whatever reached here.
22
+ const NAME = /^(?:@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*$/u
23
+ const VERSION = /^[\dA-Za-z][\dA-Za-z.+-]*$/u
53
24
 
54
- // A Map of each file's path in the package to its bytes and mode. pnpm 12
55
- // takes a backslash in a name for a separator, which is not supported.
56
- function filesOf(entries, where, major) {
57
- const files = new Map()
58
- const tops = new Set()
59
- for (const entry of entries) {
60
- if (major >= 12 && entry.storedName.includes('\\')) throw new DeptreeError(`${quote(entry.storedName)} has a backslash, which pnpm 12 takes for a separator, and that is not supported`, where)
61
- if (entry.type === 'directory') continue
62
- if (entry.type !== 'file') throw new DeptreeError(`${quote(entry.name)} is a ${entry.type}, which is not supported`, where)
63
- tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
64
- if (tops.size > 1 || tops.has('')) throw new DeptreeError('the tarball has files under more than one directory, or at its top', where)
65
- const name = nameOf(entry.storedName)
66
- if (name === '' || name.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
67
- throw new DeptreeError(`${quote(entry.storedName)} names no file in the package`, where)
68
- }
69
- const file = { data: entry.data, mode: (entry.mode & 0o111) === 0 ? 0o644 : 0o755 }
70
- const earlier = files.get(name)
71
- if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(name)} is in the tarball twice`, where)
72
- files.set(name, file)
73
- }
74
- return files
75
- }
76
-
77
- const decoder = new TextDecoder('utf-8', { fatal: true })
78
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
79
- const names = (value) => Object.keys(value ?? {})
80
-
81
- // Whether a package.json has bins, as the lockfile's hasBin records it:
82
- // by a `bin` that names any, or with none, by a directories.bin. Where
83
- // `bin` is there and names none, and there is a directories.bin, pnpm
84
- // resolves it as having none and pnpm 11 rewrites a snapshot as having
85
- // some, so that is undefined: bins are linked as the lockfile has it.
86
- // pnpm 12 records it for a `bin` that is a string or object not empty, or
87
- // a directories.bin that is a string not empty.
88
- function hasBin({ bin, directories }, major) {
89
- if (major >= 12) {
90
- const named = typeof bin === 'string' ? bin !== '' : bin !== null && typeof bin === 'object' && !Array.isArray(bin) && Object.keys(bin).length > 0
91
- return named || (directories !== null && typeof directories === 'object' && !Array.isArray(directories) && typeof directories.bin === 'string' && directories.bin !== '')
92
- }
93
- if (bin === undefined || bin === null) return Boolean(directories?.bin)
94
- if (bin && Object.keys(bin).length > 0) return true
95
- return directories?.bin ? undefined : false
25
+ function checkId(name, version, where) {
26
+ if (!NAME.test(name) || !VERSION.test(version)) throw new DeptreeError(`${quote(`${name}@${version}`)} is no package the registry's URL names as it is`, where)
96
27
  }
97
28
 
98
- function readManifest(files, pkg, where) {
99
- const file = files.get('package.json')
100
- if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
101
- let manifest
102
- try {
103
- manifest = JSON.parse(decoder.decode(file.data))
104
- } catch {
105
- throw new DeptreeError('package.json is not JSON', where)
106
- }
107
- if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('package.json is not an object', where)
108
- if (manifest.name !== pkg.name || manifest.version !== pkg.version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
109
- return manifest
29
+ // The registry's own tarball, by its sha512 alone, as fetchTarball takes it.
30
+ export function ownTarball(url, name, version, integrity, where) {
31
+ checkId(name, version, where)
32
+ const expected = tarballUrl(name, version)
33
+ if (url !== expected) throw new DeptreeError(`only the registry's own tarball of ${name}@${version}, ${expected}, is supported`, where)
34
+ const sha512 = integrity?.split(' ').find((part) => part.startsWith('sha512-'))
35
+ if (sha512 === undefined) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
36
+ return { name, version, integrity: sha512 }
110
37
  }
111
38
 
112
- // What the lockfile recorded of the package against the package.json.
113
- export function checkManifest(manifest, pkg, where, major) {
114
- for (const field of ['os', 'cpu', 'libc']) {
115
- if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
116
- }
117
- const has = hasBin(manifest, major)
118
- if (has !== undefined && has !== pkg.hasBin) throw new DeptreeError(`package.json ${pkg.hasBin ? 'has no bins, and the lockfile says it has' : 'has bins, and the lockfile says it has none'}`, where)
119
- if (!same(listed(bundledOf(manifest)), listed(pkg.bundledDependencies))) throw new DeptreeError('package.json bundles other than the lockfile says', where)
120
- }
39
+ // yarn's mirror of npm's registry serves the same tarballs at the same paths.
40
+ const YARNPKG = 'https://registry.yarnpkg.com/'
41
+ export const fromMirror = (url) => (url.startsWith(YARNPKG) ? `${REGISTRY}${url.slice(YARNPKG.length)}` : url)
121
42
 
122
- const bundledOf = (manifest) => manifest.bundleDependencies ?? manifest.bundledDependencies
43
+ const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
44
+ // The name of a package's own node_modules, where npm and yarn install its
45
+ // dependencies, in any case: macOS takes `Node_Modules` for it.
46
+ export const isModules = (name) => fold(name) === 'node_modules'
123
47
 
124
- // Bundled dependencies as the lockfile records them, where pnpm 10 writes
125
- // an empty list and pnpm 11 leaves it out.
126
- const listed = (bundled) => (Array.isArray(bundled) && bundled.length === 0 ? undefined : bundled)
48
+ export const sameFile = (a, b) => a.mode === b.mode && sameBytes(a.data, b.data)
127
49
 
128
- // A snapshot's dependencies against the package.json of its package, as
129
- // fetchPackage read it and `read` as hook.js's hook has it. One the
130
- // package.json, as overridden, names a directory for is linked there,
131
- // from the lockfile's directory, as pnpm writes it.
132
- export function checkDependencies(manifest, read, pkg, where) {
133
- const bundled = bundledOf(manifest)
134
- const given = new Set([...names(pkg.dependencies), ...names(pkg.optionalDependencies)])
135
- for (const name of [...names(read.dependencies), ...names(read.optionalDependencies)]) {
136
- if (bundled === true || (Array.isArray(bundled) && bundled.includes(name)) || given.has(name)) continue
137
- throw new DeptreeError(`package.json asks for ${quote(name)}, which the lockfile does not give it`, where)
138
- }
139
- for (const [name, spec] of [...Object.entries(read.dependencies ?? {}), ...Object.entries(read.optionalDependencies ?? {})]) {
140
- const target = pkg.dependencies[name] ?? pkg.optionalDependencies[name]
141
- if (target === undefined) continue
142
- const local = localOf(spec, `${where}: package.json`)
143
- if (local === undefined || target === `link:${local.dir}` || (local.protocol === 'file:' && packageKeyOf(target).endsWith(`@file:${local.dir}`))) continue
144
- throw new DeptreeError(`the lockfile gives it ${quote(name)} as ${quote(target)}, and its package.json, overridden, names ${quote(local.dir)}`, where)
145
- }
146
- // A peer resolved is filed as optional where it is optional; pnpm's
147
- // compatibility database adds peers to a few packages, which the
148
- // lockfile records among their peers and the package.json does not.
149
- const optional = new Set([...names(read.optionalDependencies), ...names(manifest.peerDependencies), ...names(manifest.peerDependenciesMeta), ...names(pkg.peerDependencies), ...names(pkg.peerDependenciesMeta)])
150
- for (const name of names(pkg.optionalDependencies)) {
151
- if (!optional.has(name)) throw new DeptreeError(`the lockfile gives it ${quote(name)} as optional, which its package.json does not`, where)
50
+ // Adds to `dirs` each one `files` are in, refusing one that is a file too.
51
+ export function withDirs(files, where, dirs = new Set()) {
52
+ for (const path of files.keys()) {
53
+ const segments = path.split('/')
54
+ for (let i = 1; i < segments.length; i++) dirs.add(segments.slice(0, i).join('/'))
152
55
  }
56
+ 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)
57
+ return { files, dirs }
153
58
  }
154
59
 
155
- // A version's tarball from the registry, through @preventive/upstream, held
156
- // to `integrity` and to be gzipped: its bytes, and its entries unpacked.
157
60
  export async function fetchTarball(name, version, integrity, where) {
61
+ checkId(name, version, where)
62
+ if (!/^sha512-[\d+/A-Za-z]{86}==$/u.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
158
63
  const bytes = await getTarball(name, version, { tarball: tarballUrl(name, version), integrity })
159
64
  if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
160
65
  if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
161
- return { bytes, entries: unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES })) }
162
- }
163
-
164
- // A package's files, and its package.json as parsed; the package has to be
165
- // from the registry.
166
- export async function fetchPackage(pkg, where, major) {
167
- const { entries } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where)
168
- const files = filesOf(entries, where, major)
169
- const manifest = readManifest(files, pkg, where)
170
- checkManifest(manifest, pkg, where, major)
171
- return { files, manifest }
66
+ const tar = await decompress(bytes, 'gzip', { limit: MAX_BYTES })
67
+ return { bytes, entries: unpack(tar), inflated: tar.length }
172
68
  }
package/src/yarn1/bins.js CHANGED
@@ -1,19 +1,12 @@
1
- // Where yarn 1 fails as it links bins (package-linker.js): of each package
2
- // in the tree, each dependency's bins are linked from its copy nearest the
3
- // package's node_modules, as node would find it from there, and yarn fails
4
- // where there is none. What linking does to the tree, each target made
5
- // executable, yarn's fetcher has done already (package.js). A dependency
6
- // with no copy of its own reference in the tree, as one deduplicated into
7
- // another's has none, links none, as yarn has no location for it.
1
+ // Where yarn 1 fails as it links bins (package-linker.js). The one change
2
+ // linking makes to the tree, each target made executable, package.js has
3
+ // made. A dependency deduplicated into another's reference links no bins.
8
4
 
9
5
  import { dirname, join } from '@preventive/vfs/path.js'
10
6
  import { DeptreeError, quote } from '../error.js'
11
- import { binsOf } from './package.js'
12
7
 
13
- // Whether node finds the package at `loc` by its name from `dir`, a
14
- // directory at a time up from it, as yarn's
15
- // findNearestInstalledVersionOfPackage looks. Paths are from the
16
- // lockfile's directory, `.` it.
8
+ // As yarn's findNearestInstalledVersionOfPackage looks; paths are from the
9
+ // lockfile's directory, `.`.
17
10
  function finds(name, loc, dir) {
18
11
  for (;; dir = dirname(dir)) {
19
12
  if (join(dir, name) === loc || join(dir, `node_modules/${name}`) === loc) return true
@@ -21,17 +14,14 @@ function finds(name, loc, dir) {
21
14
  }
22
15
  }
23
16
 
24
- // `placed` the flat tree, tree.js's; `patterns` resolve.js's; `fetched`
25
- // each registry package's files, and `manifestOf` its package.json, as
26
- // yarn has them; `locations` each reference's copies, where they really
27
- // are, and `realOf` where a path in the tree really is.
28
- export function checkBinLinks({ placed, patterns, fetched, manifestOf, locations, realOf }) {
17
+ export function checkBinLinks({ placed, patterns, locations, realOf }) {
29
18
  for (const { loc, info } of placed) {
30
19
  const binLoc = `${loc}/node_modules`
20
+ const realBinLoc = realOf(binLoc)
31
21
  for (const pattern of info.ref.dependencies) {
32
22
  const dep = patterns.get(pattern)
33
- if (dep.kind !== 'registry' || !locations.has(dep) || binsOf(manifestOf.get(dep), fetched.get(dep)).size === 0) continue
34
- const found = locations.get(dep).some((at) => finds(dep.name, at, binLoc) || finds(dep.name, at, realOf(binLoc)))
23
+ if (dep.kind !== 'registry' || !locations.has(dep) || !dep.hasBins) continue
24
+ const found = locations.get(dep).some((at) => finds(dep.name, at, binLoc) || finds(dep.name, at, realBinLoc))
35
25
  if (!found) throw new DeptreeError(`yarn finds no copy of ${quote(dep.name)} to link the bins of`, quote(loc))
36
26
  }
37
27
  }
@@ -1,12 +1,5 @@
1
- // yarn 1's package-compatibility.js: a package whose os, cpu or engines
2
- // the host does not take is left out where it is optional, and fails the
3
- // install otherwise; so does the root project, checked as yarn checks it
4
- // before anything is resolved. Engines are checked against the Node yarn
5
- // runs on and yarn itself; any other engine Node reports a version of in
6
- // process.versions — v8, uv, openssl and the rest — would be checked
7
- // against the Node that runs yarn, which is not known here, and is
8
- // refused. One yarn knows of no version for is passed over, as yarn
9
- // passes over it.
1
+ // yarn 1's package-compatibility.js, engines checked against host.node and
2
+ // host.yarn; one yarn knows no version of is passed over, as yarn does.
10
3
 
11
4
  import { compareVersions, major, satisfies, valid } from '@preventive/upstream/semver.js'
12
5
  import { DeptreeError, quote } from '../error.js'
@@ -52,35 +45,23 @@ function testEngine(name, range, versions) {
52
45
  return false
53
46
  }
54
47
 
55
- // Why the host does not take `manifest`, or undefined where it does; its
56
- // os and cpu not checked with ignorePlatform, and its engines not with
57
- // ignoreEngines. A manifest's engines may be a list of `name range`
58
- // strings, which yarn reads into a mapping first.
48
+ // engines may be a list of `name range` strings, which yarn reads as a map.
59
49
  export function incompatibility(manifest, host, where, { ignoreEngines, ignorePlatform }) {
60
50
  const { os, cpu } = manifest
61
51
  let { engines } = manifest
62
52
  if (!ignorePlatform && Array.isArray(os) && os.length > 0 && !isValid(os, host.os)) return `its os, ${JSON.stringify(os)}, does not take ${quote(host.os)}`
63
53
  if (!ignorePlatform && Array.isArray(cpu) && cpu.length > 0 && !isValid(cpu, host.cpu)) return `its cpu, ${JSON.stringify(cpu)}, does not take ${quote(host.cpu)}`
64
54
  if (ignoreEngines) return undefined
65
- if (Array.isArray(engines)) {
66
- const read = {}
67
- for (const item of engines) {
68
- if (typeof item !== 'string') continue
69
- const [name, ...rest] = item.trim().split(/ +/gu)
70
- read[name] = rest.join(' ')
71
- }
72
- engines = read
73
- }
55
+ if (Array.isArray(engines)) engines = Object.fromEntries(engines.filter((item) => typeof item === 'string').map((item) => item.trim().split(/ +/gu)).map(([name, ...rest]) => [name, rest.join(' ')]))
74
56
  if (engines === null || typeof engines !== 'object') return undefined
75
57
  const versions = { node: host.node, yarn: host.yarn }
76
58
  for (let [name, range] of Object.entries(engines)) {
77
59
  if (name === 'iojs') name = 'node'
78
- if (typeof range !== 'string' && (Object.hasOwn(versions, name) || REPORTED.has(name))) throw new DeptreeError(`engines.${name} is not a string, which yarn fails on`, where)
79
- if (Object.hasOwn(versions, name)) {
80
- if (!testEngine(name, range, versions)) return `its engines.${name}, ${quote(String(range))}, does not take ${versions[name]}`
81
- } else if (REPORTED.has(name)) {
82
- throw new DeptreeError(`yarn checks engines.${name} against the Node it runs on, which is not known here`, where)
83
- }
60
+ const known = Object.hasOwn(versions, name)
61
+ if (!known && !REPORTED.has(name)) continue
62
+ if (typeof range !== 'string') throw new DeptreeError(`engines.${name} is not a string, which yarn fails on`, where)
63
+ if (!known) throw new DeptreeError(`yarn checks engines.${name} against the Node it runs on, which is not known here`, where)
64
+ if (!testEngine(name, range, versions)) return `its engines.${name}, ${quote(range)}, does not take ${versions[name]}`
84
65
  }
85
66
  return undefined
86
67
  }
@@ -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) {