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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,111 @@
1
+ // The dependencies folder `soldeer install` makes from a soldeer.lock: each
2
+ // registry dependency's zip fetched, held to the lockfile's checksum, and
3
+ // extracted in a folder of its own (zip.js).
4
+
5
+ import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
6
+ import { getZip } from '@preventive/upstream/soldeer.js'
7
+ import { Vfs, VfsError } from '@preventive/vfs'
8
+ import { eachConcurrently } from '../concurrent.js'
9
+ import { DeptreeError, quote } from '../error.js'
10
+ import { fold, mount } from '../mount.js'
11
+ import { checkCollisions } from '../pnpm/checks.js'
12
+ import { configOf } from './config.js'
13
+ import { checkHost, inputsOf } from './inputs.js'
14
+ import { extractZip } from './zip.js'
15
+
16
+ // What the registry takes, as @preventive/upstream/soldeer.js holds a name
17
+ // and a version to: of these, Soldeer's sanitize_filename leaves a folder
18
+ // `<name>-<version>` as it is on Unix.
19
+ const NAME = /^(?=.{3,100}$)[@\da-z][\da-z-]*[\da-z]$/u
20
+ const VERSION = /^(?=.{1,128}$)[\dA-Za-z][\w.+-]*$/u
21
+
22
+ // Refuses a Vfs that holds a dependencies folder at its root, or, where
23
+ // names are `folded`, a name that is one there.
24
+ function checkNoDependencies(vfs, folded) {
25
+ for (const name of vfs.readdir('/')) {
26
+ if (name === 'dependencies' || (folded && fold(name) === 'dependencies')) {
27
+ throw new DeptreeError('a dependencies folder is there already, which is neither kept beside the tree nor removed', `vfs[${quote(`/${name}`)}]`)
28
+ }
29
+ }
30
+ }
31
+
32
+ // The registry dependencies, each with the folder Soldeer installs it in;
33
+ // any other kind is refused. Where names are `folded`, a folder is one
34
+ // with another that differs from it only in case or normalization.
35
+ function registryDependencies(lock, config, folded) {
36
+ const dependencies = Object.values(lock.dependencies).map((dependency) => ({ ...dependency, folder: `${dependency.name}-${dependency.version}` }))
37
+ const key = (folder) => (folded ? fold(folder) : folder)
38
+ const folders = new Set(dependencies.map(({ folder }) => key(folder)))
39
+ for (const { type, name, version } of dependencies) {
40
+ const where = `dependencies[${quote(name)}]`
41
+ if (type === 'git') throw new DeptreeError('a git dependency, which Soldeer clones with its history, is not supported', where)
42
+ if (type === 'private') throw new DeptreeError('a private dependency, which the registry hands out to those signed in alone, is not supported', where)
43
+ 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)
44
+ if (!NAME.test(name)) throw new DeptreeError('a name the registry does not take', where)
45
+ if (!VERSION.test(version)) throw new DeptreeError(`${quote(version)} is a version the registry does not take`, where)
46
+ }
47
+ // Soldeer downloads each zip beside the folders, as `<folder>.zip`.
48
+ for (const { name, folder } of dependencies) {
49
+ if (folders.has(key(`${folder}.zip`))) throw new DeptreeError(`its zip is downloaded as ${quote(`${folder}.zip`)}, a folder Soldeer installs another dependency in`, `dependencies[${quote(name)}]`)
50
+ }
51
+ return dependencies
52
+ }
53
+
54
+ // Each dependency's zip, fetched and extracted a few at a time, by its
55
+ // folder.
56
+ async function fetchAll(dependencies) {
57
+ const extracted = new Map()
58
+ await eachConcurrently(dependencies, async ({ name, version, checksum, folder }) => {
59
+ const where = `dependencies[${quote(name)}]`
60
+ try {
61
+ extracted.set(folder, await extractZip(await getZip(name, version, checksum), where))
62
+ } catch (error) {
63
+ throw error instanceof DeptreeError ? error : new DeptreeError(error.message, where, { cause: error })
64
+ }
65
+ })
66
+ return extracted
67
+ }
68
+
69
+ function writeTree(extracted) {
70
+ const vfs = new Vfs()
71
+ vfs.mkdir('/dependencies')
72
+ let files = 0
73
+ let bytes = 0
74
+ for (const [folder, { dirs, files: written }] of extracted) {
75
+ const root = `/dependencies/${folder}`
76
+ vfs.mkdir(root)
77
+ for (const dir of dirs) vfs.mkdir(`${root}/${dir}`, { recursive: true })
78
+ for (const [path, file] of written) {
79
+ try {
80
+ vfs.writeFile(`${root}/${path}`, file.data, { mode: file.mode })
81
+ } catch (error) {
82
+ if (error instanceof VfsError) throw new DeptreeError(`cannot be written: ${error.message}`, quote(`dependencies/${folder}/${path}`), { cause: error })
83
+ throw error
84
+ }
85
+ files++
86
+ bytes += file.data.length
87
+ }
88
+ }
89
+ return { vfs, files, bytes }
90
+ }
91
+
92
+ export async function buildSoldeerTree(options) {
93
+ const { host: given, vfs: into } = options ?? {}
94
+ if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
95
+ const inputs = inputsOf(options ?? {})
96
+ const host = checkHost(given)
97
+ const folded = host.os === 'darwin'
98
+ // Refused before anything is fetched; mount checks again.
99
+ if (into !== undefined) checkNoDependencies(into, folded)
100
+ const { config } = configOf(inputs)
101
+ const lock = parseSoldeerLockfile(inputs.lockfile, { config })
102
+ const dependencies = registryDependencies(lock, config, folded)
103
+ const extracted = await fetchAll(dependencies)
104
+ // In the lockfile's order, whatever order the fetches finished in.
105
+ const { vfs, files, bytes } = writeTree(dependencies.map(({ folder }) => [folder, extracted.get(folder)]))
106
+ if (folded) checkCollisions(vfs)
107
+ const stats = { dependencies: dependencies.length, files, bytes }
108
+ if (into === undefined) return { vfs, stats }
109
+ mount(vfs, into, folded, checkNoDependencies)
110
+ return { vfs: into, stats }
111
+ }
@@ -0,0 +1,142 @@
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.
18
+
19
+ import { ArchiveError, unzip } from '@preventive/archive/zip.js'
20
+ import { DeptreeError, quote } from '../error.js'
21
+
22
+ const END = 0x06054b50
23
+ const CENTRAL = 0x02014b50
24
+ const UTF8 = 0x0800
25
+ const S_IFLNK = 0o120000
26
+ const [NTFS, TIMESTAMP, UNICODE_COMMENT, AES] = [0x000a, 0x5455, 0x6375, 0x9901]
27
+
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.
30
+ const MAX_BYTES = 512 * 1024 * 1024
31
+
32
+ // As the archive reader decodes a name: a leading U+FEFF is part of it.
33
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true })
34
+ const encoder = new TextEncoder()
35
+
36
+ const ones = (byte) => [...byte.toString(2)].filter((bit) => bit === '1').length
37
+
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.
42
+ function extraRefusal(view, at, length) {
43
+ for (let pos = at; pos < at + length;) {
44
+ const id = view.getUint16(pos, true)
45
+ const size = view.getUint16(pos + 2, true)
46
+ const body = pos + 4
47
+ 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'
48
+ if (id === TIMESTAMP && (size === 0 || (size !== 5 && size !== 1 + 4 * ones(view.getUint8(body))))) return 'an extended timestamp the zip crate does not read'
49
+ if (id === AES) return 'an AES extra field, which has the zip crate decrypt the entry'
50
+ if (id === UNICODE_COMMENT) return 'a Unicode comment extra field, which the zip crate checks'
51
+ pos = body + size
52
+ }
53
+ return undefined
54
+ }
55
+
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.
60
+ function centralRecords(bytes) {
61
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
62
+ let end = bytes.length - 22
63
+ while (view.getUint32(end, true) !== END || end + 22 + view.getUint16(end + 20, true) !== bytes.length) end--
64
+ const records = []
65
+ let at = view.getUint32(end + 16, true)
66
+ for (let i = 0; i < view.getUint16(end + 10, true); i++) {
67
+ if (view.getUint32(at, true) !== CENTRAL) throw new Error('unreachable: a central record where unzip found none')
68
+ const [nameLength, extraLength, commentLength] = [at + 28, at + 30, at + 32].map((field) => view.getUint16(field, true))
69
+ records.push({
70
+ system: view.getUint8(at + 5),
71
+ flags: view.getUint16(at + 8, true),
72
+ attributes: view.getUint32(at + 38, true),
73
+ name: bytes.subarray(at + 46, at + 46 + nameLength),
74
+ extra: extraRefusal(view, at + 46 + nameLength, extraLength),
75
+ })
76
+ at += 46 + nameLength + extraLength + commentLength
77
+ }
78
+ return records
79
+ }
80
+
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.
84
+ function unixMode({ system, attributes }) {
85
+ if (attributes === 0) return undefined
86
+ const upper = attributes >>> 16
87
+ if (upper !== 0) return upper
88
+ if (system === 3) return 0
89
+ if (system !== 0) return undefined
90
+ const mode = attributes & 0x10 ? 0o040775 : 0o100664
91
+ return attributes & 0x01 ? mode & ~0o222 : mode
92
+ }
93
+
94
+ // What str::trim_end_matches(['.', ' ']) and eq_ignore_ascii_case make of
95
+ // a component Soldeer holds to `.git`.
96
+ const isGit = (component) => component.replace(/[. ]+$/u, '').replace(/[A-Z]/gu, (char) => char.toLowerCase()) === '.git'
97
+
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) {
101
+ let entries
102
+ try {
103
+ entries = await unzip(bytes, { limit: MAX_BYTES })
104
+ } catch (error) {
105
+ if (error instanceof ArchiveError) throw new DeptreeError(`its zip cannot be read: ${error.message}`, where, { cause: error })
106
+ throw error
107
+ }
108
+ 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.
112
+ const last = new Map()
113
+ for (const [index, entry] of entries.entries()) {
114
+ const record = records[index]
115
+ if (decoder.decode(record.name) !== entry.storedName) throw new Error('unreachable: unzip lists entries out of the central directory\'s order')
116
+ const here = `${where}: ${quote(entry.storedName)}`
117
+ 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
+ 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
+ last.set(entry.storedName, index)
121
+ }
122
+ const dirs = new Set()
123
+ const files = new Map()
124
+ for (const index of last.values()) {
125
+ const entry = entries[index]
126
+ if (entry.name === '.') continue
127
+ const components = entry.name.split('/')
128
+ if (components.some((component) => component.includes(':'))) throw new DeptreeError('a name with a ":" in it, which Soldeer fails on', `${where}: ${quote(entry.storedName)}`)
129
+ if (components.some(isGit)) continue
130
+ for (let i = 1; i < components.length; i++) dirs.add(components.slice(0, i).join('/'))
131
+ if (entry.type === 'directory') {
132
+ dirs.add(entry.name)
133
+ continue
134
+ }
135
+ const mode = unixMode(records[index])
136
+ const data = entry.type === 'symlink' ? encoder.encode(entry.linkname) : entry.data
137
+ // A file written again keeps its mode where the zip crate reads none.
138
+ const kept = mode === undefined || (mode & S_IFLNK) === S_IFLNK ? files.get(entry.name)?.mode ?? 0o644 : mode & 0o777 & ~0o022
139
+ files.set(entry.name, { data, mode: kept })
140
+ }
141
+ return { dirs, files }
142
+ }
package/src/tarball.js CHANGED
@@ -51,11 +51,13 @@ function nameOf(stored) {
51
51
  export const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
52
52
  const sameFile = (a, b) => a.mode === b.mode && sameBytes(a.data, b.data)
53
53
 
54
- // A Map of each file's path in the package to its bytes and mode.
55
- function filesOf(entries, where) {
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) {
56
57
  const files = new Map()
57
58
  const tops = new Set()
58
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)
59
61
  if (entry.type === 'directory') continue
60
62
  if (entry.type !== 'file') throw new DeptreeError(`${quote(entry.name)} is a ${entry.type}, which is not supported`, where)
61
63
  tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
@@ -81,7 +83,13 @@ const names = (value) => Object.keys(value ?? {})
81
83
  // `bin` is there and names none, and there is a directories.bin, pnpm
82
84
  // resolves it as having none and pnpm 11 rewrites a snapshot as having
83
85
  // some, so that is undefined: bins are linked as the lockfile has it.
84
- function hasBin({ bin, directories }) {
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
+ }
85
93
  if (bin === undefined || bin === null) return Boolean(directories?.bin)
86
94
  if (bin && Object.keys(bin).length > 0) return true
87
95
  return directories?.bin ? undefined : false
@@ -102,11 +110,11 @@ function readManifest(files, pkg, where) {
102
110
  }
103
111
 
104
112
  // What the lockfile recorded of the package against the package.json.
105
- export function checkManifest(manifest, pkg, where) {
113
+ export function checkManifest(manifest, pkg, where, major) {
106
114
  for (const field of ['os', 'cpu', 'libc']) {
107
115
  if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
108
116
  }
109
- const has = hasBin(manifest)
117
+ const has = hasBin(manifest, major)
110
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)
111
119
  if (!same(listed(bundledOf(manifest)), listed(pkg.bundledDependencies))) throw new DeptreeError('package.json bundles other than the lockfile says', where)
112
120
  }
@@ -144,15 +152,21 @@ export function checkDependencies(manifest, read, pkg, where) {
144
152
  }
145
153
  }
146
154
 
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 })
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
+ export async function fetchTarball(name, version, integrity, where) {
158
+ const bytes = await getTarball(name, version, { tarball: tarballUrl(name, version), integrity })
152
159
  if (!await matchesIntegrity(bytes, integrity)) throw new DeptreeError(`the tarball is not ${integrity}`, where)
153
160
  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)
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)
155
169
  const manifest = readManifest(files, pkg, where)
156
- checkManifest(manifest, pkg, where)
170
+ checkManifest(manifest, pkg, where, major)
157
171
  return { files, manifest }
158
172
  }
@@ -0,0 +1,38 @@
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.
8
+
9
+ import { dirname, join } from '@preventive/vfs/path.js'
10
+ import { DeptreeError, quote } from '../error.js'
11
+ import { binsOf } from './package.js'
12
+
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.
17
+ function finds(name, loc, dir) {
18
+ for (;; dir = dirname(dir)) {
19
+ if (join(dir, name) === loc || join(dir, `node_modules/${name}`) === loc) return true
20
+ if (dir === '.') return false
21
+ }
22
+ }
23
+
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 }) {
29
+ for (const { loc, info } of placed) {
30
+ const binLoc = `${loc}/node_modules`
31
+ for (const pattern of info.ref.dependencies) {
32
+ 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)))
35
+ if (!found) throw new DeptreeError(`yarn finds no copy of ${quote(dep.name)} to link the bins of`, quote(loc))
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,86 @@
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.
10
+
11
+ import { compareVersions, major, satisfies, valid } from '@preventive/upstream/semver.js'
12
+ import { DeptreeError, quote } from '../error.js'
13
+ import { satisfiesWithPrereleases } from './peers.js'
14
+
15
+ // What Node reports in process.versions, but `node`, in any release or
16
+ // build of it from 12 on (src/node_metadata.h).
17
+ const REPORTED = new Set([
18
+ 'acorn', 'ada', 'amaro', 'ares', 'base64', 'brotli', 'cjs_module_lexer', 'cldr', 'http_parser', 'icu', 'libffi', 'lief',
19
+ 'llhttp', 'merve', 'modules', 'napi', 'nbytes', 'ncrypto', 'nghttp2', 'nghttp3', 'ngtcp2', 'openssl', 'simdjson', 'simdutf',
20
+ 'sqlite', 'tz', 'undici', 'unicode', 'uv', 'uvwasi', 'v8', 'zlib', 'zstd',
21
+ ])
22
+
23
+ // yarn's isValid: an os or cpu list of names, `!` before one to exclude.
24
+ function isValid(items, actual) {
25
+ let isNotWhitelist = true
26
+ let isBlacklist = false
27
+ for (const item of items) {
28
+ if (item[0] === '!') {
29
+ isBlacklist = true
30
+ if (actual === item.slice(1)) return false
31
+ } else {
32
+ isNotWhitelist = false
33
+ if (item === actual) return true
34
+ }
35
+ }
36
+ return isBlacklist && isNotWhitelist
37
+ }
38
+
39
+ const LOOSE = { loose: true }
40
+
41
+ // yarn's testEngine: yarn's own version taken with its prereleases, and
42
+ // Node's versions before 1.0.0 taken for its majors.
43
+ function testEngine(name, range, versions) {
44
+ const actual = versions[name]
45
+ if (!actual || !valid(actual, LOOSE)) return false
46
+ if (satisfies(actual, range, LOOSE)) return true
47
+ if (name === 'yarn' && satisfiesWithPrereleases(actual, range, true)) return true
48
+ if (name === 'node' && compareVersions(actual, '1.0.0', LOOSE) > 0) {
49
+ const of = major(actual, LOOSE)
50
+ return [`0.10.${of}`, `0.11.${of}`, `0.12.${of}`, `0.13.${of}`].some((fake) => satisfies(fake, range, LOOSE))
51
+ }
52
+ return false
53
+ }
54
+
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.
59
+ export function incompatibility(manifest, host, where, { ignoreEngines, ignorePlatform }) {
60
+ const { os, cpu } = manifest
61
+ let { engines } = manifest
62
+ 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
+ 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
+ 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
+ }
74
+ if (engines === null || typeof engines !== 'object') return undefined
75
+ const versions = { node: host.node, yarn: host.yarn }
76
+ for (let [name, range] of Object.entries(engines)) {
77
+ 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
+ }
84
+ }
85
+ return undefined
86
+ }
@@ -0,0 +1,52 @@
1
+ // The globs yarn matches with minimatch's defaults, as far as the lockfile
2
+ // reader lets them through: a segment at a time, `**` as any number of
3
+ // whole segments, `*` and `?` within one, and no segment that starts with
4
+ // a dot taken by a wildcard.
5
+
6
+ import { escape } from '../matcher.js'
7
+
8
+ const compiled = new Map()
9
+
10
+ function compile(glob) {
11
+ return glob.split('/').map((segment) => {
12
+ if (segment === '**') return null
13
+ const dot = segment.startsWith('.') || !/[*?]/u.test(segment) ? '' : '(?!\\.)'
14
+ return new RegExp(`^${dot}${segment.split(/([*?])/u).map((part) => (part === '*' ? '[^/]*' : part === '?' ? '[^/]' : escape(part))).join('')}$`, 'u')
15
+ })
16
+ }
17
+
18
+ // The places in `glob` that `path` reaches, a name at a time, a `**`
19
+ // taking none or more, in time linear in both: a place is the index of the
20
+ // glob's next segment, its length where all are taken.
21
+ function placesOf(glob, path) {
22
+ if (!compiled.has(glob)) compiled.set(glob, compile(glob))
23
+ const tests = compiled.get(glob)
24
+ const close = (places) => {
25
+ for (let i = 0; i < tests.length; i++) if (places.has(i) && tests[i] === null) places.add(i + 1)
26
+ return places
27
+ }
28
+ let places = close(new Set([0]))
29
+ for (const segment of path === '' ? [] : path.split('/')) {
30
+ const next = new Set()
31
+ for (const i of places) {
32
+ if (i === tests.length) continue
33
+ if (tests[i] === null) {
34
+ if (!segment.startsWith('.')) next.add(i)
35
+ } else if (tests[i].test(segment)) next.add(i + 1)
36
+ }
37
+ places = close(next)
38
+ }
39
+ return { places, length: tests.length }
40
+ }
41
+
42
+ // Whether `glob` takes `path`.
43
+ export function matchesGlob(glob, path) {
44
+ const { places, length } = placesOf(glob, path)
45
+ return places.has(length)
46
+ }
47
+
48
+ // Whether `glob` may take a path below `dir`: some of it left to take.
49
+ export function reachesBelow(glob, dir) {
50
+ const { places, length } = placesOf(glob, dir)
51
+ return [...places].some((place) => place < length)
52
+ }