@preventive/deptree 1.0.0-alpha.0

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,213 @@
1
+ // What pnpm 11's frozen install holds each project to beyond what pnpm
2
+ // 10's does (@pnpm/lockfile.verification): specifiers that name one git
3
+ // repository and commit alike are the same; a catalog dependency has to
4
+ // have resolved to the version the lockfile's catalog records; and a
5
+ // dependency on a workspace package has to be linked exactly where the
6
+ // package's version is in its range — which pnpm 10 checks only when it
7
+ // resolves.
8
+
9
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
10
+ import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
11
+ import { join, normalize } from '@preventive/vfs/path.js'
12
+ import { DeptreeError, quote } from '../error.js'
13
+
14
+ const GIT_HOSTS = new Set(['github.com', 'gitlab.com', 'bitbucket.org'])
15
+ const SHORTCUTS = [['github:', 'github.com'], ['gitlab:', 'gitlab.com'], ['bitbucket:', 'bitbucket.org']]
16
+
17
+ function gitUrl(host, path, committish) {
18
+ if (path === '' || path.includes('@') || path.includes('?') || /\s/u.test(path) || path.split('/').includes('')) return undefined
19
+ const repository = path.endsWith('.git') ? path.slice(0, -4) : path
20
+ if (repository === '' || repository.endsWith('/')) return undefined
21
+ return `git+https://${host}/${repository}.git${committish ? `#${committish}` : ''}`
22
+ }
23
+
24
+ // A git specifier as one URL, as gitSpecifiersAreEquivalent spells it, or
25
+ // undefined for one that is not.
26
+ function gitSpecifier(specifier) {
27
+ const hash = specifier.indexOf('#')
28
+ const committish = hash === -1 ? undefined : specifier.slice(hash + 1)
29
+ if (committish?.includes('#')) return undefined
30
+ const repository = hash === -1 ? specifier : specifier.slice(0, hash)
31
+ const shortcut = SHORTCUTS.find(([prefix]) => repository.startsWith(prefix))
32
+ let found
33
+ if (shortcut !== undefined) found = gitUrl(shortcut[1], repository.slice(shortcut[0].length), committish)
34
+ else if (!repository.startsWith('.') && !/[\s:@]/u.test(repository) && repository.split('/').length === 2) found = gitUrl('github.com', repository, committish)
35
+ if (found !== undefined) return found
36
+ const schemeEnd = repository.indexOf('://')
37
+ if (schemeEnd === -1) return undefined
38
+ const scheme = repository.slice(0, schemeEnd).toLowerCase()
39
+ if (scheme !== 'git' && scheme !== 'git+https' && scheme !== 'https') return undefined
40
+ const location = repository.slice(schemeEnd + 3)
41
+ const slash = location.indexOf('/')
42
+ if (slash === -1) return undefined
43
+ const host = location.slice(0, slash).toLowerCase()
44
+ const path = location.slice(slash + 1)
45
+ if (host === '' || /[\s?@]/u.test(host) || (scheme === 'https' && !GIT_HOSTS.has(host) && !path.endsWith('.git'))) return undefined
46
+ return gitUrl(host, path, committish)
47
+ }
48
+
49
+ // dependencySpecifiersAreEqual: pnpm 11 takes two specifiers of one git
50
+ // repository and commit, however spelled, to be the same; pnpm 10 only
51
+ // two spelled the same.
52
+ export function sameSpecifier(a, b, major) {
53
+ if (a === b) return true
54
+ if (major < 11 || a === undefined || b === undefined) return false
55
+ const git = gitSpecifier(a)
56
+ return git !== undefined && git === gitSpecifier(b)
57
+ }
58
+
59
+ // The version an importer's target resolved to, as the lockfile spells
60
+ // it: a key of the alias's own name is its version and peers.
61
+ export const refOf = (alias, target) => (target.startsWith(`${alias}@`) ? target.slice(alias.length + 1) : target)
62
+
63
+ const targetOf = (importer, alias) => importer.dependencies[alias] ?? importer.devDependencies[alias] ?? importer.optionalDependencies[alias]
64
+
65
+ // catalogResolutionsAreUpToDate.
66
+ export function checkCatalogResolutions(importer, catalogs, where) {
67
+ for (const [alias, specifier] of Object.entries(importer.specifiers)) {
68
+ if (!specifier.startsWith('catalog:')) continue
69
+ const name = specifier.slice('catalog:'.length).trim() || 'default'
70
+ const version = Object.hasOwn(catalogs, name) && Object.hasOwn(catalogs[name], alias) ? catalogs[name][alias].version : undefined
71
+ const target = targetOf(importer, alias)
72
+ if (version === undefined || target === undefined) continue
73
+ const resolved = packageKeyOf(refOf(alias, target))
74
+ if (valid(resolved) !== null && resolved !== version) throw new DeptreeError(`${quote(alias)} resolved to ${quote(resolved)}, and the lockfile's catalog ${quote(name)} to ${quote(version)}, which pnpm 11 refuses a frozen install for`, where)
75
+ }
76
+ }
77
+
78
+ // A path pnpm resolves from a directory, `./` and all, relative to the
79
+ // lockfile's directory as the lockfile's links are; one from the home
80
+ // directory or the root cannot be told here.
81
+ function specPath(dir, path, where) {
82
+ const clean = path.startsWith('./') ? path.slice(2) : path
83
+ if (/^(?:~[/\\]|[/\\]|[A-Za-z]:)/u.test(clean) || clean.includes('\\')) throw new DeptreeError(`${quote(path)} is not a path from the project, which is not supported`, where)
84
+ return normalize(join(dir, clean.replace(/\/+$/u, '')))
85
+ }
86
+
87
+ const isWorkspacePath = (spec) => /^(?:[./\\]|~[/\\]|[A-Za-z]:)/u.test(spec)
88
+ // Of two paths in the lockfile's normal form, whether one is the other or
89
+ // in it.
90
+ const within = (parent, child) => child === parent || (parent === '.' ? child !== '..' && !child.startsWith('../') : child.startsWith(`${parent}/`))
91
+
92
+ function targetName(spec, alias) {
93
+ if (spec.startsWith('workspace:')) {
94
+ const raw = spec.slice('workspace:'.length)
95
+ const at = raw.lastIndexOf('@')
96
+ return isWorkspacePath(raw) || at <= 0 ? alias : raw.slice(0, at)
97
+ }
98
+ if (spec.startsWith('npm:')) {
99
+ const raw = spec.slice('npm:'.length)
100
+ if (validRange(raw) !== null) return alias
101
+ const at = raw.lastIndexOf('@')
102
+ return at > 0 ? raw.slice(0, at) : raw
103
+ }
104
+ return alias
105
+ }
106
+
107
+ function versionRange(spec) {
108
+ if (spec.startsWith('workspace:')) {
109
+ const raw = spec.slice('workspace:'.length)
110
+ const at = raw.lastIndexOf('@')
111
+ return at > 0 ? raw.slice(at + 1) || '*' : raw
112
+ }
113
+ if (spec.startsWith('npm:')) {
114
+ const raw = spec.slice('npm:'.length)
115
+ if (validRange(raw) !== null) return raw
116
+ const at = raw.indexOf('@', 1)
117
+ return at === -1 ? '*' : raw.slice(at + 1) || '*'
118
+ }
119
+ return spec
120
+ }
121
+
122
+ const inRange = (version, range) => range === '*' || range === '^' || range === '~' || (typeof version === 'string' && satisfies(version, range, { loose: true }))
123
+
124
+ // version-selector-type's tag: a name that is no version or range.
125
+ const isTag = (range) => valid(range, { loose: true }) === null && validRange(range, { loose: true }) === null && encodeURIComponent(range) === range
126
+
127
+ const KINDS = ['optionalDependencies', 'dependencies', 'devDependencies']
128
+
129
+ // The directory a specifier names, where it names one: by `link:`,
130
+ // `file:`, a `workspace:` path, or a path alone, as pnpm reads one. One
131
+ // led by a backslash, a path to pnpm on Windows alone, is taken for one
132
+ // too, for specPath to refuse, as a lockfile pnpm writes elsewhere never
133
+ // links it.
134
+ function pathOf(spec) {
135
+ if (spec.startsWith('link:') || spec.startsWith('file:')) return spec.slice(5)
136
+ if (spec.startsWith('workspace:')) return isWorkspacePath(spec.slice('workspace:'.length)) ? spec.slice('workspace:'.length) : undefined
137
+ return /^(?:[./\\]|~[/\\]|[a-z]:)/iu.test(spec) ? spec : undefined
138
+ }
139
+
140
+ // A dependency the lockfile links has to be linked where the project's
141
+ // package.json, read through the read-package hook, names a directory for
142
+ // it, as a lockfile pnpm writes always has it: pnpm 11 holds a `link:` or
143
+ // `workspace:` path to that, and pnpm 10, or pnpm 11 a path alone, would
144
+ // link whatever the lockfile says. A `file:` one is pnpm's to link, where
145
+ // it does.
146
+ export function checkLinkTargets({ id, manifest, importer }, where) {
147
+ for (const kind of KINDS) {
148
+ for (const [alias, target] of Object.entries(importer[kind])) {
149
+ const spec = manifest[kind]?.[alias]
150
+ if (!spec || !target.startsWith('link:') || importer.specifiers[alias].startsWith('file:')) continue
151
+ const path = pathOf(spec)
152
+ const linkedTo = target.slice('link:'.length)
153
+ if (path !== undefined && specPath(id, path, `${where}.${kind}.${alias}`) !== linkedTo) {
154
+ throw new DeptreeError(`the lockfile is not up to date with this package.json, which a frozen install refuses: ${alias} is linked to ${quote(linkedTo)}, which is not where ${quote(spec)} leads`, where)
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ // checkLinkedPackagesAreUpToDate, for the project at `id`, less the
161
+ // directories a package.json names, which checkLinkTargets holds links to:
162
+ // `manifest` is its package.json as read through the read-package hook,
163
+ // `projects` every project's by its directory, as given, and
164
+ // `linkWorkspacePackages` the setting.
165
+ export function checkLinkedPackages({ manifest, importer, projects, linkWorkspacePackages }, where) {
166
+ const byName = new Map()
167
+ const byDir = new Map()
168
+ for (const [dir, project] of projects) {
169
+ byDir.set(dir, project)
170
+ const directory = project.publishConfig?.directory
171
+ if (typeof directory === 'string' && project.publishConfig.linkDirectory !== false) byDir.set(normalize(join(dir, directory)), project)
172
+ if (!project.name) continue
173
+ if (!byName.has(project.name)) byName.set(project.name, new Map())
174
+ const version = project.version ?? '0.0.0'
175
+ if (byName.get(project.name).has(version)) throw new DeptreeError(`${quote(String(project.name))} at ${quote(String(version))} is another project's name and version too, which leaves which pnpm 11 checks a dependency against to the order it finds them in`, `manifests[${quote(dir)}]`)
176
+ byName.get(project.name).set(version, dir)
177
+ }
178
+ const outdated = (detail) => new DeptreeError(`the lockfile is not up to date with this package.json, which pnpm 11 refuses a frozen install for: ${detail}`, where)
179
+ for (const kind of KINDS) {
180
+ const wanted = manifest[kind]
181
+ if (wanted == null) continue
182
+ for (const [alias, target] of Object.entries(importer[kind])) {
183
+ const spec = wanted[alias]
184
+ if (!spec) continue
185
+ const here = `${where}.${kind}.${alias}`
186
+ const workspaceRange = spec.startsWith('workspace:') && !isWorkspacePath(spec.slice('workspace:'.length))
187
+ const linked = target.startsWith('link:')
188
+ const local = importer.specifiers[alias].startsWith('file:') || packageKeyOf(target).includes('@file:')
189
+ if (local && !linked) throw new DeptreeError('a dependency on a local directory or tarball is not supported', here)
190
+ if (local) continue
191
+ if (linked && pathOf(spec) !== undefined) continue
192
+ const name = targetName(spec, alias)
193
+ const range = versionRange(spec)
194
+ if (linked && isTag(range)) continue
195
+ const named = byName.get(name)
196
+ const dir = linked ? target.slice('link:'.length) : named?.get(packageKeyOf(refOf(alias, target)))
197
+ if (dir === undefined) {
198
+ const taking = workspaceRange && named !== undefined ? [...named.keys()].find((version) => inRange(projects.get(named.get(version)).version, range)) : undefined
199
+ if (taking !== undefined) throw outdated(`the workspace package ${quote(name)} (${taking}) is in the range ${quote(spec)} and not linked`)
200
+ continue
201
+ }
202
+ if (!linkWorkspacePackages && !spec.startsWith('workspace:')) continue
203
+ if (linked && workspaceRange && named !== undefined && ![...named.values()].some((root) => within(root, dir))) {
204
+ throw outdated(`${alias} is linked to ${quote(dir)}, which is in no workspace package named ${quote(name)}`)
205
+ }
206
+ if (!byDir.has(dir)) throw new DeptreeError(`it is linked to ${quote(dir)}, which is no project, and whose package.json pnpm 11 reads`, here)
207
+ const { version } = byDir.get(dir)
208
+ if (linked !== inRange(version, range)) {
209
+ throw outdated(linked ? `the linked workspace package ${alias} (${version ?? 'unknown'}) is not in the range ${quote(spec)}` : `the workspace package ${alias} (${version ?? 'unknown'}) is in the range ${quote(spec)} and not linked`)
210
+ }
211
+ }
212
+ }
213
+ }
@@ -0,0 +1,54 @@
1
+ // The graph a pnpm 10 install links, as @pnpm/deps.graph-builder builds it
2
+ // from a frozen lockfile: a node for each snapshot installed, at
3
+ // node_modules/.pnpm/<its directory>/node_modules/<its name>, with its
4
+ // dependencies and optional dependencies as children by alias; and, for
5
+ // each project, its direct dependencies by alias. A child left out of the
6
+ // install is left out of its parent's children too. A `link:` child is the
7
+ // directory it names, which is no node. Paths here are relative to the
8
+ // lockfile's directory, the root of the tree.
9
+
10
+ import { DeptreeError, quote } from '../error.js'
11
+ import { depPathToFilename } from './filename.js'
12
+
13
+ const VIRTUAL_STORE = 'node_modules/.pnpm'
14
+
15
+ // A target as a path: a node's directory, or where a link leads, which
16
+ // may climb out of the lockfile's directory.
17
+ function childOf(target, nodes, skipped) {
18
+ if (target.startsWith('link:')) return target.slice(5)
19
+ if (skipped.has(target)) return undefined
20
+ return nodes.get(target).dir
21
+ }
22
+
23
+ function childrenOf(targets, nodes, skipped) {
24
+ const children = new Map()
25
+ for (const [alias, target] of Object.entries(targets)) {
26
+ const dir = childOf(target, nodes, skipped)
27
+ if (dir !== undefined) children.set(alias, dir)
28
+ }
29
+ return children
30
+ }
31
+
32
+ // `nodes` by snapshot key, and `direct`, by project, the children each
33
+ // project links: devDependencies first, as pnpm spreads them, which is
34
+ // the order hoisting walks them in.
35
+ export async function buildGraph(lockfile, skipped, maxLength, major = 10) {
36
+ const nodes = new Map()
37
+ const keyByDir = new Map()
38
+ for (const [key, pkg] of Object.entries(lockfile.packages)) {
39
+ if (skipped.has(key)) continue
40
+ const store = `${VIRTUAL_STORE}/${await depPathToFilename(key, maxLength, major)}`
41
+ const dir = `${store}/node_modules/${pkg.name}`
42
+ if (keyByDir.has(dir)) throw new DeptreeError(`${quote(keyByDir.get(dir))} and ${quote(key)} would be installed in one directory`, quote(dir))
43
+ keyByDir.set(dir, key)
44
+ nodes.set(key, { key, pkg, name: pkg.name, dir, modules: `${store}/node_modules` })
45
+ }
46
+ for (const node of nodes.values()) {
47
+ node.children = childrenOf({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }, nodes, skipped)
48
+ }
49
+ const direct = new Map()
50
+ for (const [id, importer] of Object.entries(lockfile.importers)) {
51
+ direct.set(id, childrenOf({ ...importer.devDependencies, ...importer.dependencies, ...importer.optionalDependencies }, nodes, skipped))
52
+ }
53
+ return { nodes, direct }
54
+ }
@@ -0,0 +1,109 @@
1
+ // Hoisting as pnpm 10 does it (@pnpm/hoist): every alias in the graph a
2
+ // pattern matches gets a link to what it names, in node_modules/.pnpm/
3
+ // node_modules for the private pattern and in the root node_modules for
4
+ // the public one, which wins where both match. The first to take an alias
5
+ // keeps it, and the order is pnpm's: the projects' direct dependencies
6
+ // first, then the graph by depth, a node's depth being where pnpm's walk
7
+ // first reaches it, and nodes of one depth in the order of their
8
+ // directories. An alias is taken with its case folded, and the root
9
+ // project's own aliases are taken before anything, as they were spelled.
10
+
11
+ import { createMatcher } from '../matcher.js'
12
+
13
+ // pnpm's graphWalker and getDependencies: one level at a time, but each
14
+ // level's next is walked out to the bottom before the level's second
15
+ // node's next is, so a node's depth is where that walk first reaches it,
16
+ // which is not always the least.
17
+ function walk(nodes, starts) {
18
+ const visited = new Set()
19
+ const step = (dirs) => {
20
+ const found = []
21
+ for (const dir of dirs) {
22
+ if (visited.has(dir)) continue
23
+ visited.add(dir)
24
+ const node = nodes.get(dir)
25
+ if (node !== undefined) found.push(node)
26
+ }
27
+ return found
28
+ }
29
+ const levels = (depth, found) => {
30
+ const listed = found.map((node) => ({ node, depth }))
31
+ const next = found.map((node) => step(node.children.values()))
32
+ return [...listed, ...next.flatMap((level) => levels(depth + 1, level))]
33
+ }
34
+ return levels(0, step(starts))
35
+ }
36
+
37
+ // UTF-16 order, as pnpm's lexCompare has it.
38
+ const lexCompare = (a, b) => (a > b ? 1 : a < b ? -1 : 0)
39
+
40
+ // The aliases hoisted from the graph, walked from `starts`: a Map of each
41
+ // link's path to its target. `taken` holds the names, folded, that none
42
+ // may be hoisted by: the root project's own aliases, and, with pnpm 10,
43
+ // with `projects` named among them at the top, hoisted last.
44
+ function hoistGraph(nodes, starts, taken, typeOf, projects = new Map()) {
45
+ const root = new Map([...projects].map(([id, name]) => [name, { project: id }]))
46
+ const listed = new Set()
47
+ for (const [alias, dir] of starts) {
48
+ if (listed.has(alias)) continue
49
+ listed.add(alias)
50
+ root.set(alias, dir)
51
+ }
52
+ const order = [
53
+ { children: root, dir: '', depth: -1 },
54
+ ...walk(nodes, starts.map(([, dir]) => dir)).map(({ node, depth }) => ({ children: node.children, dir: node.dir, depth })),
55
+ ]
56
+ order.sort((a, b) => a.depth - b.depth || lexCompare(a.dir, b.dir))
57
+ const links = new Map()
58
+ const hoistedProjects = new Map()
59
+ for (const { children } of order) {
60
+ for (const [alias, dir] of children) {
61
+ const where = typeOf(alias)
62
+ if (where === undefined || taken.has(alias.toLowerCase())) continue
63
+ if (typeof dir === 'object') hoistedProjects.set(`${where}/${alias}`, dir.project)
64
+ else if (nodes.has(dir)) {
65
+ taken.add(alias.toLowerCase())
66
+ links.set(`${where}/${alias}`, dir)
67
+ }
68
+ }
69
+ }
70
+ for (const [path, dir] of hoistedProjects) links.set(path, dir)
71
+ return links
72
+ }
73
+
74
+ // Where each hoisted alias is linked, and to which directory: a Map of
75
+ // the link's path to its target, both relative to the lockfile's
76
+ // directory. `nodes` is the graph by directory; `direct` its projects'
77
+ // direct dependencies, the root project's under `.`; `projects` the
78
+ // workspace's named projects by directory, where hoistWorkspacePackages
79
+ // has them hoisted by name too.
80
+ //
81
+ // pnpm 10 puts those names first among the root's, a direct dependency of
82
+ // one name replacing it. Hoisting a project does not take its name, so a
83
+ // package of that name may be hoisted to the same place too; there the
84
+ // project wins, as pnpm replaces a link into the store with it and leaves
85
+ // its own in place of one. It takes the root project's aliases as they are
86
+ // spelled, and folds the case of those it hoists.
87
+ //
88
+ // pnpm 11 folds the root project's aliases too. It hoists the graph, then
89
+ // each project by its name where no project's direct dependency in the
90
+ // graph has that name, and then the graph again with those names taken
91
+ // from it; a project hoisted is not held back by a `link:` of its name, or
92
+ // by a package hoisted by it. (It holds back two projects of which one's
93
+ // name is a directory of the other's, which no two names a package can
94
+ // have are.)
95
+ export function hoist(nodes, direct, { hoistPattern, publicHoistPattern }, projects = new Map(), major = 10) {
96
+ if (hoistPattern === undefined && publicHoistPattern === undefined) return new Map()
97
+ const isPublic = createMatcher(publicHoistPattern ?? [])
98
+ const isPrivate = createMatcher(hoistPattern ?? [])
99
+ const typeOf = (alias) => (isPublic(alias) ? 'node_modules' : isPrivate(alias) ? 'node_modules/.pnpm/node_modules' : undefined)
100
+ const starts = [...direct.values()].flatMap((children) => [...children].filter(([, dir]) => nodes.has(dir)))
101
+ const rootAliases = [...direct.get('.')?.keys() ?? []]
102
+ if (major < 11) return hoistGraph(nodes, starts, new Set(rootAliases), typeOf, projects)
103
+ const takenByDependencies = new Set(starts.map(([alias]) => alias.toLowerCase()))
104
+ const hoistedProjects = [...projects].filter(([, name]) => typeOf(name) !== undefined && !takenByDependencies.has(name.toLowerCase()))
105
+ const taken = new Set([...rootAliases, ...hoistedProjects.map(([, name]) => name)].map((alias) => alias.toLowerCase()))
106
+ const links = nodes.size === 0 ? new Map() : hoistGraph(nodes, starts, taken, typeOf)
107
+ for (const [id, name] of hoistedProjects) links.set(`${typeOf(name)}/${name}`, id)
108
+ return links
109
+ }
@@ -0,0 +1,106 @@
1
+ // What pnpm 10 makes of a package.json before it reads its dependencies:
2
+ // its read-package hook (@pnpm/hooks.read-package-hook), less what is
3
+ // refused elsewhere — package extensions and a pnpmfile's readPackage —
4
+ // and less Yarn's compatibility database, which adds dependencies to a few
5
+ // packages by name and is not reproduced. Overrides replace or, as `-`,
6
+ // remove what the package asks for (createVersionsOverrider), and
7
+ // ignoredOptionalDependencies removes the optional dependencies it names.
8
+ // pnpm runs it on every package it resolves and on every project's
9
+ // package.json before holding it to its importer, which is why a project
10
+ // overridden is recorded as overridden.
11
+ //
12
+ // An override to a directory, `link:` or `file:`, is written into a
13
+ // project relative to it, as pnpm writes it; pnpm 11 takes a path alone
14
+ // for one too, where pnpm 10 writes it as it is. pnpm 11 also converges
15
+ // where no override is chosen (overrides.js), and drops a peer's
16
+ // peerDependenciesMeta with the peer.
17
+
18
+ import { intersects, satisfies, validRange } from '@preventive/upstream/semver.js'
19
+ import { DeptreeError } from '../error.js'
20
+ import { createMatcher } from '../matcher.js'
21
+
22
+ const KINDS = ['dependencies', 'optionalDependencies', 'devDependencies']
23
+
24
+ // pnpm's isIntersectingRange: no range is any, one range is itself, and
25
+ // two ranges meet where some version is in both.
26
+ const meets = (range, spec) => !range || spec === range || (validRange(spec) !== null && validRange(range) !== null && intersects(spec, range))
27
+
28
+ // pickMostSpecificVersionOverride, with its own comparator and sort: the
29
+ // order it leaves overrides in is the one pnpm takes the first of.
30
+ const mostSpecific = (overrides) => overrides.sort((a, b) => (meets(b.target.range ?? '', a.target.range ?? '') ? -1 : 1))[0]
31
+
32
+ const isPeerRange = (spec) => validRange(spec) !== null || spec.includes('workspace:') || spec.includes('catalog:')
33
+
34
+ // A path from one directory under the lockfile's to another, both in
35
+ // their normal form.
36
+ function pathBetween(from, to) {
37
+ const a = from === '.' ? [] : from.split('/')
38
+ const b = to === '.' ? [] : to.split('/')
39
+ let shared = 0
40
+ while (shared < a.length && shared < b.length && a[shared] === b[shared]) shared++
41
+ return [...a.slice(shared).map(() => '..'), ...b.slice(shared)].join('/') || '.'
42
+ }
43
+
44
+ // An override to a directory, `local` as listOverrides has it, as pnpm
45
+ // writes it into the project at `dir`: relative to it.
46
+ function localSpec({ protocol, dir: to }, dir) {
47
+ const path = pathBetween(dir, to)
48
+ return protocol === '' && !path.startsWith('.') ? `./${path}` : `${protocol}${path}`
49
+ }
50
+
51
+ function checkFields(manifest, where) {
52
+ for (const kind of [...KINDS, 'peerDependencies']) {
53
+ const deps = manifest[kind]
54
+ if (deps === undefined) continue
55
+ if (deps === null || typeof deps !== 'object' || Array.isArray(deps) || Object.values(deps).some((spec) => typeof spec !== 'string')) {
56
+ throw new DeptreeError('expected a mapping of names to specifiers', `${where}.${kind}`)
57
+ }
58
+ }
59
+ }
60
+
61
+ // `overrides` is listOverrides's; `ignored` the ignoredOptionalDependencies
62
+ // patterns; `major` pnpm's major version. The hook hands back a changed
63
+ // copy of a package.json; `dir` is the directory of a project's, where an
64
+ // override to a path is written into it as pnpm writes it, and undefined
65
+ // for a package's, whose specifiers are not read.
66
+ export function createHook({ overrides, ignored, major = 10 }) {
67
+ const withParent = overrides.filter(({ parent }) => parent !== undefined)
68
+ const generic = overrides.filter(({ parent, converge }) => parent === undefined && !converge)
69
+ const converging = new Map(overrides.filter(({ converge }) => converge).map(({ target, spec }) => [target.name, spec]))
70
+ const isIgnored = ignored.length > 0 ? createMatcher(ignored) : undefined
71
+ return (manifest, where, { dir } = {}) => {
72
+ checkFields(manifest, where)
73
+ const copy = structuredClone(manifest)
74
+ if (overrides.length > 0) {
75
+ const scoped = withParent.filter(({ parent }) => parent.name === copy.name && (!parent.range || satisfies(copy.version, parent.range)))
76
+ const override = (deps, peers) => {
77
+ for (const [name, spec] of Object.entries(peers ?? deps)) {
78
+ const chosen = mostSpecific(scoped.filter(({ target }) => target.name === name && meets(target.range, spec)))
79
+ ?? mostSpecific(generic.filter(({ target }) => target.name === name && meets(target.range, spec)))
80
+ const version = converging.get(name)
81
+ if (chosen === undefined && version !== undefined && validRange(spec, { loose: true }) !== null && satisfies(version, spec, { loose: true })) (peers ?? deps)[name] = version
82
+ if (chosen === undefined) continue
83
+ if (chosen.spec === '-') {
84
+ delete (peers ?? deps)[name]
85
+ if (peers !== undefined && major >= 11) delete copy.peerDependenciesMeta?.[name]
86
+ continue
87
+ }
88
+ const { local } = chosen
89
+ const wanted = dir !== undefined && local !== undefined && (major >= 11 || local.protocol !== '') ? localSpec(local, dir) : chosen.spec
90
+ if (peers === undefined || !isPeerRange(wanted)) deps[name] = wanted
91
+ else peers[name] = wanted
92
+ }
93
+ }
94
+ for (const kind of KINDS) if (copy[kind] !== undefined) override(copy[kind])
95
+ if (copy.peerDependencies !== undefined) override(copy.dependencies ??= {}, copy.peerDependencies)
96
+ }
97
+ if (isIgnored !== undefined) {
98
+ for (const name of Object.keys(copy.optionalDependencies ?? {})) {
99
+ if (!isIgnored(name)) continue
100
+ delete copy.optionalDependencies[name]
101
+ delete copy.dependencies?.[name]
102
+ }
103
+ }
104
+ return copy
105
+ }
106
+ }