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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +41 -12
  5. package/pnpm.d.ts +158 -25
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +60 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +60 -10
  15. package/src/mount.js +104 -44
  16. package/src/npm/bins.js +54 -0
  17. package/src/npm/compat.js +97 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +75 -0
  21. package/src/npm/manifests.js +130 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/npmrc.js +24 -0
  28. package/src/patch.js +22 -41
  29. package/src/pnpm/bins.js +152 -131
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +53 -96
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +29 -75
  34. package/src/pnpm/gitignore.js +139 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +68 -61
  38. package/src/pnpm/hoisted.js +234 -0
  39. package/src/pnpm/hook.js +26 -31
  40. package/src/pnpm/inputs.js +73 -56
  41. package/src/pnpm/install.js +85 -131
  42. package/src/pnpm/local.js +21 -40
  43. package/src/pnpm/minimatch.js +319 -0
  44. package/src/pnpm/nm-hoist-graph.js +299 -0
  45. package/src/pnpm/nm-hoist.js +149 -0
  46. package/src/pnpm/npm-packlist.js +217 -0
  47. package/src/pnpm/overrides.js +11 -51
  48. package/src/pnpm/package.js +121 -0
  49. package/src/pnpm/packlist.js +169 -109
  50. package/src/pnpm/patches.js +18 -25
  51. package/src/pnpm/projects.js +63 -107
  52. package/src/pnpm/readers.js +63 -83
  53. package/src/pnpm/settings.js +64 -100
  54. package/src/pnpm/tree.js +197 -169
  55. package/src/pnpm/uptodate.js +16 -28
  56. package/src/pnpm/workspace.js +124 -133
  57. package/src/project.js +57 -0
  58. package/src/soldeer/config.js +8 -24
  59. package/src/soldeer/inputs.js +5 -15
  60. package/src/soldeer/tree.js +22 -60
  61. package/src/soldeer/zip.js +17 -36
  62. package/src/tarball.js +55 -140
  63. package/src/yarn1/bins.js +9 -19
  64. package/src/yarn1/compat.js +9 -28
  65. package/src/yarn1/hoist.js +53 -68
  66. package/src/yarn1/inputs.js +19 -61
  67. package/src/yarn1/manifest.js +8 -23
  68. package/src/yarn1/package.js +24 -63
  69. package/src/yarn1/peers.js +8 -15
  70. package/src/yarn1/requests.js +19 -37
  71. package/src/yarn1/resolve.js +36 -113
  72. package/src/yarn1/settings.js +15 -43
  73. package/src/yarn1/tree.js +67 -91
  74. package/yarn1.d.ts +34 -5
  75. package/yarn1.js +1 -8
  76. package/src/pnpm/npmrc.js +0 -31
  77. package/src/pnpm/project.js +0 -97
  78. package/src/yarn1/glob.js +0 -52
  79. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,149 @@
1
+ // The hoist of @yarnpkg/nm 4.0.5, which pnpm 9 and 10 bundle for the hoisted
2
+ // linker: each package is moved as near the root as it can go without
3
+ // shadowing a different one of its name for a package that needs that one.
4
+ // Step for step as it runs, with its recursions on stacks of their own, and
5
+ // its debug output and checks left out, which change nothing. pnpm sets no
6
+ // hoisting limits, hoist priorities or external soft links, which are left
7
+ // out too: the root alone is a hoist border, and nothing depends on it.
8
+
9
+ import { DeptreeError } from '../error.js'
10
+ import { REGULAR, WORKSPACE, buildPreferenceMap, depthFirst, getHoistIdentMap, getUsedDependencies, getZeroRoundUsedDependencies, hoistGraph, regularDependencies, walk } from './nm-hoist-graph.js'
11
+
12
+ export { REGULAR, WORKSPACE, depthFirst, reachable } from './nm-hoist-graph.js'
13
+
14
+ const makeLocator = (name, reference) => `${name}@${reference}`
15
+ const makeIdent = (name, reference) => {
16
+ const hash = reference.indexOf('#')
17
+ return makeLocator(name, hash >= 0 ? reference.slice(hash + 1) : reference)
18
+ }
19
+ const getIdentName = (locator) => locator.slice(0, locator.indexOf('@', 1))
20
+
21
+ // The steps hoisting may take, and the nodes of the tree it gives, past
22
+ // which it is refused: on a graph made to defeat it, the hoist walks each
23
+ // path through what it cannot hoist, and the tree has a copy of a package
24
+ // for each, of which there can be more than there is time or memory for.
25
+ const MAX_STEPS = 50_000_000
26
+ const MAX_NODES = 100_000
27
+
28
+ function counter(limit, what, stats) {
29
+ let steps = 0
30
+ return (count = 1) => {
31
+ steps += count
32
+ if (stats !== undefined) stats[what] = steps
33
+ if (steps > limit) throw new DeptreeError(`hoisting it ${what}, which is not supported`, 'lockfile')
34
+ }
35
+ }
36
+
37
+ // hoistTo of one node: its hoisting, until no name has another ident to try.
38
+ function hoistToNode(rootNodePath, parentShadowedNodes, options, flags, step) {
39
+ const rootNode = rootNodePath.at(-1)
40
+ step(rootNodePath.length)
41
+ const preferenceMap = buildPreferenceMap(rootNode, step)
42
+ step(preferenceMap.size)
43
+ const hoistIdentMap = getHoistIdentMap(rootNode, preferenceMap)
44
+ const usedDependencies = rootNodePath.length === 1 ? new Map() : options.fastLookupPossible ? getZeroRoundUsedDependencies(rootNodePath, step) : getUsedDependencies(rootNodePath, step)
45
+ const hoistIdents = new Map([...hoistIdentMap].map(([name, idents]) => [name, idents[0]]))
46
+ const shadowedNodes = new Map()
47
+ let wasStateChanged
48
+ do {
49
+ const state = { rootNode, rootNodePath, usedDependencies, hoistIdents, parentShadowedNodes, shadowedNodes, options, step, seenNodes: new Set(), isGraphChanged: false, anotherRoundNeeded: false }
50
+ hoistGraph(state)
51
+ if (state.isGraphChanged) flags.isGraphChanged = true
52
+ if (state.anotherRoundNeeded) flags.anotherRoundNeeded = true
53
+ wasStateChanged = false
54
+ step(hoistIdentMap.size)
55
+ for (const [name, idents] of hoistIdentMap) {
56
+ if (idents.length > 1 && !rootNode.dependencies.has(name)) {
57
+ hoistIdents.delete(name)
58
+ idents.shift()
59
+ hoistIdents.set(name, idents[0])
60
+ wasStateChanged = true
61
+ }
62
+ }
63
+ } while (wasStateChanged)
64
+ return shadowedNodes
65
+ }
66
+
67
+ // hoistTo: each node of the tree in turn becomes the root hoisted to, depth
68
+ // first along every path that does not come back to a package on it. The
69
+ // locators on the path are read by nothing else but the debug output.
70
+ function hoistTo(tree, options, step) {
71
+ const flags = { anotherRoundNeeded: false, isGraphChanged: false }
72
+ const locators = new Set([tree.locator])
73
+ const enter = (path, parentShadowedNodes) => ({ path, shadowedNodes: hoistToNode(path, parentShadowedNodes, options, flags, step), items: regularDependencies(path.at(-1)) })
74
+ depthFirst(enter([tree], new Map()), (dependency, frame) => {
75
+ if (locators.has(dependency.locator)) return undefined
76
+ locators.add(dependency.locator)
77
+ return enter([...frame.path, dependency], frame.shadowedNodes)
78
+ }, ({ path }) => locators.delete(path.at(-1).locator))
79
+ return flags
80
+ }
81
+
82
+ // The working copy of the tree: a node per package node of the tree, shared
83
+ // where the tree shares it, and coupled then, so that hoisting copies it
84
+ // before it changes it.
85
+ function cloneTree(tree, step) {
86
+ const workNodeOf = (node, dependencyKind) => ({
87
+ name: node.name,
88
+ references: new Set([node.reference]),
89
+ locator: makeLocator(node.identName, node.reference),
90
+ ident: makeIdent(node.identName, node.reference),
91
+ dependencies: new Map(),
92
+ originalDependencies: new Map(),
93
+ hoistedDependencies: new Map(),
94
+ peerNames: new Set(node.peerNames),
95
+ decoupled: true,
96
+ dependencyKind,
97
+ })
98
+ const treeCopy = workNodeOf(tree, WORKSPACE)
99
+ const seenNodes = new Map([[tree, treeCopy]])
100
+ const markNodeCoupled = (start) => walk(start, undefined, function* (node) {
101
+ node.decoupled = false
102
+ for (const dep of regularDependencies(node)) yield [dep]
103
+ }, step)
104
+ depthFirst({ workNode: treeCopy, items: tree.dependencies.values() }, (node, { workNode: parentNode }) => {
105
+ step()
106
+ const isSeen = seenNodes.has(node)
107
+ if (!isSeen) seenNodes.set(node, workNodeOf(node, node.dependencyKind || REGULAR))
108
+ const workNode = seenNodes.get(node)
109
+ parentNode.dependencies.set(node.name, workNode)
110
+ parentNode.originalDependencies.set(node.name, workNode)
111
+ if (!isSeen) return { workNode, items: node.dependencies.values() }
112
+ markNodeCoupled(workNode)
113
+ return undefined
114
+ })
115
+ return treeCopy
116
+ }
117
+
118
+ // The hoisted tree, unfolded along each path into one of nodes with a name,
119
+ // an identName, references and dependencies, a node's peers left out.
120
+ function shrinkTree(tree, maxNodes, stats) {
121
+ const step = counter(maxNodes, `makes a tree of more than ${maxNodes} packages`, stats)
122
+ const treeCopy = { name: tree.name, identName: getIdentName(tree.locator), references: new Set(tree.references), dependencies: new Set() }
123
+ const onPath = new Set([tree])
124
+ depthFirst({ node: tree, result: treeCopy, items: regularDependencies(tree) }, (node, { node: parentWorkNode, result: parentNode }) => {
125
+ step()
126
+ const resultNode = parentWorkNode === node ? parentNode : { name: node.name, identName: getIdentName(node.locator), references: node.references, dependencies: new Set() }
127
+ parentNode.dependencies.add(resultNode)
128
+ if (onPath.has(node)) return undefined
129
+ onPath.add(node)
130
+ return { node, result: resultNode, items: regularDependencies(node) }
131
+ }, ({ node }) => node !== tree && onPath.delete(node))
132
+ return treeCopy
133
+ }
134
+
135
+ // `tree` is a node of `name`, `identName`, `reference`, `peerNames`,
136
+ // `dependencyKind` and a Set of `dependencies`, as pnpm's real-hoist makes
137
+ // it.
138
+ export function hoist(tree, { maxSteps = MAX_STEPS, maxNodes = MAX_NODES, stats } = {}) {
139
+ const step = counter(maxSteps, `takes more than ${maxSteps} steps`, stats)
140
+ const treeCopy = cloneTree(tree, step)
141
+ const options = { fastLookupPossible: true }
142
+ let anotherRoundNeeded
143
+ do {
144
+ const result = hoistTo(treeCopy, options, step)
145
+ anotherRoundNeeded = result.anotherRoundNeeded || result.isGraphChanged
146
+ options.fastLookupPossible = false
147
+ } while (anotherRoundNeeded)
148
+ return shrinkTree(treeCopy, maxNodes, stats)
149
+ }
@@ -0,0 +1,217 @@
1
+ // The walks of npm-packlist over ignore-walk that pnpm 9 and 10 (npm-packlist
2
+ // 5.1.3, ignore-walk 5) and pnpm 11 (npm-packlist 10.0.4, ignore-walk 8)
3
+ // run over a directory, kept to their steps, odd ones and all: a walker of a
4
+ // directory asks its parent of each entry by a path from there, and reads
5
+ // the ignore files among its entries, in the order ignoreFiles lists them.
6
+ // `view` reads the directory, and refuses what is not followed here.
7
+
8
+ import { basename, dirname, join, normalize } from '@preventive/vfs/path.js'
9
+ import { quote } from '../error.js'
10
+ import { glob } from './glob.js'
11
+ import { NO_TRAVERSAL_5, caseless, fromParts, rulesOf } from './minimatch.js'
12
+
13
+ const DEFAULTS = ['.npmignore', '.gitignore', '**/.git', '**/.svn', '**/.hg', '**/CVS', '**/.git/**', '**/.svn/**', '**/.hg/**', '**/CVS/**', '/.lock-wscript', '/.wafpickle-*', '/build/config.gypi', 'npm-debug.log', '**/.npmrc', '.*.swp', '.DS_Store', '**/.DS_Store/**', '._*', '**/._*/**', '*.orig']
14
+
15
+ const BUILTIN = Symbol('built-in rules')
16
+ const NECESSARY = Symbol('necessary rules')
17
+ const STRICT = Symbol('strict rules')
18
+
19
+ const MUST_HAVE_NAMES = ['readme', 'copying', 'license', 'licence']
20
+ const MUST_HAVE_RE = caseless(String.raw`^(?:readme|copying|license|licence)(?:\..*[^~$])?$`)
21
+
22
+ // npm-packlist 5's `@(readme|copying|license|licence){,.*[^~$]}`, as glob
23
+ // and minimatch 5 read it: two patterns of one part.
24
+ const MUST_HAVES_5 = ['', String.raw`\.[^/]*?[^~$]`].map((rest) => [caseless(`^${NO_TRAVERSAL_5}(?=.)(?:${MUST_HAVE_NAMES.join('|')})${rest}$`)])
25
+
26
+ // npm-packlist 10's `!/readme{,.*[^~$]}` and the like, as minimatch 10 reads them.
27
+ const MUST_HAVES_10 = MUST_HAVE_NAMES.map((name) => fromParts(true, ['', String.raw`\.[^/]*?[^~$]`].map((rest) => ['', caseless(`^${name}${rest}$`)]), '10.2'))
28
+
29
+ const relOf = (walker, entry) => (walker.rel === '' ? entry : `${walker.rel}/${entry}`)
30
+
31
+ function readRules(view, rel, minimatch, where) {
32
+ const here = `${where}: ${quote(rel)}`
33
+ return rulesOf([view.text(rel, here)], minimatch, here)
34
+ }
35
+
36
+ // What ignore-walk 5 and 8 make of one rule against an entry.
37
+ function ruleMatches(rule, entry, partial, base) {
38
+ const relative = base !== undefined && rule.globParts.some((part) => part.length <= (part.at(-1) ? 1 : 2))
39
+ return rule.test(`/${entry}`) || rule.test(entry) || (partial && (
40
+ rule.test(`/${entry}/`) || rule.test(`${entry}/`) || (rule.negate && (rule.test(`/${entry}`, true) || rule.test(entry, true)))
41
+ || (relative && (rule.test(`/${base}/`) || rule.test(`${base}/`) || (rule.negate && (rule.test(`/${base}`, true) || rule.test(base, true)))))))
42
+ }
43
+
44
+ function applyRules(walker, entry, partial, included, base) {
45
+ let kept = included
46
+ for (const file of walker.ignoreFiles) {
47
+ for (const rule of walker.rules.get(file) ?? []) {
48
+ if (rule.negate !== kept && ruleMatches(rule, entry, partial, base)) kept = rule.negate
49
+ }
50
+ }
51
+ return kept
52
+ }
53
+
54
+ // npm-packlist 5's pathHasPkg: a package's directory in node_modules.
55
+ function packageIn(entry) {
56
+ if (!entry.startsWith('node_modules/')) return false
57
+ const [first, ...rest] = entry.slice('node_modules/'.length).split('/', 2)
58
+ return first !== '' && (!first.startsWith('@') || rest.length === 1)
59
+ }
60
+
61
+ // npm-packlist 5's filterEntry over ignore-walk 5's.
62
+ function filter5(walker, entry, partial) {
63
+ const { isProject } = walker
64
+ if (!isProject && /^node_modules(?:$|\/)/iu.test(walker.rel)) return filter5(walker.parent, `${walker.basename}/${entry}`, partial)
65
+ if (isProject && (entry === 'node_modules' || packageIn(entry))) return false
66
+ if ((isProject && entry === 'package.json') || MUST_HAVE_RE.test(entry) || (isProject && entry === 'npm-shrinkwrap.json')) return true
67
+ if (isProject && entry === 'package-lock.json') return false
68
+ const included = isProject ? true : filter5(walker.parent, `${walker.basename}/${entry}`, partial)
69
+ return applyRules(walker, entry, partial, included)
70
+ }
71
+
72
+ // ignore-walk 8's filterEntry, which npm-packlist 10 keeps.
73
+ function filter10(walker, entry, partial, base) {
74
+ let included = true
75
+ if (walker.parent !== undefined) {
76
+ included = filter10(walker.parent, `${walker.basename}/${entry}`, partial, base ?? entry)
77
+ if (!included && !walker.exact) return false
78
+ }
79
+ return applyRules(walker, entry, partial, included, base)
80
+ }
81
+
82
+ // A walk of one directory: its ignore files read, its entries filtered,
83
+ // then each file kept and each directory walked. `entries` are its own, or,
84
+ // for npm-packlist 5's root where package.json has `files`, what those take.
85
+ function visit(view, walker, entries, engine, result = new Set()) {
86
+ if (entries.length === 0) return result
87
+ for (const entry of entries) {
88
+ if (walker.ignoreFiles.includes(entry)) engine.readIgnore(walker, entry)
89
+ }
90
+ if (engine.major >= 11 && walker.rules.has('package.json')) walker.rules.delete('.npmignore')
91
+ if (walker.rules.has('.npmignore') || (engine.major >= 11 && walker.rules.has('package.json'))) walker.rules.delete('.gitignore')
92
+ for (const entry of entries) {
93
+ const file = engine.filter(walker, entry, false)
94
+ const dir = engine.filter(walker, entry, true)
95
+ if ((!file && !dir) || entry.includes('*')) continue
96
+ const rel = relOf(walker, entry)
97
+ if (view.type(rel) !== 'directory') {
98
+ if (file) result.add(rel)
99
+ } else if (dir) visit(view, engine.child(walker, entry, rel, file), view.entries(rel), engine, result)
100
+ }
101
+ return result
102
+ }
103
+
104
+ // npm-normalize-package-bin 2's bin: an object, or nothing.
105
+ function normalizeBin(pkg) {
106
+ const { bin } = pkg
107
+ const named = typeof bin === 'string' ? (pkg.name ? { [pkg.name]: bin } : {})
108
+ : Array.isArray(bin) ? Object.fromEntries(bin.map((path) => [basename(String(path)), path]))
109
+ : bin !== null && typeof bin === 'object' ? bin : {}
110
+ const clean = Object.entries(named).map(([key, path]) => [
111
+ join('/', basename(key.replaceAll(/[:\\]/gu, '/'))).slice(1),
112
+ typeof path === 'string' ? join('/', path).replaceAll('\\', '/').slice(1) : '',
113
+ ]).filter(([key, path]) => key !== '' && path !== '')
114
+ return clean.length > 0 ? Object.fromEntries(clean) : undefined
115
+ }
116
+
117
+ // npm-packlist 5's mustHaveFilesFromPackage, of `pkg` with its bin normalized.
118
+ const mustHaves5 = (pkg) => [
119
+ ...[pkg.browser, pkg.main, ...Object.values(pkg.bin ?? {})].filter(Boolean).map((path) => `/${path}`),
120
+ '/package.json', '/npm-shrinkwrap.json', '!/package-lock.json', MUST_HAVES_5,
121
+ ]
122
+
123
+ // npm-packlist 5's root entries where package.json has `files`: what glob
124
+ // takes of each pattern in turn, a `!` one's taken back out.
125
+ function filesEntries5(view, pkg, where) {
126
+ const taken = new Set()
127
+ const negates = new Set()
128
+ for (const pattern of new Set([...pkg.files, ...mustHaves5(pkg)])) {
129
+ const negate = typeof pattern === 'string' && pattern.match(/^!*/u)[0].length % 2 === 1
130
+ const body = typeof pattern === 'string' ? pattern.replace(/^!+/u, '').replace(/^\.?\/+/u, '') : pattern
131
+ for (const found of glob(view, body, where)) {
132
+ const path = found.replace(/\/+$/u, '')
133
+ ;(negate ? taken : negates).delete(path)
134
+ ;(negate ? negates : taken).add(path)
135
+ }
136
+ }
137
+ pkg.files = [...taken, ...[...negates].map((path) => `!${path}`)]
138
+ return [...new Set([...taken].map((path) => path.replace(/^\/+/u, '')))]
139
+ }
140
+
141
+ // `manifest` is undefined where npm-packlist fails to parse package.json,
142
+ // which it then reads no rules of. `minimatch` is the version pnpm bundles.
143
+ export function pack10(view, manifest, where, minimatch) {
144
+ const pkg = manifest === undefined ? undefined : { ...structuredClone(manifest), bin: normalizeBin(manifest) }
145
+ const files = Array.isArray(pkg?.files)
146
+ const rules = new Map([[BUILTIN, rulesOf([...DEFAULTS, '/package-lock.json', '/yarn.lock', '/pnpm-lock.yaml', '/archived-packages/**'], minimatch, where)]])
147
+ const root = { rel: '', isProject: true, rules, ignoreFiles: [BUILTIN, 'package.json', '.npmignore', '.gitignore', NECESSARY] }
148
+ const own = view.entries('').filter((entry) => entry !== '.git' && entry !== 'node_modules')
149
+ const engine = {
150
+ major: 10,
151
+ filter: filter5,
152
+ readIgnore(walker, entry) {
153
+ if (entry !== 'package.json') walker.rules.set(entry, readRules(view, relOf(walker, entry), minimatch, where))
154
+ else if (walker.isProject && files) walker.rules.set(entry, rulesOf(pkg.files.map((path) => `!${path}`), minimatch, where))
155
+ else if (walker.isProject && pkg !== undefined) walker.rules.set(NECESSARY, rulesOf(mustHaves5(pkg).map((path) => (Array.isArray(path) ? fromParts(true, path, minimatch) : `!${path}`)), minimatch, where))
156
+ },
157
+ child: (walker, entry, rel) => ({ rel, parent: walker, basename: basename(rel), isProject: false, rules: new Map(), ignoreFiles: walker.ignoreFiles }),
158
+ }
159
+ return visit(view, root, files && own.includes('package.json') ? filesEntries5(view, pkg, where) : own, engine)
160
+ }
161
+
162
+ // npm-packlist 10's processPackage: package.json's rules, and the strict ones.
163
+ // pnpm from 11.28 keeps a package.yaml and a package.json5 too, by `alternates`.
164
+ function processPackage(view, walker, pkg, where, alternates) {
165
+ const ignores = []
166
+ const strict = ['/.git', '!/package.json', ...MUST_HAVES_10, '/.git', '/node_modules', '.npmrc', '/package-lock.json', '/yarn.lock', '/pnpm-lock.yaml', '/bun.lockb']
167
+ for (const entry of pkg.files ?? []) {
168
+ let file = entry.startsWith('./') ? entry.slice(1) : entry
169
+ if (file.endsWith('/*')) file += '*'
170
+ const type = view.type(file.replace(/^!+/u, ''))
171
+ if (type === 'file') {
172
+ strict.unshift(`!${file}`)
173
+ walker.requiredFiles.push(file.startsWith('/') ? file.slice(1) : file)
174
+ } else if (type === 'directory') ignores.push(`!${file}`, `!${file}/**`)
175
+ else ignores.push(`!${file}`)
176
+ }
177
+ if (pkg.files) walker.rules.set('package.json', rulesOf(['*', ...ignores], '10.2', where))
178
+ const fields = [pkg.browser, pkg.main, ...pkg.bin === undefined || pkg.bin === null ? [] : Object.values(pkg.bin)].filter(Boolean).map((path) => `!/${path}`)
179
+ walker.rules.set(STRICT, rulesOf([...strict, ...fields, ...alternates ? ['!/package.yaml', '!/package.json5'] : []], '10.2', where))
180
+ }
181
+
182
+ // pnpm's normalizePackage: `./` taken off main, browser and each bin.
183
+ const stripDotSlash = (path) => (typeof path === 'string' ? path.replace(/^\.[/\\]/u, '') : path)
184
+
185
+ export function pack11(view, manifest, where, alternates) {
186
+ const { bin } = manifest
187
+ const pkg = {
188
+ ...manifest,
189
+ main: stripDotSlash(manifest.main),
190
+ browser: stripDotSlash(manifest.browser),
191
+ bin: bin !== null && typeof bin === 'object' ? Object.fromEntries(Object.entries(bin).map(([key, path]) => [key, stripDotSlash(path)])) : stripDotSlash(bin),
192
+ }
193
+ const defaults = rulesOf([...DEFAULTS, '/archived-packages/**'], '10.2', where)
194
+ const walkerOf = (fields) => {
195
+ const made = { rules: new Map([[BUILTIN, defaults]]), requiredFiles: [], ...fields }
196
+ if (!made.isPackage) made.rules.set(STRICT, rulesOf(['/.git', ...made.requiredFiles.map((file) => `!${file}`)], '10.2', where))
197
+ return made
198
+ }
199
+ const root = walkerOf({ rel: '', isPackage: true, ignoreFiles: [BUILTIN, 'package.json', '.npmignore', '.gitignore', STRICT] })
200
+ const engine = {
201
+ major: 11,
202
+ filter: filter10,
203
+ readIgnore(walker, entry) {
204
+ if (entry === 'package.json' && walker.isPackage) processPackage(view, walker, pkg, where, alternates)
205
+ else walker.rules.set(entry, readRules(view, relOf(walker, entry), '10.2', where))
206
+ },
207
+ child: (parent, entry, rel, file) => walkerOf({
208
+ rel,
209
+ parent,
210
+ basename: entry,
211
+ exact: file || filter10(parent, `${entry}/`, false),
212
+ ignoreFiles: [BUILTIN, '.npmignore', '.gitignore', STRICT],
213
+ requiredFiles: parent.requiredFiles.map(normalize).filter((path) => dirname(path) === entry).map((path) => basename(path)),
214
+ }),
215
+ }
216
+ return visit(view, root, view.entries(''), engine)
217
+ }
@@ -1,40 +1,13 @@
1
- // Overrides as pnpm 10 reads them. The root package.json gives Yarn's
2
- // `resolutions` and its own `pnpm.overrides`, the second winning a
3
- // selector both name; where the two name any, they are the overrides,
4
- // and pnpm-workspace.yaml's are passed over whole, as `pnpm install`
5
- // spreads the package.json's settings over the rest. Only where the
6
- // package.json names none are pnpm-workspace.yaml's `overrides` read. In
7
- // each, a value of `$name` is the specifier
8
- // the root package.json gives its own dependency `name` (optional over
9
- // regular over dev), and one of `catalog:` or `catalog:<name>` is what
10
- // that catalog gives the package the selector targets. A selector is a
11
- // package, `name` or `name@range`, and may lead with its parent and a
12
- // `>`: `bar@2>foo@1`. Anything pnpm cannot read — a selector it cannot
13
- // parse, a `$name` with no such dependency, a catalog without the entry,
14
- // or with one it refuses — is refused the same.
15
- //
16
- // The overrides are what the lockfile was resolved with, which is where
17
- // they did their work: with a frozen lockfile pnpm only holds them to the
18
- // lockfile's `overrides` (uptodate.js), and resolves anew where they
19
- // differ.
20
- //
21
- // An override to a directory — `link:`, `file:` or a path alone, such as
22
- // `./vendor/foo` — names it from the lockfile's directory, and is read
23
- // only from a Vfs given that holds it (tree.js): one outside the lockfile's
24
- // directory, or from the root or the home directory, is refused.
25
- //
26
- // pnpm 11 reads them from pnpm-workspace.yaml alone, trims each selector,
27
- // takes a catalog's `workspace:` entry, and reads `name@` with an exact
28
- // version as converging: a dependency on `name` whose range takes that
29
- // version is given it, where no other override is chosen. It refuses one
30
- // with a parent and an empty range, and one whose version is not exact.
1
+ // Overrides as pnpm's parseOverrides reads them. A frozen install holds them
2
+ // only to the lockfile's `overrides`, which they were resolved with. pnpm 11
3
+ // reads `name@` and an exact version as converging: a dependency on `name`
4
+ // whose range takes that version is given it where no override is chosen.
31
5
 
32
6
  import { valid } from '@preventive/upstream/semver.js'
33
7
  import { join } from '@preventive/vfs/path.js'
34
8
  import { DeptreeError, quote } from '../error.js'
35
9
 
36
- // validate-npm-package-name 5's validForOldPackages, which pnpm reads a
37
- // selector's name by: what npm ever took as a name.
10
+ // From validate-npm-package-name 5, by which pnpm reads a selector's name.
38
11
  const SCOPED = /^(?:@([^/]+?)\/)?([^/]+?)$/u
39
12
  export function validForOldPackages(name) {
40
13
  if (name === '' || name.startsWith('.') || name.startsWith('_') || name.trim() !== name) return false
@@ -44,29 +17,25 @@ export function validForOldPackages(name) {
44
17
  return m !== null && encodeURIComponent(m[1]) === m[1] && encodeURIComponent(m[2]) === m[2]
45
18
  }
46
19
 
47
- // @pnpm/parse-wanted-dependency: a name, where what comes before the first
48
- // `@` past the start is one, then what follows it.
20
+ // @pnpm/parse-wanted-dependency.
49
21
  function parseWanted(raw) {
50
22
  const at = raw.indexOf('@', 1)
51
23
  const name = at === -1 ? raw : raw.slice(0, at)
52
24
  return validForOldPackages(name) ? { name, range: at === -1 ? undefined : raw.slice(at + 1) } : undefined
53
25
  }
54
26
 
55
- // A `>` after anything but a space, `|` or `@` splits the parent from the
56
- // package, as pnpm's DELIMITER_REGEX has it; `foo@>1` is one package.
27
+ // pnpm's DELIMITER_REGEX: `foo@>1` is one package, `bar@2>foo@1` two.
57
28
  const DELIMITER = /[^ @|]>/u
58
29
 
59
30
  export function parseSelector(selector, where) {
60
31
  if (!selector.isWellFormed()) throw new DeptreeError(`pnpm cannot parse the selector ${quote(selector)}`, where)
61
32
  const split = selector.search(DELIMITER)
62
- const parts = split === -1 ? [selector] : [selector.slice(0, split + 1), selector.slice(split + 2)]
63
- const parsed = parts.map(parseWanted)
33
+ const parsed = (split === -1 ? [selector] : [selector.slice(0, split + 1), selector.slice(split + 2)]).map(parseWanted)
64
34
  if (parsed.includes(undefined)) throw new DeptreeError(`pnpm cannot parse the selector ${quote(selector)}`, where)
65
35
  return parsed.length === 1 ? { target: parsed[0] } : { parent: parsed[0], target: parsed[1] }
66
36
  }
67
37
 
68
- // A layer's overrides with each `$name` replaced; `manifest` is the root
69
- // package.json as parsed.
38
+ // A layer's overrides with each `$name` replaced from the root package.json.
70
39
  export function replaceReferences(overrides, manifest, where) {
71
40
  const own = { ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }
72
41
  const replaced = Object.create(null)
@@ -82,15 +51,11 @@ export function replaceReferences(overrides, manifest, where) {
82
51
 
83
52
  const CATALOG = 'catalog:'
84
53
 
85
- // The catalog a `catalog:` specifier names, `default` where it names none,
86
- // or undefined for another specifier.
87
54
  export const catalogOf = (spec) => (spec.startsWith(CATALOG) ? spec.slice(CATALOG.length).trim() || 'default' : undefined)
88
55
 
89
- // The entry catalog `catalog` of `catalogs` has for `name`, if any.
90
56
  export const catalogEntry = (catalogs, catalog, name) => (Object.hasOwn(catalogs, catalog) && Object.hasOwn(catalogs[catalog], name) ? catalogs[catalog][name] : undefined)
91
57
 
92
- // @pnpm/catalogs.resolver's resolveFromCatalog: the specifier a catalog
93
- // gives `name`, where `spec` asks for one.
58
+ // @pnpm/catalogs.resolver's resolveFromCatalog.
94
59
  function fromCatalog(catalogs, spec, name, where, major) {
95
60
  const catalog = catalogOf(spec)
96
61
  if (catalog === undefined) return spec
@@ -103,8 +68,7 @@ function fromCatalog(catalogs, spec, name, where, major) {
103
68
  return found
104
69
  }
105
70
 
106
- // The directory an override names, as pnpm's local resolver reads a
107
- // specifier, and by which protocol, or undefined for one that is none.
71
+ // As pnpm's local resolver reads a specifier.
108
72
  export function localOf(spec, where) {
109
73
  const protocol = ['file:', 'link:'].find((prefix) => spec.startsWith(prefix)) ?? (/^(?:[./]|~\/)/u.test(spec) ? '' : undefined)
110
74
  if (protocol === undefined) return undefined
@@ -114,10 +78,6 @@ export function localOf(spec, where) {
114
78
  return { protocol, dir }
115
79
  }
116
80
 
117
- // The overrides pnpm installs with, in order, as its parseOverrides has
118
- // them: each selector parsed, and its specifier with any catalog resolved,
119
- // and `local` the directory it names, where it names one. By selector,
120
- // they are what the lockfile's `overrides` is held to.
121
81
  export function listOverrides(overrides, catalogs, major = 10) {
122
82
  const seen = new Set()
123
83
  return Object.entries(overrides ?? {}).map(([raw, given]) => {
@@ -0,0 +1,121 @@
1
+ // A registry package as pnpm installs it: its tarball read as @pnpm/store.cafs
2
+ // reads it, and held to what npm packs, more than pnpm holds it to. A
3
+ // dependency the lockfile left out of a snapshot would leave the package to
4
+ // find it wherever it is hoisted, if anywhere.
5
+
6
+ import { normalize } from '@preventive/vfs/path.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { checkNesting } from '../manifest.js'
9
+ import { isInside } from '../mount.js'
10
+ import { fetchTarball, sameFile } from '../tarball.js'
11
+ import { localOf } from './overrides.js'
12
+
13
+ function nameOf(stored) {
14
+ const slash = stored.indexOf('/')
15
+ let name = slash === -1 ? stored : stored.slice(slash + 1)
16
+ if (name.includes('./')) name = normalize(`/${name}`).slice(1)
17
+ return name.replaceAll('//', '/')
18
+ }
19
+
20
+ // pnpm 9, 10 and 11 drop a name's first segment at a `\` as at a `/` where the
21
+ // ustar header holds the name, and pnpm 10 and 11, where a name has a `.\`,
22
+ // turn each `\` into a `/` before normalizing it; pnpm 12 takes every `\` for
23
+ // a separator, and fails on a `..` that makes.
24
+ function filesOf(entries, where) {
25
+ const files = new Map()
26
+ const tops = new Set()
27
+ for (const entry of entries) {
28
+ if (entry.storedName.includes('\\')) throw new DeptreeError(`${quote(entry.storedName)} has a backslash, which pnpm may take for a separator, and that is not supported`, where)
29
+ if (entry.type === 'directory') continue
30
+ if (entry.type !== 'file') throw new DeptreeError(`${quote(entry.name)} is a ${entry.type}, which is not supported`, where)
31
+ tops.add(entry.storedName.slice(0, Math.max(entry.storedName.indexOf('/'), 0)))
32
+ if (tops.size > 1 || tops.has('')) throw new DeptreeError('the tarball has files under more than one directory, or at its top', where)
33
+ const name = nameOf(entry.storedName)
34
+ if (!isInside(name)) {
35
+ throw new DeptreeError(`${quote(entry.storedName)} names no file in the package`, where)
36
+ }
37
+ const file = { data: entry.data, mode: (entry.mode & 0o111) === 0 ? 0o644 : 0o755 }
38
+ const earlier = files.get(name)
39
+ if (earlier !== undefined && !sameFile(earlier, file)) throw new DeptreeError(`${quote(name)} is in the tarball twice`, where)
40
+ files.set(name, file)
41
+ }
42
+ return files
43
+ }
44
+
45
+ const decoder = new TextDecoder('utf-8', { fatal: true })
46
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
47
+ const names = (value) => Object.keys(value ?? {})
48
+
49
+ // Undefined where `bin` names none beside a directories.bin: pnpm resolves that
50
+ // as having no bins and pnpm 11 rewrites a snapshot as having some, so bins are
51
+ // linked as the lockfile has it.
52
+ function hasBin({ bin, directories }, major) {
53
+ if (major >= 12) {
54
+ const named = typeof bin === 'string' ? bin !== '' : bin !== null && typeof bin === 'object' && !Array.isArray(bin) && Object.keys(bin).length > 0
55
+ return named || (directories !== null && typeof directories === 'object' && !Array.isArray(directories) && typeof directories.bin === 'string' && directories.bin !== '')
56
+ }
57
+ if (bin == null) return Boolean(directories?.bin)
58
+ if (bin && Object.keys(bin).length > 0) return true
59
+ return directories?.bin ? undefined : false
60
+ }
61
+
62
+ function readManifest(files, pkg, where) {
63
+ const file = files.get('package.json')
64
+ if (file === undefined) throw new DeptreeError('the tarball has no package.json', where)
65
+ let manifest
66
+ try {
67
+ manifest = JSON.parse(decoder.decode(file.data))
68
+ } catch {
69
+ throw new DeptreeError('package.json is not JSON', where)
70
+ }
71
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('package.json is not an object', where)
72
+ checkNesting(manifest, `${where}: package.json`)
73
+ if (manifest.name !== pkg.name || manifest.version !== pkg.version) throw new DeptreeError(`package.json is for ${quote(`${manifest.name}@${manifest.version}`)}`, where)
74
+ return manifest
75
+ }
76
+
77
+ export function checkManifest(manifest, pkg, where, major) {
78
+ for (const field of ['os', 'cpu', 'libc']) {
79
+ if (!same(manifest[field], pkg[field])) throw new DeptreeError(`package.json's ${field} is not the lockfile's`, where)
80
+ }
81
+ const has = hasBin(manifest, major)
82
+ 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)
83
+ if (!same(listed(bundledOf(manifest)), listed(pkg.bundledDependencies))) throw new DeptreeError('package.json bundles other than the lockfile says', where)
84
+ }
85
+
86
+ const bundledOf = (manifest) => manifest.bundleDependencies ?? manifest.bundledDependencies
87
+
88
+ // pnpm 10 writes an empty list of bundled dependencies, pnpm 11 none.
89
+ const listed = (bundled) => (Array.isArray(bundled) && bundled.length === 0 ? undefined : bundled)
90
+
91
+ // `read` is the package.json as hook.js's hook has it, and `packages` the
92
+ // lockfile's, by which a `file:` target is the directory it resolves to.
93
+ export function checkDependencies(manifest, read, pkg, packages, where) {
94
+ const bundled = bundledOf(manifest)
95
+ const given = new Set([...names(pkg.dependencies), ...names(pkg.optionalDependencies)])
96
+ for (const name of [...names(read.dependencies), ...names(read.optionalDependencies)]) {
97
+ if (bundled === true || (Array.isArray(bundled) && bundled.includes(name)) || given.has(name)) continue
98
+ throw new DeptreeError(`package.json asks for ${quote(name)}, which the lockfile does not give it`, where)
99
+ }
100
+ for (const [name, spec] of [...Object.entries(read.dependencies ?? {}), ...Object.entries(read.optionalDependencies ?? {})]) {
101
+ const target = pkg.dependencies[name] ?? pkg.optionalDependencies[name]
102
+ if (target === undefined) continue
103
+ const local = localOf(spec, `${where}: package.json`)
104
+ if (local === undefined || target === `link:${local.dir}` || (local.protocol === 'file:' && packages[target]?.resolution.directory === local.dir)) continue
105
+ throw new DeptreeError(`the lockfile gives it ${quote(name)} as ${quote(target)}, and its package.json, overridden, names ${quote(local.dir)}`, where)
106
+ }
107
+ // A resolved optional peer is filed as optional, and pnpm's compatibility
108
+ // database adds peers to a few packages that their package.json lacks.
109
+ const optional = new Set([...names(read.optionalDependencies), ...names(manifest.peerDependencies), ...names(manifest.peerDependenciesMeta), ...names(pkg.peerDependencies), ...names(pkg.peerDependenciesMeta)])
110
+ for (const name of names(pkg.optionalDependencies)) {
111
+ if (!optional.has(name)) throw new DeptreeError(`the lockfile gives it ${quote(name)} as optional, which its package.json does not`, where)
112
+ }
113
+ }
114
+
115
+ export async function fetchPackage(pkg, where, major) {
116
+ const { entries } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where)
117
+ const files = filesOf(entries, where)
118
+ const manifest = readManifest(files, pkg, where)
119
+ checkManifest(manifest, pkg, where, major)
120
+ return { files, manifest }
121
+ }