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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/npm.d.ts +288 -0
  3. package/npm.js +7 -0
  4. package/package.json +36 -10
  5. package/pnpm.d.ts +116 -22
  6. package/pnpm.js +2 -10
  7. package/soldeer.d.ts +13 -0
  8. package/soldeer.js +1 -7
  9. package/src/concurrent.js +16 -17
  10. package/src/error.js +5 -9
  11. package/src/glob.js +55 -0
  12. package/src/hash.js +64 -13
  13. package/src/manifest.js +52 -0
  14. package/src/matcher.js +59 -10
  15. package/src/mount.js +95 -44
  16. package/src/npm/bins.js +71 -0
  17. package/src/npm/compat.js +92 -0
  18. package/src/npm/dev-engines.js +52 -0
  19. package/src/npm/graph.js +68 -0
  20. package/src/npm/inputs.js +80 -0
  21. package/src/npm/manifests.js +138 -0
  22. package/src/npm/package.js +57 -0
  23. package/src/npm/ratio.js +34 -0
  24. package/src/npm/settings.js +67 -0
  25. package/src/npm/tree.js +136 -0
  26. package/src/npm/versions.js +20 -0
  27. package/src/{pnpm/npmrc.js → npmrc.js} +5 -11
  28. package/src/patch.js +21 -31
  29. package/src/pnpm/bins.js +32 -103
  30. package/src/pnpm/checks.js +8 -35
  31. package/src/pnpm/commands.js +49 -86
  32. package/src/pnpm/filename.js +10 -21
  33. package/src/pnpm/frozen.js +27 -70
  34. package/src/pnpm/gitignore.js +137 -0
  35. package/src/pnpm/glob.js +65 -0
  36. package/src/pnpm/graph.js +15 -43
  37. package/src/pnpm/hoist.js +65 -55
  38. package/src/pnpm/hook.js +26 -31
  39. package/src/pnpm/inputs.js +67 -40
  40. package/src/pnpm/install.js +72 -115
  41. package/src/pnpm/local.js +21 -40
  42. package/src/pnpm/minimatch.js +328 -0
  43. package/src/pnpm/npm-packlist.js +221 -0
  44. package/src/pnpm/overrides.js +10 -49
  45. package/src/pnpm/package.js +120 -0
  46. package/src/pnpm/packlist.js +168 -109
  47. package/src/pnpm/patches.js +18 -25
  48. package/src/pnpm/projects.js +63 -107
  49. package/src/pnpm/readers.js +46 -55
  50. package/src/pnpm/settings.js +60 -97
  51. package/src/pnpm/tree.js +134 -149
  52. package/src/pnpm/uptodate.js +16 -28
  53. package/src/pnpm/workspace.js +122 -131
  54. package/src/project.js +41 -0
  55. package/src/soldeer/config.js +8 -24
  56. package/src/soldeer/inputs.js +2 -5
  57. package/src/soldeer/tree.js +20 -56
  58. package/src/soldeer/zip.js +17 -36
  59. package/src/tarball.js +38 -142
  60. package/src/yarn1/bins.js +9 -19
  61. package/src/yarn1/compat.js +9 -28
  62. package/src/yarn1/hoist.js +53 -68
  63. package/src/yarn1/inputs.js +16 -51
  64. package/src/yarn1/manifest.js +8 -23
  65. package/src/yarn1/package.js +24 -63
  66. package/src/yarn1/peers.js +8 -15
  67. package/src/yarn1/requests.js +19 -37
  68. package/src/yarn1/resolve.js +35 -111
  69. package/src/yarn1/settings.js +14 -41
  70. package/src/yarn1/tree.js +67 -91
  71. package/yarn1.d.ts +30 -2
  72. package/yarn1.js +1 -8
  73. package/src/pnpm/project.js +0 -97
  74. package/src/yarn1/glob.js +0 -52
  75. /package/{LICENSE → LICENSE-MIT} +0 -0
package/pnpm.d.ts CHANGED
@@ -20,12 +20,12 @@ export { LockfileError, YamlError } from '@preventive/lockfile/pnpm.js'
20
20
  export { setCacheDir } from '@preventive/upstream/npm.js'
21
21
 
22
22
  // The machine pnpm would install on, which a tree depends on: `pnpm` is
23
- // the version that installs, and has to be a 10.x, an 11.x or a 12.x from
24
- // 12.8.1 on, the three built for, each as it differs from the others; an
25
- // earlier 12.x installs otherwise in places, and is refused. Left out, it
26
- // is the one
27
- // the root package.json's packageManager pins, which pnpm switches to, and
28
- // has to be given where that pins none. `node` is the Node it runs on,
23
+ // the version that installs, and has to be a 9.x from 9.15.0 on, a 10.x,
24
+ // an 11.x or a 12.x from 12.8.1 on, the four built for, each as it differs
25
+ // from the others; an earlier 9.x or 12.x installs otherwise in places, and
26
+ // is refused. Left out, it is the one the root package.json's
27
+ // packageManager pins, which pnpm switches to, and has to be given where
28
+ // that pins none. `node` is the Node it runs on,
29
29
  // unless the settings name a nodeVersion or, for pnpm 11, the root
30
30
  // package.json's engines.runtime pins one; `os`, `cpu` and `libc` as Node
31
31
  // and pnpm name them — `linux`, `x64`, `glibc` — with `unknown` for a libc
@@ -112,19 +112,45 @@ export interface PnpmProject {
112
112
  // is read only with `project` given, and only where the directory is
113
113
  // under the lockfile's and holds a package.json there. pnpm links to it by a
114
114
  // path alone or `link:`. By `file:` it installs it as a package, of the
115
- // files npm-packlist's built-in rules keep — with pnpm 12, its own port's
116
- // — which are followed here alone: a directory with a .npmignore or
117
- // .gitignore, a package.json with `files` or bundled dependencies, or a
118
- // link in it, is refused. pnpm hardlinks those files from the directory
119
- // into each snapshot of the package, so a file linking a bin makes
120
- // executable is made so in every snapshot and in the directory, which is
121
- // not written here; a CRLF `#!` line it rewrites is rewritten as a file of
122
- // that snapshot's own. Where it builds the package — an install script, a
115
+ // files its packlist picks — npm-packlist 5.1.3 for pnpm 9 and 10, 10.0.4
116
+ // for pnpm 11, and pnpm 12's own port of it — which each is followed here
117
+ // as that version runs: by package.json's `files`, `main`, `bin` and, but
118
+ // for pnpm 12, `browser`; by the .npmignore and .gitignore files where it
119
+ // reads them; and by its own rules, case and all, odd steps among them,
120
+ // such as pnpm 9 and 10 keeping what a `files` glob takes that their rules
121
+ // leave out, or the minimatch pnpm 10 bundles from 10.31 matching `**`
122
+ // otherwise. Of glob syntax only `*`, `?` and `**` are followed, which all
123
+ // read alike: a pattern with braces, a class, an extglob or a backslash is
124
+ // refused, and so are a link the walk comes on, bundled dependencies,
125
+ // `files` that is not a list of strings, a file kept by a path a pattern
126
+ // spells with a `.` part, and a package.json with a byte order mark for
127
+ // pnpm 11 before 11.28, which fails on it. Refused too, where a pnpm may
128
+ // make too large a regexp of it, failing for pnpm 9, 10 and 11 and dropping
129
+ // it unread for 12, is a pattern of more than 4096 characters and, for pnpm
130
+ // 12, an ignore file or `files` of more than 16 KiB; and so are a pattern
131
+ // with more than 100 `**` parts for pnpm 9 and 10, and a directory nested
132
+ // more than 100 deep, for the time matching them takes. Matching takes
133
+ // time linear in the path and the pattern. pnpm hardlinks those files from
134
+ // the directory into each snapshot of the package, so a file linking a bin
135
+ // makes executable is made so in every snapshot and in the directory, which
136
+ // is not written here; a CRLF `#!` line it rewrites is rewritten as a file
137
+ // of that snapshot's own. Where it builds the package — an install script, a
123
138
  // binding.gyp, which pnpm 11 and 12 pass over with `gypfile: false`, or a
124
139
  // .hooks directory — or, with pnpm 11 and 12, where packageImportMethod is
125
140
  // other than auto or hardlink, each snapshot has a copy of its own
126
141
  // instead. One by `file:` to a tarball is refused, and so is a `file:`
127
- // dependency no override names.
142
+ // dependency no override names. One to the lockfile's own directory that
143
+ // the lockfile has as `file:` and an empty path, as pnpm 9, 10 and 11
144
+ // write it, is refused for pnpm 12, which fails on that lockfile.
145
+ //
146
+ // pnpm 9 reads its settings as pnpm 10 does, but none of
147
+ // pnpm-workspace.yaml: of that it reads the projects and the catalogs
148
+ // alone, and fails on one that sets anything else but no `packages`, which
149
+ // is refused; where one sets nothing, it finds projects everywhere, as `**`
150
+ // does. Of the package.json's `pnpm` field it reads fewer keys, and what
151
+ // pnpm 10 has that pnpm 9 has no setting for, such as dedupePeers or
152
+ // enableGlobalVirtualStore, it passes over. It hoists `*eslint*` and
153
+ // `*prettier*` publicly by default.
128
154
  //
129
155
  // Of the .npmrc, only what pnpm reads for an install is read: its settings
130
156
  // by their kebab-case names, those that can change the tree held to what
@@ -180,7 +206,7 @@ export interface PnpmProject {
180
206
  // or is made, and every file and link is written where nothing is. The
181
207
  // tree is built, and held to every check below, before any of it is
182
208
  // written, so a refusal leaves the Vfs as it was. Nothing outside
183
- // node_modules is written, though pnpm 10 makes the files a linked
209
+ // node_modules is written, though pnpm 9 and 10 make the files a linked
184
210
  // directory's bins run executable too.
185
211
  //
186
212
  // The two ways the files come, one or the other: given, with `lockfile`
@@ -230,15 +256,45 @@ export interface PnpmTreeStats {
230
256
  links: number
231
257
  }
232
258
 
259
+ // A snapshot in the tree, as an SBOM would list it: `path` is where its
260
+ // files are, from the lockfile's directory, which is `/` of the Vfs —
261
+ // node_modules/.pnpm/<dir>/node_modules/<name>; `key` the lockfile's
262
+ // snapshot key, its peers and patch hash in it. `name` and `version` are
263
+ // the package's own, which its package.json is held to, and `integrity`
264
+ // the sha512 its tarball is held to; one a `file:` override has pnpm
265
+ // install from a directory has `directory`, from the lockfile's, `.` for
266
+ // its own, and neither a version nor an integrity, as the lockfile records
267
+ // none.
268
+ // `dev` is whether devDependencies alone reach it: no project's
269
+ // dependencies or optionalDependencies do, through what is installed, so
270
+ // `pnpm install --prod` would leave it out. `optional` is whether optional
271
+ // dependencies alone reach it, as the lockfile records it. `patch` is the
272
+ // patch applied to it, by pnpm's hash of it and the path the settings name
273
+ // it by: of two patches of one text, the first they name.
274
+ export interface PnpmInstalled {
275
+ path: string
276
+ key: string
277
+ name: string
278
+ version: string | undefined
279
+ integrity: string | undefined
280
+ directory: string | undefined
281
+ dev: boolean
282
+ optional: boolean
283
+ patch: { hash: string, path: string } | undefined
284
+ }
285
+
233
286
  // `vfs` is the one given, the tree mounted into it, or a new one.
287
+ // `installed` is each snapshot in the tree, one for each `stats.installed`
288
+ // counts, in the lockfile's order.
234
289
  export interface PnpmTree {
235
290
  vfs: Vfs
236
291
  stats: PnpmTreeStats
292
+ installed: PnpmInstalled[]
237
293
  }
238
294
 
239
295
  // The node_modules tree `pnpm install --frozen-lockfile --ignore-scripts`
240
- // makes with the isolated linker of host.pnpm, 10, 11 or 12, and no other
241
- // install: whatever the
296
+ // makes with the isolated linker of host.pnpm, 9, 10, 11 or 12, and no
297
+ // other install: whatever the
242
298
  // settings say of frozen lockfiles, the install is frozen, which is also
243
299
  // the only one that hoists by the lockfile's graph alone. It is rooted at
244
300
  // the lockfile's directory: each package's
@@ -256,6 +312,20 @@ export interface PnpmTree {
256
312
  // installs too, which is not followed here. Every file is written once,
257
313
  // and a write that would replace anything with something else is refused;
258
314
  // into a Vfs given, one that would replace anything at all.
315
+ //
316
+ // pnpm 9 makes its tree as pnpm 10 does but in places, each built as
317
+ // pnpm 9 makes it. It ends the name of a directory under
318
+ // node_modules/.pnpm it cuts short with 26 base32 characters of an MD5,
319
+ // not 32 hex of a SHA-256, and leaves a `#` in it. It hoists from the
320
+ // lockfile, not the graph: the snapshots of one depth in the order of
321
+ // their keys, not their directories', and an alias taken by a child left
322
+ // out, a `link:` or a project as well as by a snapshot hoisted, the root's
323
+ // all taken from the start as its specifiers spell them. It takes a bin's
324
+ // command by its name before it drops the scope, so links `@x/y z` as
325
+ // `y z`, and links a `bin` string, or a directories.bin, where it leads
326
+ // out of the package, which is refused; it fails on a bin that is a
327
+ // directory, which is refused, where pnpm 10 passes over it.
328
+ //
259
329
  // pnpm 11 links bins otherwise in places — npm owns `npx` and pnpm its
260
330
  // aliases, a project's .bin takes the bins of the peers its dependencies
261
331
  // require — and each is built as the one given links them.
@@ -312,6 +382,19 @@ export interface PnpmTree {
312
382
  // or at host.pnpm for a range, with its package: pnpm 12 runs that one,
313
383
  // and fails a frozen install where it is not there.
314
384
  //
385
+ // pnpm 9 holds a lockfile to less than pnpm 10: neither to the catalogs
386
+ // nor to dedupePeers, nor a dependency's version to its range. It hashes a
387
+ // patch with MD5, in base32, and picks one for a package by `name@version`
388
+ // as spelled, else by `name`, never by a range. It overrides a peer in
389
+ // place, whatever the override. Where the root package.json's
390
+ // packageManager pins another pnpm, pnpm 9 installs with itself, unless
391
+ // managePackageManagerVersions has it switch to that one, or
392
+ // packageManagerStrict and packageManagerStrictVersion have it fail, each
393
+ // refused; and it fails on another package manager with
394
+ // packageManagerStrict, as it is by default, which is refused. It knows no
395
+ // runtime, and holds a project's os, cpu and libc to the host's own,
396
+ // whatever supportedArchitectures says.
397
+ //
315
398
  // pnpm 12 makes none of pnpm 11's further checks of a lockfile, but holds
316
399
  // a directory a project depends on by `file:` to it: each dependency the
317
400
  // snapshot has is one its package.json, overridden, asks for, a peer among
@@ -386,6 +469,17 @@ export function buildPnpmTree(options: PnpmTreeOptions): Promise<PnpmTree>
386
469
  // file, which is refused; and the projects come in the order of their
387
470
  // paths by name, `a/b` before `a-b`.
388
471
  //
472
+ // pnpm 9 finds them with fast-glob, otherwise again: past the names before
473
+ // a glob's first `**` it walks into every directory, one with a leading
474
+ // dot among them, though no `*` or `**` takes a project there; it walks
475
+ // from the top for every glob where one has a `*` in its first name; and
476
+ // it leaves out what a `!` glob takes, leading dots and all. It reads
477
+ // every manifest a project has, not the first, and fails on a glob that
478
+ // leads through a file, both refused. Where pnpm-workspace.yaml sets
479
+ // nothing, it finds projects everywhere, as `**` does; where it sets
480
+ // anything but no `packages`, it fails, which is refused; and it refuses
481
+ // no name for it but pnpm-workspace.yml.
482
+ //
389
483
  // Refused: a root with no manifest, which pnpm takes for no project; a
390
484
  // project, the root among them, whose manifest is package.json5 or
391
485
  // package.yaml, which pnpm reads where there is no package.json, or is a
@@ -394,10 +488,10 @@ export function buildPnpmTree(options: PnpmTreeOptions): Promise<PnpmTree>
394
488
  // project in a directory a lockfile could not key its importer by, with a
395
489
  // control, bidirectional or backslash character in its path, or a drive
396
490
  // letter; a node_modules pnpm walks into, which it does only under a
397
- // directory with a leading dot that a glob spells; a glob buildPnpmTree
398
- // refuses, or a pnpm not 10.x, 11.x or 12.x; and a pnpm-workspace.yaml
399
- // that is not YAML, is not a mapping, is not UTF-8, or is under another
400
- // name pnpm refuses.
491
+ // directory with a leading dot, one a glob spells or, for pnpm 9, one
492
+ // past a `**`; a glob buildPnpmTree refuses, or a pnpm not 9.x, 10.x, 11.x
493
+ // or 12.x; and a pnpm-workspace.yaml that is not YAML, is not a mapping,
494
+ // is not UTF-8, or is under another name pnpm refuses.
401
495
  export interface PnpmProjectsOptions {
402
496
  project: PnpmProject
403
497
  host?: Pick<PnpmHost, 'pnpm'>
package/pnpm.js CHANGED
@@ -1,15 +1,7 @@
1
- // A node_modules tree built in memory from a pnpm lockfile, as pnpm 10 or
2
- // 11 installs it with the isolated linker: pnpm.d.ts says what it takes and
3
- // what comes back. The project is read through the view given, and the
4
- // tree built in a Vfs; the one filesystem touched is that of the tarball
5
- // caches @preventive/upstream reads, and writes where it keeps its own.
1
+ // A node_modules tree built in memory from a pnpm lockfile, as pnpm 9, 10,
2
+ // 11 or 12 installs it with the isolated linker; see pnpm.d.ts.
6
3
  export { buildPnpmTree } from './src/pnpm/tree.js'
7
4
  export { findPnpmProjects } from './src/pnpm/inputs.js'
8
5
  export { DeptreeError } from './src/error.js'
9
- // Where @preventive/upstream caches what it fetches, tarballs among it;
10
- // unset, it keeps no cache of its own, and writes nothing.
11
6
  export { setCacheDir } from '@preventive/upstream/npm.js'
12
- // What the readers beneath refuse the lockfile with, and the YAML of it
13
- // and of pnpm-workspace.yaml: the cause of a DeptreeError that names the
14
- // file.
15
7
  export { LockfileError, YamlError } from '@preventive/lockfile/pnpm.js'
package/soldeer.d.ts CHANGED
@@ -94,10 +94,23 @@ export interface SoldeerTreeStats {
94
94
  bytes: number
95
95
  }
96
96
 
97
+ // A dependency in the tree, as an SBOM would list it: `path` is its
98
+ // folder, from the project's root, which is `/` of the Vfs —
99
+ // dependencies/<name>-<version>; `name` and `version` the lockfile's, as
100
+ // the registry has them; `checksum` the hex sha256 its zip is held to.
101
+ export interface SoldeerInstalled {
102
+ path: string
103
+ name: string
104
+ version: string
105
+ checksum: string
106
+ }
107
+
97
108
  // `vfs` is the one given, the tree mounted into it, or a new one.
109
+ // `installed` is each dependency, in the lockfile's order.
98
110
  export interface SoldeerTree {
99
111
  vfs: Vfs
100
112
  stats: SoldeerTreeStats
113
+ installed: SoldeerInstalled[]
101
114
  }
102
115
 
103
116
  // The dependencies folder `soldeer install` makes from the lockfile, with
package/soldeer.js CHANGED
@@ -1,12 +1,6 @@
1
1
  // The dependencies folder built in memory from a soldeer.lock, as Soldeer
2
- // 0.12 installs it: soldeer.d.ts says what it takes and what comes back.
3
- // The project is read through the view given, and the tree built in a Vfs;
4
- // the one filesystem touched is that of the cache @preventive/upstream
5
- // reads, and writes where it keeps one.
2
+ // 0.12 installs it; see soldeer.d.ts.
6
3
  export { buildSoldeerTree } from './src/soldeer/tree.js'
7
4
  export { DeptreeError } from './src/error.js'
8
- // Where @preventive/upstream caches what it fetches, zips among it; unset,
9
- // it keeps no cache of its own, and writes nothing.
10
5
  export { setCacheDir } from '@preventive/upstream/npm.js'
11
- // What the lockfile, and the config read with it, are refused with.
12
6
  export { LockfileError, TomlError } from '@preventive/lockfile/soldeer.js'
package/src/concurrent.js CHANGED
@@ -1,24 +1,23 @@
1
- // The packages a tree is built of are fetched and unpacked a few at a
2
- // time, so that a large lockfile does not start a request for each at
3
- // once.
1
+ import { Queue } from '@chalker/queue'
2
+ import { refusalOf } from './error.js'
4
3
 
5
4
  const CONCURRENCY = 8
6
5
 
7
- // Runs `job` on each of `items`, a few at a time. The first failure stops
8
- // the rest from starting, and is thrown once every job started has ended,
9
- // so that none goes on, fetching or writing a cache, after the call has.
10
- export async function eachConcurrently(items, job) {
11
- const queue = [...items]
6
+ // A few at a time, so a large lockfile does not start every request at once.
7
+ // The first failure is thrown once every started job has ended, so that none
8
+ // goes on fetching or writing a cache after the call returns.
9
+ export async function eachConcurrently(items, job, whereOf) {
10
+ const queue = new Queue(CONCURRENCY)
12
11
  let failure
13
- const worker = async () => {
14
- while (queue.length > 0 && failure === undefined) {
15
- try {
16
- await job(queue.shift())
17
- } catch (error) {
18
- failure ??= { error }
19
- }
12
+ await Promise.all([...items].map(async (item) => {
13
+ await queue.claim()
14
+ try {
15
+ if (failure === undefined) await job(item)
16
+ } catch (error) {
17
+ failure ??= { error: whereOf === undefined ? error : refusalOf(error, whereOf(item)) }
18
+ } finally {
19
+ queue.release()
20
20
  }
21
- }
22
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
21
+ }))
23
22
  if (failure !== undefined) throw failure.error
24
23
  }
package/src/error.js CHANGED
@@ -1,7 +1,5 @@
1
- // `where` is what a refusal is about — a file and the setting or key in
2
- // it, `pnpm-workspace.yaml: nodeLinker`, or a package and the file in it —
3
- // or undefined for the call as a whole; the message leads with it. What a
4
- // package below refused with is kept as the `cause`.
1
+ // `where` is what is refused, such as `pnpm-workspace.yaml: nodeLinker`, or
2
+ // undefined for the call as a whole; the message leads with it.
5
3
  export class DeptreeError extends Error {
6
4
  constructor(detail, where, options) {
7
5
  super(where === undefined ? detail : `${where}: ${detail}`, options)
@@ -10,17 +8,15 @@ export class DeptreeError extends Error {
10
8
  }
11
9
  }
12
10
 
13
- // A piece of an input for a message: quoted, cut short where it runs long,
14
- // and with every control, line separator and bidirectional control
15
- // escaped, so a name cannot act on a terminal or reorder what is shown.
11
+ export const refusalOf = (error, where) => (error instanceof DeptreeError ? error : new DeptreeError(error.message, where, { cause: error }))
12
+
13
+ // Escaped so that a name cannot act on a terminal or reorder what is shown.
16
14
  const UNSHOWN = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu
17
15
  export function quote(text) {
18
16
  const cut = text.length > 200 ? `${text.slice(0, text.codePointAt(199) > 0xFFFF ? 199 : 200)}…` : text
19
17
  return JSON.stringify(cut).replaceAll(UNSHOWN, (char) => `\\u${char.codePointAt(0).toString(16).padStart(4, '0')}`)
20
18
  }
21
19
 
22
- // The first key two mappings of strings differ at, for a message: `sides`
23
- // names where each is from, and `same` tells two values alike.
24
20
  export function difference(a, b, [aSide, bSide], same = (x, y) => x === y) {
25
21
  for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
26
22
  const inA = Object.hasOwn(a, key)
package/src/glob.js ADDED
@@ -0,0 +1,55 @@
1
+ // Workspace globs as yarn and npm match and walk them, by minimatch's
2
+ // defaults as far as the lockfile reader lets them through: no wildcard
3
+ // takes a leading dot.
4
+
5
+ import { DeptreeError, quote } from './error.js'
6
+ import { reach, wildcard } from './matcher.js'
7
+ import { typeOf } from './project.js'
8
+
9
+ const compiled = new Map()
10
+
11
+ function compile(glob) {
12
+ return glob.split('/').map((segment) => {
13
+ if (segment === '**') return segment
14
+ const dot = !segment.startsWith('.') && /[*?]/u.test(segment)
15
+ const matches = wildcard(segment, { one: true })
16
+ return { test: (name) => !(dot && name.startsWith('.')) && matches(name) }
17
+ })
18
+ }
19
+
20
+ function placesOf(glob, path) {
21
+ if (!compiled.has(glob)) compiled.set(glob, compile(glob))
22
+ return reach(compiled.get(glob), path === '' ? [] : path.split('/'))
23
+ }
24
+
25
+ export const matchesGlob = (glob, path) => placesOf(glob, path).at(-1)
26
+
27
+ // Whether `glob` may take a path below `dir`: some of it left to take.
28
+ const reachesBelow = (glob, dir) => placesOf(glob, dir).slice(0, -1).some(Boolean)
29
+
30
+ // The directories the globs take that have a package.json, as yarn and npm
31
+ // walk for them. glob follows a link or not by where it is, so one the
32
+ // globs reach is refused. `enter` refuses a directory, or says whether it
33
+ // is kept and walked into.
34
+ export function walkWorkspaces(project, globs, { manager, fold = (path) => path, skip = () => false, enter = () => true }) {
35
+ const folded = globs.map(fold)
36
+ const found = []
37
+ const pending = globs.length === 0 ? [] : ['']
38
+ while (pending.length > 0) {
39
+ const dir = pending.pop()
40
+ for (const name of project.readdir(`/${dir}`)) {
41
+ const path = dir === '' ? name : `${dir}/${name}`
42
+ const key = fold(path)
43
+ const taken = folded.some((glob) => matchesGlob(glob, key))
44
+ if (skip(name) || (!taken && !folded.some((glob) => reachesBelow(glob, key)))) continue
45
+ const { type } = project.lstat(`/${path}`)
46
+ if (type === 'symlink') throw new DeptreeError(`a link where ${manager} looks for workspaces is not supported`, quote(path))
47
+ if (type !== 'directory') continue
48
+ const manifest = taken && typeOf(project, `/${path}/package.json`) !== undefined
49
+ if (!enter(path, name, taken, manifest)) continue
50
+ if (manifest) found.push(path)
51
+ pending.push(path)
52
+ }
53
+ }
54
+ return found.sort()
55
+ }
package/src/hash.js CHANGED
@@ -1,7 +1,3 @@
1
- // Digests on the platform's Web Crypto, which every runtime this runs on
2
- // has: the integrity a lockfile pins a tarball to, and the hex digests
3
- // pnpm names a patch and a long directory by.
4
-
5
1
  import { DeptreeError } from './error.js'
6
2
 
7
3
  const encoder = new TextEncoder()
@@ -10,18 +6,73 @@ const digest = async (algorithm, bytes) => new Uint8Array(await crypto.subtle.di
10
6
  const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
11
7
  const base64 = (bytes) => btoa(String.fromCodePoint(...bytes))
12
8
 
13
- // Text is hashed as its UTF-8, and only text that has one: TextEncoder
14
- // writes a lone surrogate as U+FFFD, so two different strings would hash
15
- // the same. `where` is what the text is, for the refusal.
16
- export async function sha256Hex(text, where) {
9
+ // Only well-formed text is hashed: TextEncoder writes a lone surrogate as
10
+ // U+FFFD, so two different strings would hash the same.
11
+ function utf8(text, where) {
17
12
  if (typeof text !== 'string' || !text.isWellFormed()) throw new DeptreeError('expected well-formed text to hash', where)
18
- return hex(await digest('SHA-256', encoder.encode(text)))
13
+ return encoder.encode(text)
14
+ }
15
+
16
+ export const sha256Hex = async (text, where) => hex(await digest('SHA-256', utf8(text, where)))
17
+
18
+ // MD5, which Web Crypto has not, as RFC 1321 has it.
19
+ const SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
20
+ const SINES = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0)
21
+ function md5(input) {
22
+ const blocks = Math.ceil((input.length + 9) / 64)
23
+ const padded = new Uint8Array(blocks * 64)
24
+ padded.set(input)
25
+ padded[input.length] = 0x80
26
+ const view = new DataView(padded.buffer)
27
+ view.setUint32(padded.length - 8, (input.length * 8) >>> 0, true)
28
+ view.setUint32(padded.length - 4, Math.floor(input.length / 2 ** 29), true)
29
+ const state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
30
+ for (let block = 0; block < padded.length; block += 64) {
31
+ let [a, b, c, d] = state
32
+ for (let i = 0; i < 64; i++) {
33
+ const round = i >> 4
34
+ const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d)
35
+ const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16
36
+ const shift = SHIFTS[round * 4 + (i % 4)]
37
+ const sum = (a + f + SINES[i] + view.getUint32(block + g * 4, true)) >>> 0
38
+ ;[a, d, c] = [d, c, b]
39
+ b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0
40
+ }
41
+ state[0] = (state[0] + a) >>> 0
42
+ state[1] = (state[1] + b) >>> 0
43
+ state[2] = (state[2] + c) >>> 0
44
+ state[3] = (state[3] + d) >>> 0
45
+ }
46
+ const bytes = new Uint8Array(16)
47
+ const out = new DataView(bytes.buffer)
48
+ state.forEach((word, i) => out.setUint32(i * 4, word, true))
49
+ return bytes
19
50
  }
20
51
 
21
- // Whether `bytes` are what a subresource integrity names: a sha512, the
22
- // only kind taken, in padded base64.
52
+ // RFC 4648's base32, lowercased and unpadded.
53
+ const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567'
54
+ function base32(bytes) {
55
+ let text = ''
56
+ let bits = 0
57
+ let value = 0
58
+ for (const byte of bytes) {
59
+ value = (value << 8) | byte
60
+ bits += 8
61
+ while (bits >= 5) {
62
+ bits -= 5
63
+ text += BASE32[(value >>> bits) & 31]
64
+ }
65
+ }
66
+ return bits > 0 ? text + BASE32[(value << (5 - bits)) & 31] : text
67
+ }
68
+
69
+ // pnpm 9's createBase32Hash: the MD5 of the text's UTF-8, in base32.
70
+ export const md5Base32 = (text, where) => base32(md5(utf8(text, where)))
71
+
23
72
  export const matchesIntegrity = async (bytes, integrity) => integrity === `sha512-${base64(await digest('SHA-512', bytes))}`
24
73
 
25
- // The hex sha1 of bytes, as yarn 1 records a tarball's after the `#` of
26
- // its URL.
74
+ // As yarn 1 records a tarball's after the `#` of its URL.
27
75
  export const sha1Hex = async (bytes) => hex(await digest('SHA-1', bytes))
76
+
77
+ // As soldeer.lock records a zip's checksum.
78
+ export const bytesSha256Hex = async (bytes) => hex(await digest('SHA-256', bytes))
@@ -0,0 +1,52 @@
1
+ // A package.json as pnpm, yarn 1 and npm read one, a byte order mark dropped.
2
+
3
+ import { DeptreeError, quote } from './error.js'
4
+ import { isInside } from './mount.js'
5
+
6
+ // A package.json is a few levels deep. One far deeper is refused where it is
7
+ // read, and again where it is copied whole, as structuredClone, which
8
+ // recurses, runs out of stack on one some thousands deep.
9
+ const DEEPEST = 100
10
+
11
+ export function checkNesting(value, where) {
12
+ const pending = [[value, 0]]
13
+ while (pending.length > 0) {
14
+ const [item, depth] = pending.pop()
15
+ if (item === null || typeof item !== 'object') continue
16
+ if (depth === DEEPEST) throw new DeptreeError(`nested more than ${DEEPEST} deep, which is not supported`, where)
17
+ for (const child of Object.values(item)) pending.push([child, depth + 1])
18
+ }
19
+ return value
20
+ }
21
+
22
+ // What a package.json's mapping has under `key` of its own. JSON.parse makes
23
+ // plain objects, which have `constructor` and `toString` from
24
+ // Object.prototype under names a package may have.
25
+ export const own = (map, key) => (map != null && Object.hasOwn(map, key) ? map[key] : undefined)
26
+
27
+ export function readManifest(text, where) {
28
+ if (typeof text !== 'string') throw new TypeError(`${where} must be the text of a package.json`)
29
+ let manifest
30
+ try {
31
+ manifest = JSON.parse(text.replace(/^/u, ''))
32
+ } catch (error) {
33
+ throw new DeptreeError(`not JSON: ${error.message}`, where, { cause: error })
34
+ }
35
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) throw new DeptreeError('expected an object', where)
36
+ return checkNesting(manifest, where)
37
+ }
38
+
39
+ // The package.json texts given by directory, in a Map or a Record: the
40
+ // project's, and its workspaces', each in a directory under it, as one
41
+ // found in a project is. A workspace's dependencies are written in its
42
+ // directory, and a link made to it.
43
+ export function readManifests(texts) {
44
+ const read = new Map()
45
+ for (const [dir, text] of texts instanceof Map ? texts : Object.entries(texts)) {
46
+ const where = `manifests[${quote(dir)}]`
47
+ if (dir !== '.' && !isInside(dir)) throw new DeptreeError('expected "." or a directory under the project\'s, by its path from there in normal form', where)
48
+ read.set(dir, readManifest(text, where))
49
+ }
50
+ if (!read.has('.')) throw new DeptreeError('the root package.json is not given', 'manifests["."]')
51
+ return read
52
+ }
package/src/matcher.js CHANGED
@@ -1,19 +1,68 @@
1
1
  // pnpm's name patterns (@pnpm/matcher), as `hoist-pattern` and
2
- // `public-hoist-pattern` read them: `*` for any run of characters and
3
- // nothing else special, `!` in front to exclude. One pattern is that
4
- // pattern or its negation; several are read in order, where an exclusion
5
- // cancels what matched before it and nothing after it matches again but a
6
- // later inclusion, and a list of exclusions alone matches what none of them
7
- // does.
2
+ // `public-hoist-pattern` read them; and the walk of a path through a glob,
3
+ // which pnpm's workspace globs and yarn's share.
8
4
 
9
- // Text as a regular expression that matches it alone.
10
- export const escape = (text) => text.replace(/[$()+.?[\\\]^{|}]/gu, '\\$&')
5
+ // Whether a text matches `pattern`, `*` any run of what `any` takes and,
6
+ // with `one`, `?` any one code point; anything else itself. The places of
7
+ // `pattern` a text reaches are kept a code point at a time, in O(n·m) for
8
+ // any pattern, where a regexp of k `*`s backtracks in O(n^k): a glob from a
9
+ // project's own files is no one's to stall.
10
+ export function wildcard(pattern, { one = false, any = () => true } = {}) {
11
+ const parts = [...pattern]
12
+ const end = parts.length
13
+ const onward = (places) => {
14
+ for (let i = 0; i < end; i++) if (places[i] === 1 && parts[i] === '*') places[i + 1] = 1
15
+ }
16
+ return (text) => {
17
+ let here = new Uint8Array(end + 1)
18
+ let next = new Uint8Array(end + 1)
19
+ here[0] = 1
20
+ onward(here)
21
+ for (const char of text) {
22
+ next.fill(0)
23
+ for (let i = 0; i < end; i++) {
24
+ if (here[i] === 0) continue
25
+ if (parts[i] === '*') {
26
+ if (any(char)) next[i] = 1
27
+ } else if (parts[i] === char || (one && parts[i] === '?')) next[i + 1] = 1
28
+ }
29
+ onward(next)
30
+ ;[here, next] = [next, here]
31
+ }
32
+ return here[end] === 1
33
+ }
34
+ }
35
+
36
+ // For each place in `glob`, a regexp per name or `**`, whether `names` reach
37
+ // it, the last being a full match; linear per name, with no recursion however
38
+ // many `**`. A `**` takes no name with a leading dot unless `dot`.
39
+ export function reach(glob, names, dot = false) {
40
+ let here = Array.from({ length: glob.length + 1 }, (_, g) => g === 0)
41
+ let next = Array.from({ length: glob.length + 1 }, () => false)
42
+ const onward = (places) => {
43
+ for (let g = 0; g < glob.length; g++) if (places[g] && glob[g] === '**') places[g + 1] = true
44
+ }
45
+ onward(here)
46
+ for (const name of names) {
47
+ next.fill(false)
48
+ for (let g = 0; g < glob.length; g++) {
49
+ if (!here[g]) continue
50
+ if (glob[g] !== '**') next[g + 1] ||= glob[g].test(name)
51
+ else if (dot || !name.startsWith('.')) next[g] = true
52
+ }
53
+ onward(next)
54
+ ;[here, next] = [next, here]
55
+ }
56
+ return here
57
+ }
58
+
59
+ // pnpm's `*` is a regexp's `.*`, which takes no line terminator.
60
+ const LINE = new Set(['\n', '\r', '\u2028', '\u2029'])
11
61
 
12
62
  function matcherOf(pattern) {
13
63
  if (pattern === '*') return () => true
14
64
  if (!pattern.includes('*')) return (input) => input === pattern
15
- const regexp = new RegExp(`^${pattern.split('*').map(escape).join('.*')}$`, 'u')
16
- return (input) => regexp.test(input)
65
+ return wildcard(pattern, { any: (char) => !LINE.has(char) })
17
66
  }
18
67
 
19
68
  export function createMatcher(patterns) {