@preventive/deptree 1.0.0-alpha.1 → 1.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +325 -0
  8. package/npm.js +7 -0
  9. package/package.json +92 -11
  10. package/pnpm.d.ts +401 -81
  11. package/pnpm.js +4 -9
  12. package/soldeer.d.ts +235 -0
  13. package/soldeer.js +6 -0
  14. package/src/cargo/crate.js +183 -0
  15. package/src/cargo/inputs.js +81 -0
  16. package/src/cargo/members.js +90 -0
  17. package/src/cargo/registry.js +65 -0
  18. package/src/cargo/tree.js +125 -0
  19. package/src/cargo/workspace.js +177 -0
  20. package/src/concurrent.js +32 -0
  21. package/src/error.js +8 -10
  22. package/src/glob.js +55 -0
  23. package/src/hash.js +51 -16
  24. package/src/manifest.js +52 -0
  25. package/src/matcher.js +60 -10
  26. package/src/mount.js +124 -42
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +96 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +202 -322
  41. package/src/pnpm/checks.js +8 -35
  42. package/src/pnpm/commands.js +230 -0
  43. package/src/pnpm/filename.js +19 -16
  44. package/src/pnpm/frozen.js +29 -73
  45. package/src/pnpm/gitignore.js +138 -0
  46. package/src/pnpm/glob.js +65 -0
  47. package/src/pnpm/graph.js +26 -34
  48. package/src/pnpm/hoist.js +96 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +26 -31
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +123 -124
  53. package/src/pnpm/local.js +95 -40
  54. package/src/pnpm/minimatch.js +319 -0
  55. package/src/pnpm/nm-hoist-graph.js +299 -0
  56. package/src/pnpm/nm-hoist.js +149 -0
  57. package/src/pnpm/npm-packlist.js +217 -0
  58. package/src/pnpm/overrides.js +11 -51
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +176 -81
  61. package/src/pnpm/patches.js +18 -25
  62. package/src/pnpm/projects.js +132 -89
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +74 -95
  65. package/src/pnpm/tree.js +216 -237
  66. package/src/pnpm/uptodate.js +16 -28
  67. package/src/pnpm/workspace.js +152 -126
  68. package/src/project.js +56 -0
  69. package/src/soldeer/config.js +63 -0
  70. package/src/soldeer/git.js +52 -0
  71. package/src/soldeer/inputs.js +30 -0
  72. package/src/soldeer/tree.js +83 -0
  73. package/src/soldeer/zip.js +121 -0
  74. package/src/tarball.js +123 -131
  75. package/src/yarn1/bins.js +28 -0
  76. package/src/yarn1/compat.js +67 -0
  77. package/src/yarn1/hoist.js +249 -0
  78. package/src/yarn1/inputs.js +83 -0
  79. package/src/yarn1/manifest.js +64 -0
  80. package/src/yarn1/package.js +206 -0
  81. package/src/yarn1/peers.js +51 -0
  82. package/src/yarn1/requests.js +74 -0
  83. package/src/yarn1/resolve.js +289 -0
  84. package/src/yarn1/settings.js +95 -0
  85. package/src/yarn1/tree.js +219 -0
  86. package/yarn1.d.ts +368 -0
  87. package/yarn1.js +7 -0
  88. package/src/pnpm/npmrc.js +0 -31
  89. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,83 @@
1
+ // The dependencies folder `soldeer install` makes from a soldeer.lock.
2
+
3
+ import { utf8fromStringLoose } from '@exodus/bytes/utf8.js'
4
+ import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
5
+ import { getZip } from '@preventive/upstream/soldeer.js'
6
+ import { Vfs } from '@preventive/vfs'
7
+ import { eachConcurrently } from '../concurrent.js'
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { checkNoDir, fold, makeDirs, mount, writeFiles } from '../mount.js'
10
+ import { configOf } from './config.js'
11
+ import { checkoutOf, githubRepoOf } from './git.js'
12
+ import { checkHost, inputsOf } from './inputs.js'
13
+ import { extractZip } from './zip.js'
14
+
15
+ // What the registry takes, as @preventive/upstream/soldeer.js checks a name
16
+ // and version, which Soldeer's sanitize_filename leaves as they are on Unix.
17
+ const NAME = /^(?=.{3,100}$)[@\da-z][\da-z-]*[\da-z]$/u
18
+ const VERSION = /^(?=.{1,128}$)[\dA-Za-z][\w.+-]*$/u
19
+ // A folder sanitize_filename leaves as it is on Unix: none of the characters
20
+ // it replaces, and at most 255 bytes, past which it cuts the name short.
21
+ const isKept = (folder) => !/[/?<>\\:*|"\p{Cc}]/u.test(folder) && utf8fromStringLoose(folder).length <= 255
22
+
23
+ const GITHUB = 'github must be a GitHub client from createClient, which a git dependency is fetched through'
24
+
25
+ const checkNoDependencies = checkNoDir('dependencies', 'a dependencies folder')
26
+
27
+ const about = (name) => `dependencies[${quote(name)}]`
28
+
29
+ function checkDependency({ type, name, version, git, folder }, config) {
30
+ const where = about(name)
31
+ if (type === 'private') throw new DeptreeError('a private dependency, which the registry hands out to those signed in alone, is not supported', where)
32
+ if (type === 'git') {
33
+ if (githubRepoOf(git) === undefined) throw new DeptreeError(`a git dependency from ${quote(git)}, not a GitHub repository over https or ssh, is not supported`, where)
34
+ if (!isKept(folder)) throw new DeptreeError(`its folder, ${quote(folder)}, is one Soldeer names otherwise, which is not supported`, where)
35
+ return
36
+ }
37
+ if (config.dependencies?.[name]?.url !== undefined) throw new DeptreeError('a dependency from a URL of its own, rather than the registry, is not supported', where)
38
+ if (!NAME.test(name)) throw new DeptreeError('a name the registry does not take', where)
39
+ if (!VERSION.test(version)) throw new DeptreeError(`${quote(version)} is a version the registry does not take`, where)
40
+ }
41
+
42
+ function dependenciesOf(lock, config, folded) {
43
+ const dependencies = Object.values(lock.dependencies).map((dependency) => ({ ...dependency, folder: `${dependency.name}-${dependency.version}` }))
44
+ for (const dependency of dependencies) checkDependency(dependency, config)
45
+ const key = (folder) => (folded ? fold(folder) : folder)
46
+ const folders = new Set(dependencies.map(({ folder }) => key(folder)))
47
+ for (const { type, name, folder } of dependencies) {
48
+ if (type === 'http' && folders.has(key(`${folder}.zip`))) throw new DeptreeError(`its zip is downloaded as ${quote(`${folder}.zip`)}, a folder Soldeer installs another dependency in`, about(name))
49
+ }
50
+ return dependencies
51
+ }
52
+
53
+ async function fetchAll(dependencies, github) {
54
+ const extracted = new Map()
55
+ await eachConcurrently(dependencies, async ({ type, name, version, checksum, git, rev, folder }) => {
56
+ const where = about(name)
57
+ extracted.set(folder, type === 'git' ? await checkoutOf(github, githubRepoOf(git), rev, where) : await extractZip(await getZip(name, version, checksum), checksum, where))
58
+ }, ({ name }) => about(name))
59
+ return extracted
60
+ }
61
+
62
+ export async function buildSoldeerTree(options) {
63
+ const { host: given, vfs: into, github } = options ?? {}
64
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
65
+ if (github !== undefined && typeof github?.getRepoTarball !== 'function') throw new TypeError(GITHUB)
66
+ const inputs = inputsOf(options ?? {})
67
+ const folded = checkHost(given).os === 'darwin'
68
+ // Refused before anything is fetched; mount checks again.
69
+ if (into !== undefined) checkNoDependencies(into, folded)
70
+ const config = configOf(inputs)
71
+ const dependencies = dependenciesOf(parseSoldeerLockfile(inputs.lockfile, { config }), config, folded)
72
+ if (github === undefined && dependencies.some(({ type }) => type === 'git')) throw new TypeError(GITHUB)
73
+ const extracted = await fetchAll(dependencies, github)
74
+ const vfs = new Vfs()
75
+ makeDirs(vfs, 'dependencies')
76
+ const stats = { dependencies: dependencies.length, files: 0, bytes: 0, links: 0 }
77
+ // In the lockfile's order, whatever order the fetches finished in.
78
+ for (const { folder } of dependencies) {
79
+ writeFiles(vfs, `dependencies/${folder}`, extracted.get(folder), stats)
80
+ }
81
+ const installed = dependencies.map(({ type, name, version, checksum, git, rev, folder }) => ({ path: `dependencies/${folder}`, name, version, ...(type === 'git' ? { git, rev, commit: rev } : { checksum }) }))
82
+ return { vfs: mount(vfs, into, folded, checkNoDependencies), stats, installed }
83
+ }
@@ -0,0 +1,121 @@
1
+ // A registry zip as Soldeer 0.12 extracts it (download.rs's
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.
6
+
7
+ import { utf8fromStringLoose, utf8toStringLoose } from '@exodus/bytes/utf8.js'
8
+ import { ArchiveError, unzip } from '@preventive/archive/zip.js'
9
+ import { DeptreeError, quote } from '../error.js'
10
+ import { bytesSha256Hex } from '../hash.js'
11
+ import { MAX_BYTES } from '../tarball.js'
12
+
13
+ const END = 0x06054b50
14
+ const CENTRAL = 0x02014b50
15
+ const UTF8 = 0x0800
16
+ const S_IFLNK = 0o120000
17
+ const [NTFS, TIMESTAMP, UNICODE_COMMENT, AES] = [0x000a, 0x5455, 0x6375, 0x9901]
18
+
19
+ // As the archive reader decodes a name: a leading U+FEFF is part of it.
20
+
21
+ const ones = (byte) => [...byte.toString(2)].filter((bit) => bit === '1').length
22
+
23
+ // Why the zip crate would fail on an entry's extra fields, or undefined; an
24
+ // AES or a Unicode comment field is refused here.
25
+ function extraRefusal(view, at, length) {
26
+ for (let pos = at; pos < at + length;) {
27
+ const id = view.getUint16(pos, true)
28
+ const size = view.getUint16(pos + 2, true)
29
+ const body = pos + 4
30
+ if (id === NTFS && (size !== 32 || view.getUint16(body + 4, true) !== 1 || view.getUint16(body + 6, true) !== 24)) return 'an NTFS extra field the zip crate does not read'
31
+ if (id === TIMESTAMP && (size === 0 || (size !== 5 && size !== 1 + 4 * ones(view.getUint8(body))))) return 'an extended timestamp the zip crate does not read'
32
+ if (id === AES) return 'an AES extra field, which has the zip crate decrypt the entry'
33
+ if (id === UNICODE_COMMENT) return 'a Unicode comment extra field, which the zip crate checks'
34
+ pos = body + size
35
+ }
36
+ return undefined
37
+ }
38
+
39
+ // What the zip crate reads of each entry that unzip does not hand out. unzip
40
+ // has checked the layout whole, so each record is where it says.
41
+ function centralRecords(bytes) {
42
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
43
+ let end = bytes.length - 22
44
+ while (view.getUint32(end, true) !== END || end + 22 + view.getUint16(end + 20, true) !== bytes.length) end--
45
+ const records = []
46
+ let at = view.getUint32(end + 16, true)
47
+ for (let i = 0; i < view.getUint16(end + 10, true); i++) {
48
+ if (view.getUint32(at, true) !== CENTRAL) throw new Error('unreachable: a central record where unzip found none')
49
+ const [nameLength, extraLength, commentLength] = [at + 28, at + 30, at + 32].map((field) => view.getUint16(field, true))
50
+ records.push({
51
+ system: view.getUint8(at + 5),
52
+ flags: view.getUint16(at + 8, true),
53
+ attributes: view.getUint32(at + 38, true),
54
+ name: bytes.subarray(at + 46, at + 46 + nameLength),
55
+ extra: extraRefusal(view, at + 46 + nameLength, extraLength),
56
+ })
57
+ at += 46 + nameLength + extraLength + commentLength
58
+ }
59
+ return records
60
+ }
61
+
62
+ // The zip crate's ZipFileData::unix_mode; system 0 is MS-DOS, and 3 Unix.
63
+ function unixMode({ system, attributes }) {
64
+ if (attributes === 0) return undefined
65
+ const upper = attributes >>> 16
66
+ if (upper !== 0) return upper
67
+ if (system === 3) return 0
68
+ if (system !== 0) return undefined
69
+ const mode = attributes & 0x10 ? 0o040775 : 0o100664
70
+ return attributes & 0x01 ? mode & ~0o222 : mode
71
+ }
72
+
73
+ // What str::trim_end_matches(['.', ' ']) and eq_ignore_ascii_case make of
74
+ // a component Soldeer holds to `.git`; git's verify_path refuses to check
75
+ // one out, with core.protectNTFS, on by default.
76
+ export const isGit = (component) => component.replace(/[. ]+$/u, '').replace(/[A-Z]/gu, (char) => char.toLowerCase()) === '.git'
77
+
78
+ // getZip has held the zip to its checksum; it is held to it again where it
79
+ // is unpacked.
80
+ export async function extractZip(bytes, checksum, where) {
81
+ if (await bytesSha256Hex(bytes) !== checksum) throw new DeptreeError(`its zip's sha256 is not ${checksum}`, where)
82
+ let entries
83
+ try {
84
+ entries = await unzip(bytes, { limit: MAX_BYTES })
85
+ } catch (error) {
86
+ if (error instanceof ArchiveError) throw new DeptreeError(`its zip cannot be read: ${error.message}`, where, { cause: error })
87
+ throw error
88
+ }
89
+ const records = centralRecords(bytes)
90
+ // The zip crate keys entries by their names' bytes, here the stored names:
91
+ // of two of one name, the later is extracted where the first was.
92
+ const last = new Map()
93
+ for (const [index, entry] of entries.entries()) {
94
+ const record = records[index]
95
+ if (utf8toStringLoose(record.name) !== entry.storedName) throw new Error('unreachable: unzip lists entries out of the central directory\'s order')
96
+ const here = `${where}: ${quote(entry.storedName)}`
97
+ if (record.extra !== undefined) throw new DeptreeError(`${record.extra}, which Soldeer fails on`, here)
98
+ 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)
99
+ last.set(entry.storedName, index)
100
+ }
101
+ const dirs = new Set()
102
+ const files = new Map()
103
+ for (const index of last.values()) {
104
+ const entry = entries[index]
105
+ if (entry.name === '.') continue
106
+ const components = entry.name.split('/')
107
+ if (components.some((component) => component.includes(':'))) throw new DeptreeError('a name with a ":" in it, which Soldeer fails on', `${where}: ${quote(entry.storedName)}`)
108
+ if (components.some(isGit)) continue
109
+ for (let i = 1; i < components.length; i++) dirs.add(components.slice(0, i).join('/'))
110
+ if (entry.type === 'directory') {
111
+ dirs.add(entry.name)
112
+ continue
113
+ }
114
+ const mode = unixMode(records[index])
115
+ const data = entry.type === 'symlink' ? utf8fromStringLoose(entry.linkname) : entry.data
116
+ // A file written again keeps its mode where the zip crate reads none.
117
+ const kept = mode === undefined || (mode & S_IFLNK) === S_IFLNK ? files.get(entry.name)?.mode ?? 0o644 : mode & 0o777 & ~0o022
118
+ files.set(entry.name, { data, mode: kept })
119
+ }
120
+ return { dirs, files }
121
+ }
package/src/tarball.js CHANGED
@@ -1,158 +1,150 @@
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.
25
-
26
- import { decompress } from '@preventive/archive/compression.js'
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;
3
+ // and its version's document from the registry, where asked for, for what
4
+ // it says of where the package comes from.
5
+
6
+ import { CompressionError, decompress } from '@preventive/archive/compression.js'
27
7
  import { unpack } from '@preventive/archive/tar.js'
28
- import { normalize } from '@preventive/vfs/path.js'
29
- import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
30
- import { getTarball } from '@preventive/upstream/npm.js'
8
+ import { getMeta, getTarball } from '@preventive/upstream/npm.js'
9
+ import { settled } from './concurrent.js'
31
10
  import { DeptreeError, quote } from './error.js'
32
- import { localOf } from './pnpm/overrides.js'
33
11
  import { matchesIntegrity } from './hash.js'
12
+ import { fold } from './mount.js'
13
+ import { decodeUtf8 } from './project.js'
34
14
 
35
- // What a tarball may unpack to, as upstream bounds what it downloads.
36
- const MAX_BYTES = 512 * 1024 * 1024
15
+ // What a tarball or a zip may unpack to, as upstream bounds what it
16
+ // downloads: the archive reader makes room for what entries declare.
17
+ export const MAX_BYTES = 512 * 1024 * 1024
37
18
  export const REGISTRY = 'https://registry.npmjs.org/'
38
19
 
39
20
  // The registry's own URL for a version's tarball, as npm and pnpm spell it.
40
21
  export const tarballUrl = (name, version) => `${REGISTRY}${name}/-/${name.split('/').at(-1)}-${version}.tgz`
41
22
 
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('//', '/')
23
+ // A name and a version that URL holds as they are: ASCII a URL takes
24
+ // unescaped, no part of the name `.` or `..`, and nothing that would end the
25
+ // path. The lockfile reader holds both to more; the URL fetched is held to
26
+ // this whatever reached here.
27
+ const NAME = /^(?:@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*$/u
28
+ const VERSION = /^[\dA-Za-z][\dA-Za-z.+-]*$/u
29
+
30
+ function checkId(name, version, where) {
31
+ 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)
49
32
  }
50
33
 
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)
53
-
54
- // A Map of each file's path in the package to its bytes and mode.
55
- function filesOf(entries, where) {
56
- const files = new Map()
57
- const tops = new Set()
58
- for (const entry of entries) {
59
- if (entry.type === 'directory') continue
60
- if (entry.type !== 'file') throw new DeptreeError(`${quote(entry.name)} is a ${entry.type}, which is not supported`, where)
61
- tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
62
- if (tops.size > 1 || tops.has('')) throw new DeptreeError('the tarball has files under more than one directory, or at its top', where)
63
- const name = nameOf(entry.storedName)
64
- if (name === '' || name.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
65
- throw new DeptreeError(`${quote(entry.storedName)} names no file in the package`, where)
66
- }
67
- const file = { data: entry.data, mode: (entry.mode & 0o111) === 0 ? 0o644 : 0o755 }
68
- const earlier = files.get(name)
69
- if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(name)} is in the tarball twice`, where)
70
- files.set(name, file)
71
- }
72
- return files
34
+ // The registry's own tarball, by its sha512 alone, as fetchTarball takes it;
35
+ // where `unpinned`, with none where the lockfile records none, for
36
+ // fetchTarball to take the registry's.
37
+ export function ownTarball(url, name, version, integrity, where, unpinned = false) {
38
+ checkId(name, version, where)
39
+ const expected = tarballUrl(name, version)
40
+ if (url !== expected) throw new DeptreeError(`only the registry's own tarball of ${name}@${version}, ${expected}, is supported`, where)
41
+ const sha512 = integrity?.split(' ').find((part) => part.startsWith('sha512-'))
42
+ if (sha512 === undefined && !(unpinned && integrity === undefined)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
43
+ return { name, version, integrity: sha512 }
73
44
  }
74
45
 
75
- const decoder = new TextDecoder('utf-8', { fatal: true })
76
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
77
- const names = (value) => Object.keys(value ?? {})
78
-
79
- // Whether a package.json has bins, as the lockfile's hasBin records it:
80
- // by a `bin` that names any, or with none, by a directories.bin. Where
81
- // `bin` is there and names none, and there is a directories.bin, pnpm
82
- // resolves it as having none and pnpm 11 rewrites a snapshot as having
83
- // some, so that is undefined: bins are linked as the lockfile has it.
84
- function hasBin({ bin, directories }) {
85
- if (bin === undefined || bin === null) return Boolean(directories?.bin)
86
- if (bin && Object.keys(bin).length > 0) return true
87
- return directories?.bin ? undefined : false
46
+ // yarn's mirror of npm's registry serves the same tarballs at the same paths.
47
+ const YARNPKG = 'https://registry.yarnpkg.com/'
48
+ export const fromMirror = (url) => (url.startsWith(YARNPKG) ? `${REGISTRY}${url.slice(YARNPKG.length)}` : url)
49
+
50
+ // The name of a package's own node_modules, where npm and yarn install its
51
+ // dependencies, in any case: macOS takes `Node_Modules` for it.
52
+ export const isModules = (name) => fold(name) === 'node_modules'
53
+
54
+ export const sameFile = (a, b) => a.mode === b.mode && a.data.length === b.data.length && a.data.every((byte, i) => byte === b.data[i])
55
+
56
+ // Where a file's first line is a `#!` one ending in a CRLF within its first
57
+ // 2048 bytes, as bin-links' fixBin tells it, the index of its LF; else -1.
58
+ export function crlfShebang(data) {
59
+ if (data[0] !== 0x23 || data[1] !== 0x21) return -1
60
+ const newline = data.subarray(0, 2048).indexOf(0x0a)
61
+ return newline >= 4 && data[newline - 1] === 0x0d ? newline : -1
88
62
  }
89
63
 
90
- function readManifest(files, pkg, where) {
91
- const file = files.get('package.json')
92
- if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
93
- let manifest
94
- try {
95
- manifest = JSON.parse(decoder.decode(file.data))
96
- } catch {
97
- throw new DeptreeError('package.json is not JSON', where)
98
- }
99
- if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('package.json is not an object', where)
100
- if (manifest.name !== pkg.name || manifest.version !== pkg.version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
101
- return manifest
64
+ // `data` less such a line's CR; the file is rewritten as UTF-8, else refused with `detail`.
65
+ export function fixShebang(data, detail, where) {
66
+ const newline = crlfShebang(data)
67
+ if (newline === -1) return data
68
+ decodeUtf8(data, detail, where)
69
+ const copy = new Uint8Array(data.length - 1)
70
+ copy.set(data.subarray(0, newline - 1))
71
+ copy.set(data.subarray(newline), newline - 1)
72
+ return copy
102
73
  }
103
74
 
104
- // What the lockfile recorded of the package against the package.json.
105
- export function checkManifest(manifest, pkg, where) {
106
- for (const field of ['os', 'cpu', 'libc']) {
107
- if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
75
+ // Adds to `dirs` each one `files` are in, refusing one that is a file too.
76
+ export function withDirs(files, where, dirs = new Set()) {
77
+ for (const path of files.keys()) {
78
+ const segments = path.split('/')
79
+ for (let i = 1; i < segments.length; i++) dirs.add(segments.slice(0, i).join('/'))
108
80
  }
109
- const has = hasBin(manifest)
110
- 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)
111
- if (!same(listed(bundledOf(manifest)), listed(pkg.bundledDependencies))) throw new DeptreeError('package.json bundles other than the lockfile says', where)
81
+ 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)
82
+ return { files, dirs }
112
83
  }
113
84
 
114
- const bundledOf = (manifest) => manifest.bundleDependencies ?? manifest.bundledDependencies
115
-
116
- // Bundled dependencies as the lockfile records them, where pnpm 10 writes
117
- // an empty list and pnpm 11 leaves it out.
118
- const listed = (bundled) => (Array.isArray(bundled) && bundled.length === 0 ? undefined : bundled)
119
-
120
- // A snapshot's dependencies against the package.json of its package, as
121
- // fetchPackage read it and `read` as hook.js's hook has it. One the
122
- // package.json, as overridden, names a directory for is linked there,
123
- // from the lockfile's directory, as pnpm writes it.
124
- export function checkDependencies(manifest, read, pkg, where) {
125
- const bundled = bundledOf(manifest)
126
- const given = new Set([...names(pkg.dependencies), ...names(pkg.optionalDependencies)])
127
- for (const name of [...names(read.dependencies), ...names(read.optionalDependencies)]) {
128
- if (bundled === true || (Array.isArray(bundled) && bundled.includes(name)) || given.has(name)) continue
129
- throw new DeptreeError(`package.json asks for ${quote(name)}, which the lockfile does not give it`, where)
130
- }
131
- for (const [name, spec] of [...Object.entries(read.dependencies ?? {}), ...Object.entries(read.optionalDependencies ?? {})]) {
132
- const target = pkg.dependencies[name] ?? pkg.optionalDependencies[name]
133
- if (target === undefined) continue
134
- const local = localOf(spec, `${where}: package.json`)
135
- if (local === undefined || target === `link:${local.dir}` || (local.protocol === 'file:' && packageKeyOf(target).endsWith(`@file:${local.dir}`))) continue
136
- throw new DeptreeError(`the lockfile gives it ${quote(name)} as ${quote(target)}, and its package.json, overridden, names ${quote(local.dir)}`, where)
85
+ // Old tarballs, as npm 1.0 packed them through the system's tar, may run on
86
+ // in zeros past their gzip stream, to a whole 10240-byte record. Node's
87
+ // zlib, which npm, pnpm and yarn unpack through, stops at a zero byte after
88
+ // the stream; the platform's stream refuses anything there, so the zeros are
89
+ // cut off. The stream's last four bytes are the length its last member
90
+ // inflates to, under 2^32 as MAX_BYTES is, so it ends within three bytes
91
+ // past the last that is not zero; or, where that member is empty, as zlib
92
+ // writes one, `03 00` and eight zeros, within nine. It ends at the one place
93
+ // it decompresses whole. Each place tried inflates it all again, which only
94
+ // a padded tarball pays for.
95
+ async function gunzip(bytes) {
96
+ const inflate = (end) => decompress(bytes.subarray(0, end), 'gzip', { limit: MAX_BYTES })
97
+ try {
98
+ return await inflate(bytes.length)
99
+ } catch (error) {
100
+ if (!(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
101
+ const last = bytes.findLastIndex((byte) => byte !== 0)
102
+ for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
103
+ try {
104
+ return await inflate(end)
105
+ } catch {
106
+ // Not where the stream ends: the next byte may be.
107
+ }
108
+ }
109
+ throw error
137
110
  }
138
- // A peer resolved is filed as optional where it is optional; pnpm's
139
- // compatibility database adds peers to a few packages, which the
140
- // lockfile records among their peers and the package.json does not.
141
- const optional = new Set([...names(read.optionalDependencies), ...names(manifest.peerDependencies), ...names(manifest.peerDependenciesMeta), ...names(pkg.peerDependencies), ...names(pkg.peerDependenciesMeta)])
142
- for (const name of names(pkg.optionalDependencies)) {
143
- if (!optional.has(name)) throw new DeptreeError(`the lockfile gives it ${quote(name)} as optional, which its package.json does not`, where)
111
+ }
112
+
113
+ // What a version document says of where a package comes from, each
114
+ // undefined where it says nothing: `commit` is its gitHead.
115
+ const aboutOf = ({ gitHead, repository, homepage, bugs }) => ({ commit: gitHead, repository, homepage, bugs })
116
+ export const NO_ABOUT = Object.freeze(aboutOf({}))
117
+
118
+ // What a tree's options say of what it fetches from npm's registry:
119
+ // `metadata`, true unless given false, and `cache`, as upstream's
120
+ // CacheOptions take it, which keeps each version's document and tarball.
121
+ export function fetchingOf({ metadata = true, cache }) {
122
+ if (typeof metadata !== 'boolean') throw new TypeError('metadata must be a boolean, or left out')
123
+ if (cache !== undefined && cache !== false && (typeof cache?.read !== 'function' || typeof cache?.write !== 'function')) {
124
+ throw new TypeError('cache must be false, or a store with read and write, or left out')
144
125
  }
126
+ return { metadata, cache }
145
127
  }
146
128
 
147
- // A package's files, and its package.json as parsed; the package has to be
148
- // from the registry.
149
- export async function fetchPackage(pkg, where) {
150
- const { integrity } = pkg.resolution
151
- const bytes = await getTarball(pkg.name, pkg.version, { tarball: tarballUrl(pkg.name, pkg.version), integrity })
129
+ // Kept as `cache` says. Without a `given` integrity, as ownTarball lets one
130
+ // through unpinned, the registry's is taken from the version document, which
131
+ // getMeta holds to the registry's own tarball, and `about` is what that
132
+ // says, whatever `metadata` is. Else, with `metadata`, the document is asked
133
+ // for beside the tarball, given the dist the tarball is fetched by, which
134
+ // getMeta holds the document's to as text, the registry's being the one a
135
+ // lockfile copies, so nothing is hashed again. Else NO_ABOUT.
136
+ export async function fetchTarball(name, version, given, where, { metadata, cache }) {
137
+ checkId(name, version, where)
138
+ const meta = given === undefined ? await getMeta(name, version, { cache }) : undefined
139
+ const integrity = given ?? meta.dist.integrity
140
+ if (!/^sha512-[\d+/A-Za-z]{86}==$/u.test(integrity)) throw new DeptreeError('a tarball with no sha512 integrity is not supported', where)
141
+ const dist = { tarball: tarballUrl(name, version), integrity }
142
+ let about = NO_ABOUT
143
+ if (meta !== undefined) about = aboutOf(meta)
144
+ else if (metadata) about = getMeta(name, version, { dist, cache }).then(aboutOf)
145
+ const [bytes, said] = await settled([getTarball(name, version, dist, { cache }), about])
152
146
  if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
153
147
  if (bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the tarball is not gzipped', where)
154
- const files = filesOf(unpack(await decompress(bytes, 'gzip', { limit: MAX_BYTES })), where)
155
- const manifest = readManifest(files, pkg, where)
156
- checkManifest(manifest, pkg, where)
157
- return { files, manifest }
148
+ const tar = await gunzip(bytes)
149
+ return { bytes, tar, entries: unpack(tar), inflated: tar.length, integrity, about: said }
158
150
  }
@@ -0,0 +1,28 @@
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.
4
+
5
+ import { dirname, join } from '@preventive/vfs/path.js'
6
+ import { DeptreeError, quote } from '../error.js'
7
+
8
+ // As yarn's findNearestInstalledVersionOfPackage looks; paths are from the
9
+ // lockfile's directory, `.`.
10
+ function finds(name, loc, dir) {
11
+ for (;; dir = dirname(dir)) {
12
+ if (join(dir, name) === loc || join(dir, `node_modules/${name}`) === loc) return true
13
+ if (dir === '.') return false
14
+ }
15
+ }
16
+
17
+ export function checkBinLinks({ placed, patterns, locations, realOf }) {
18
+ for (const { loc, info } of placed) {
19
+ const binLoc = `${loc}/node_modules`
20
+ const realBinLoc = realOf(binLoc)
21
+ for (const pattern of info.ref.dependencies) {
22
+ const dep = patterns.get(pattern)
23
+ if (dep.kind === 'workspace' || !locations.has(dep) || !dep.hasBins) continue
24
+ const found = locations.get(dep).some((at) => finds(dep.name, at, binLoc) || finds(dep.name, at, realBinLoc))
25
+ if (!found) throw new DeptreeError(`yarn finds no copy of ${quote(dep.name)} to link the bins of`, quote(loc))
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,67 @@
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.
3
+
4
+ import { compareVersions, major, satisfies, valid } from '@preventive/upstream/semver.js'
5
+ import { DeptreeError, quote } from '../error.js'
6
+ import { satisfiesWithPrereleases } from './peers.js'
7
+
8
+ // What Node reports in process.versions, but `node`, in any release or
9
+ // build of it from 12 on (src/node_metadata.h).
10
+ const REPORTED = new Set([
11
+ 'acorn', 'ada', 'amaro', 'ares', 'base64', 'brotli', 'cjs_module_lexer', 'cldr', 'http_parser', 'icu', 'libffi', 'lief',
12
+ 'llhttp', 'merve', 'modules', 'napi', 'nbytes', 'ncrypto', 'nghttp2', 'nghttp3', 'ngtcp2', 'openssl', 'simdjson', 'simdutf',
13
+ 'sqlite', 'tz', 'undici', 'unicode', 'uv', 'uvwasi', 'v8', 'zlib', 'zstd',
14
+ ])
15
+
16
+ // yarn's isValid: an os or cpu list of names, `!` before one to exclude.
17
+ function isValid(items, actual) {
18
+ let isNotWhitelist = true
19
+ let isBlacklist = false
20
+ for (const item of items) {
21
+ if (item[0] === '!') {
22
+ isBlacklist = true
23
+ if (actual === item.slice(1)) return false
24
+ } else {
25
+ isNotWhitelist = false
26
+ if (item === actual) return true
27
+ }
28
+ }
29
+ return isBlacklist && isNotWhitelist
30
+ }
31
+
32
+ const LOOSE = { loose: true }
33
+
34
+ // yarn's testEngine: yarn's own version taken with its prereleases, and
35
+ // Node's versions before 1.0.0 taken for its majors.
36
+ function testEngine(name, range, versions) {
37
+ const actual = versions[name]
38
+ if (!actual || !valid(actual, LOOSE)) return false
39
+ if (satisfies(actual, range, LOOSE)) return true
40
+ if (name === 'yarn' && satisfiesWithPrereleases(actual, range, true)) return true
41
+ if (name === 'node' && compareVersions(actual, '1.0.0', LOOSE) > 0) {
42
+ const of = major(actual, LOOSE)
43
+ return [`0.10.${of}`, `0.11.${of}`, `0.12.${of}`, `0.13.${of}`].some((fake) => satisfies(fake, range, LOOSE))
44
+ }
45
+ return false
46
+ }
47
+
48
+ // engines may be a list of `name range` strings, which yarn reads as a map.
49
+ export function incompatibility(manifest, host, where, { ignoreEngines, ignorePlatform }) {
50
+ const { os, cpu } = manifest
51
+ let { engines } = manifest
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)}`
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)}`
54
+ if (ignoreEngines) return undefined
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(' ')]))
56
+ if (engines === null || typeof engines !== 'object') return undefined
57
+ const versions = { node: host.node, yarn: host.yarn }
58
+ for (let [name, range] of Object.entries(engines)) {
59
+ if (name === 'iojs') name = 'node'
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]}`
65
+ }
66
+ return undefined
67
+ }