@preventive/deptree 1.0.0 → 1.0.2

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.
package/npm.d.ts CHANGED
@@ -140,10 +140,24 @@ export interface NpmProject {
140
140
  // undefined where the document names none. What is checked of a package's
141
141
  // tarball and files is not, so a lockfile one of those checks would refuse is
142
142
  // laid out all the same. A `vfs` is not taken with it.
143
+ //
144
+ // `lazy`, false unless given true, lays the tree out as sizeEstimateOnly
145
+ // does, each package's directory made and left empty and each link made,
146
+ // but fetches nothing, not even a version document: each package is
147
+ // unpacked into it once asked for by the tree's `unpack`, and only then
148
+ // fetched, as `metadata` and `cache` say. A package unpacked is what the
149
+ // full tree has at its path, file for file, with the bins it links fixed,
150
+ // which the lockfile alone tells, and held to every check of its tarball and
151
+ // files the full tree holds it to; one never asked for is never fetched, so
152
+ // a lockfile one of those checks would refuse is laid out all the same, and
153
+ // refused where that package is unpacked. A `vfs` is not taken with it, nor
154
+ // `sizeEstimateOnly`.
143
155
  export type NpmTreeOptions = NpmTreeGiven | NpmTreeRead
144
156
 
145
157
  export type NpmLayoutOptions = NpmTreeOptions & { sizeEstimateOnly: true, vfs?: undefined }
146
158
 
159
+ export type NpmLazyOptions = NpmTreeOptions & { lazy: true, sizeEstimateOnly?: false, vfs?: undefined }
160
+
147
161
  export interface NpmTreeGiven {
148
162
  lockfile: string
149
163
  manifests: Record<string, string> | Map<string, string>
@@ -154,6 +168,7 @@ export interface NpmTreeGiven {
154
168
  metadata?: boolean
155
169
  cache?: CacheOptions['cache']
156
170
  sizeEstimateOnly?: boolean
171
+ lazy?: boolean
157
172
  }
158
173
 
159
174
  export interface NpmTreeRead {
@@ -166,6 +181,7 @@ export interface NpmTreeRead {
166
181
  metadata?: boolean
167
182
  cache?: CacheOptions['cache']
168
183
  sizeEstimateOnly?: boolean
184
+ lazy?: boolean
169
185
  }
170
186
 
171
187
  // What buildNpmTree counts, all of it plain numbers: `packages` the
@@ -175,7 +191,9 @@ export interface NpmTreeRead {
175
191
  // is written; `links` the workspaces linked. With `sizeEstimateOnly`,
176
192
  // `tarballs` counts those fetched by their version document alone; `files`
177
193
  // is 0, as none is written, and `bytes` what the sizes of those installed
178
- // add up to, each copy's, of those with one.
194
+ // add up to, each copy's, of those with one. With `lazy`, `tarballs`,
195
+ // `files` and `bytes` count what is unpacked, each 0 until `unpack` is
196
+ // asked, which adds to them.
179
197
  export interface NpmTreeStats {
180
198
  packages: number
181
199
  installed: number
@@ -243,6 +261,21 @@ export interface NpmLayout {
243
261
  installed: NpmLaidOut[]
244
262
  }
245
263
 
264
+ // With `lazy`: `vfs` a new one, of the tree's directories and links, which
265
+ // `unpack` writes each package's files into; `installed` each package, with
266
+ // nothing its version document says, as none is fetched. `unpack` takes the
267
+ // paths of packages as `installed` lists them, and resolves once each is
268
+ // unpacked, to their entries in that order, with what each one's version
269
+ // document says where `metadata` has it fetched. Each is unpacked once,
270
+ // however often and at once it is asked for, and a few tarballs are fetched at
271
+ // a time; each is written whole or not at all, and one refused rejects the
272
+ // call, and each call that asks for it after, with the DeptreeError the full
273
+ // tree is refused with, once every package the call asks for is done. A path
274
+ // the tree installs no package at is a TypeError.
275
+ export interface NpmLazyTree extends NpmTree {
276
+ unpack(paths: Iterable<string>): Promise<NpmInstalled[]>
277
+ }
278
+
246
279
  // The node_modules tree `npm ci --ignore-scripts` makes, with host.npm,
247
280
  // into a project with no node_modules yet: rooted at the lockfile's
248
281
  // directory, each package's files unpacked where the lockfile puts it,
@@ -333,6 +366,7 @@ export interface NpmLayout {
333
366
  // each is refused with a DeptreeError or a LockfileError that says where.
334
367
  // A TypeError is thrown for options of the wrong type.
335
368
  export function buildNpmTree(options: NpmLayoutOptions): Promise<NpmLayout>
369
+ export function buildNpmTree(options: NpmLazyOptions): Promise<NpmLazyTree>
336
370
  export function buildNpmTree(options: NpmTreeOptions): Promise<NpmTree>
337
371
 
338
372
  // The directories of the projects npm finds in `project`, by which
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/deptree",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "In-memory dependency tree, as a package manager installs it",
5
5
  "type": "module",
6
6
  "exports": {
@@ -54,6 +54,7 @@
54
54
  "src/error.js",
55
55
  "src/glob.js",
56
56
  "src/hash.js",
57
+ "src/lazy.js",
57
58
  "src/manifest.js",
58
59
  "src/matcher.js",
59
60
  "src/mount.js",
@@ -83,6 +84,7 @@
83
84
  "src/pnpm/hook.js",
84
85
  "src/pnpm/inputs.js",
85
86
  "src/pnpm/install.js",
87
+ "src/pnpm/lazy.js",
86
88
  "src/pnpm/local.js",
87
89
  "src/pnpm/minimatch.js",
88
90
  "src/pnpm/nm-hoist-graph.js",
@@ -98,6 +100,7 @@
98
100
  "src/pnpm/tree.js",
99
101
  "src/pnpm/uptodate.js",
100
102
  "src/pnpm/workspace.js",
103
+ "src/pnpm/write.js",
101
104
  "src/project.js",
102
105
  "src/soldeer/config.js",
103
106
  "src/soldeer/git.js",
@@ -144,11 +147,11 @@
144
147
  "dependencies": {
145
148
  "@chalker/queue": "^1.0.1",
146
149
  "@exodus/bytes": "^1.16.0",
147
- "@preventive/archive": "1.0.0",
150
+ "@preventive/archive": "^1.2.0",
148
151
  "@preventive/compare": "^1.2.11",
149
152
  "@preventive/diff": "^1.1.0",
150
153
  "@preventive/lockfile": "^1.2.0",
151
- "@preventive/upstream": "^1.2.0",
154
+ "@preventive/upstream": "^1.3.0",
152
155
  "@preventive/vfs": "1.0.0-beta.4"
153
156
  }
154
157
  }
package/pnpm.d.ts CHANGED
@@ -259,6 +259,28 @@ export interface PnpmProject {
259
259
  // copy, one with a node_modules, which pnpm drops where it builds the
260
260
  // package. A `vfs` is not taken with it.
261
261
  //
262
+ // `lazy`, false unless given true, lays the tree out as sizeEstimateOnly
263
+ // does, each package's directory made and left empty and each link made,
264
+ // but fetches nothing, not even a version document: each package is
265
+ // unpacked into it once asked for by the tree's `unpack`, and only then
266
+ // fetched, as `metadata` and `cache` say. A package unpacked is what the
267
+ // full tree has at its path, file for file, patched and fixed as linking
268
+ // bins fixes it, and held to every check of its tarball, package.json and
269
+ // patch the full tree holds it to; one never asked for is never fetched, so
270
+ // a lockfile one of those checks would refuse is laid out all the same, and
271
+ // refused where that package is unpacked. Which of a package's bins pnpm
272
+ // links turns on the others' bins, and is read only where it could change
273
+ // the package's files: a bin pnpm would make executable, or whose CRLF `#!`
274
+ // line it would make LF; one that is a directory, which pnpm 9 and 12 fail
275
+ // on; or any bin of a patched package. With the hoisted linker where any
276
+ // patch is configured, so does what pnpm's build pass does to a package it
277
+ // builds, patched or with an install script, which is read for every such
278
+ // package. The first such unpack fetches every package not unpacked yet,
279
+ // reading those that are back from the tree, as the full tree does, and
280
+ // keeps them all. Where the files could change the layout, the lockfile is
281
+ // refused as with sizeEstimateOnly. A `vfs` is not taken with it, nor
282
+ // `sizeEstimateOnly`.
283
+ //
262
284
  // The two ways the files come, one or the other: given, with `lockfile`
263
285
  // and `manifests`, `project` read only for directories; or read, with
264
286
  // `project` and none of them.
@@ -266,6 +288,8 @@ export type PnpmTreeOptions = PnpmTreeGiven | PnpmTreeRead
266
288
 
267
289
  export type PnpmLayoutOptions = PnpmTreeOptions & { sizeEstimateOnly: true, vfs?: undefined }
268
290
 
291
+ export type PnpmLazyOptions = PnpmTreeOptions & { lazy: true, sizeEstimateOnly?: false, vfs?: undefined }
292
+
269
293
  export interface PnpmTreeGiven {
270
294
  lockfile: string
271
295
  manifests: Record<string, string> | Map<string, string>
@@ -278,6 +302,7 @@ export interface PnpmTreeGiven {
278
302
  metadata?: boolean
279
303
  cache?: CacheOptions['cache']
280
304
  sizeEstimateOnly?: boolean
305
+ lazy?: boolean
281
306
  }
282
307
 
283
308
  export interface PnpmTreeRead {
@@ -292,6 +317,7 @@ export interface PnpmTreeRead {
292
317
  metadata?: boolean
293
318
  cache?: CacheOptions['cache']
294
319
  sizeEstimateOnly?: boolean
320
+ lazy?: boolean
295
321
  }
296
322
 
297
323
  // What buildPnpmTree counts, all of it plain numbers: `projects` the
@@ -304,7 +330,8 @@ export interface PnpmTreeRead {
304
330
  // With `sizeEstimateOnly`, `tarballs` counts the packages fetched by their
305
331
  // version document alone; `files` is 0, as none is written, and `bytes`
306
332
  // what the sizes of those installed add up to, each copy's, of those with
307
- // one.
333
+ // one. With `lazy`, `tarballs`, `files` and `bytes` count what is unpacked,
334
+ // each 0 until `unpack` is asked, which adds to them.
308
335
  export interface PnpmTreeStats {
309
336
  projects: number
310
337
  snapshots: number
@@ -379,6 +406,21 @@ export interface PnpmLayout {
379
406
  installed: PnpmLaidOut[]
380
407
  }
381
408
 
409
+ // With `lazy`: `vfs` a new one, of the tree's directories and links, which
410
+ // `unpack` writes each package's files into; `installed` each snapshot, with
411
+ // nothing its version document says, as none is fetched. `unpack` takes the
412
+ // paths of snapshots as `installed` lists them, and resolves once each is
413
+ // unpacked, to their entries in that order, with what each one's version
414
+ // document says where `metadata` has it fetched. Each is unpacked once,
415
+ // however often and at once it is asked for, and a few tarballs are fetched at
416
+ // a time; each is written whole or not at all, and one refused rejects the
417
+ // call, and each call that asks for it after, with the DeptreeError the full
418
+ // tree is refused with, once every package the call asks for is done. A path
419
+ // the tree installs no package at is a TypeError.
420
+ export interface PnpmLazyTree extends PnpmTree {
421
+ unpack(paths: Iterable<string>): Promise<PnpmInstalled[]>
422
+ }
423
+
382
424
  // The node_modules tree `pnpm install --frozen-lockfile --ignore-scripts`
383
425
  // makes with the isolated linker of host.pnpm, 9, 10, 11 or 12, or the
384
426
  // hoisted one of pnpm 10 or 11, and no other install: whatever the
@@ -567,6 +609,7 @@ export interface PnpmLayout {
567
609
  // and its cause is their LockfileError or YamlError. A TypeError is thrown
568
610
  // for options of the wrong type.
569
611
  export function buildPnpmTree(options: PnpmLayoutOptions): Promise<PnpmLayout>
612
+ export function buildPnpmTree(options: PnpmLazyOptions): Promise<PnpmLazyTree>
570
613
  export function buildPnpmTree(options: PnpmTreeOptions): Promise<PnpmTree>
571
614
 
572
615
  // The directories of the projects pnpm finds in `project`, by which
package/src/concurrent.js CHANGED
@@ -22,6 +22,20 @@ export async function eachConcurrently(items, job, whereOf) {
22
22
  if (failure !== undefined) throw failure.error
23
23
  }
24
24
 
25
+ // A job a few at a time across calls, as eachConcurrently runs them within
26
+ // one: what a lazy tree fetches as each package is asked for.
27
+ export function limited() {
28
+ const queue = new Queue(CONCURRENCY)
29
+ return async (job) => {
30
+ await queue.claim()
31
+ try {
32
+ return await job()
33
+ } finally {
34
+ queue.release()
35
+ }
36
+ }
37
+ }
38
+
25
39
  // Each of `values` awaited at once, the first failure by position thrown once
26
40
  // all have ended, as eachConcurrently throws one.
27
41
  export async function settled(values) {
package/src/lazy.js ADDED
@@ -0,0 +1,28 @@
1
+ // What a lazy tree (pnpm's and npm's) shares: its unpack, which writes each
2
+ // package asked for once, into the tree as laid out, as the full tree has it.
3
+
4
+ import { settled } from './concurrent.js'
5
+ import { quote } from './error.js'
6
+ import { mount } from './mount.js'
7
+
8
+ // `byPath` holds each package by its path from the tree's root, as
9
+ // `installed` lists it; `unpackOne` writes one and gives back its entry. One
10
+ // asked for again, or while it is unpacked, is unpacked once; one refused is
11
+ // refused again, as nothing of it was written.
12
+ export function unpacker(byPath, unpackOne) {
13
+ const unpacking = new Map()
14
+ return async function unpack(paths) {
15
+ if (typeof paths === 'string' || typeof paths?.[Symbol.iterator] !== 'function') throw new TypeError('paths must be an iterable of the paths of packages the tree installs')
16
+ const asked = [...paths]
17
+ for (const path of asked) {
18
+ if (typeof path !== 'string' || !byPath.has(path)) throw new TypeError(`${quote(String(path))} is not the path of a package the tree installs`)
19
+ }
20
+ for (const path of asked) if (!unpacking.has(path)) unpacking.set(path, unpackOne(byPath.get(path)))
21
+ return await settled(asked.map((path) => unpacking.get(path)))
22
+ }
23
+ }
24
+
25
+ // `tree`, a new Vfs holding one package's files at its place alone, merged
26
+ // into `vfs`, where its directory is and is empty: judged whole first, two
27
+ // names that are one on macOS among them, so a refusal writes none of it.
28
+ export const writeInto = (vfs, tree, folded) => mount(tree, vfs, folded, () => {})
package/src/npm/bins.js CHANGED
@@ -26,29 +26,48 @@ function modulesOf(location) {
26
26
  return basename(parent) === 'node_modules' ? parent : dirname(parent)
27
27
  }
28
28
 
29
- // The files linking changes, by each package's location.
30
- export function fixBins(nodes, fetched) {
29
+ // The paths of the bins each package links, by its location, of the lockfile
30
+ // alone: those it claims a name for in its node_modules' .bin first.
31
+ export function claimedBins(nodes) {
31
32
  const seen = new Set()
32
- const changed = new Map()
33
- for (const node of nodes.toSorted((a, b) => collator.compare(a.location, b.location))) {
34
- const { location, pkg } = node
35
- const { files, dirs } = fetched.get(node)
36
- const where = `packages[${quote(location)}].bin`
33
+ const claimed = new Map()
34
+ for (const { location, pkg } of nodes.toSorted((a, b) => collator.compare(a.location, b.location))) {
37
35
  for (const [name, path] of binsOf(pkg.bin)) {
38
36
  const link = `${modulesOf(location)}/.bin/${name}`
39
37
  if (seen.has(link)) continue
40
38
  seen.add(link)
41
- const segments = path.split('/')
42
- if (isModules(segments[0])) throw new DeptreeError(`${quote(path)} is in the package's own node_modules, where npm installs its dependencies, which is not supported`, where)
43
- if (segments.slice(1).some((_, i) => files.has(segments.slice(0, i + 1).join('/')))) throw new DeptreeError(`${quote(path)} runs through a file, which npm fails on`, where)
44
- const file = files.get(path)
45
- if (file === undefined) {
46
- if (!dirs.has(path)) continue
47
- throw new DeptreeError(`${quote(path)} is a directory, which is not supported`, where)
48
- }
49
- if (!changed.has(location)) changed.set(location, new Map())
50
- changed.get(location).set(path, { data: fixShebang(file.data, 'a bin with a CRLF shebang that is not UTF-8, which npm rewrites with replacement characters, is not supported', where), mode: 0o755 })
39
+ claimed.set(location, [...claimed.get(location) ?? [], path])
40
+ }
41
+ }
42
+ return claimed
43
+ }
44
+
45
+ // What linking `paths`, as claimedBins gives them, changes of the files of
46
+ // the package at `location`.
47
+ export function fixClaimed(location, paths, { files, dirs }) {
48
+ const where = `packages[${quote(location)}].bin`
49
+ const changed = new Map()
50
+ for (const path of paths) {
51
+ const segments = path.split('/')
52
+ if (isModules(segments[0])) throw new DeptreeError(`${quote(path)} is in the package's own node_modules, where npm installs its dependencies, which is not supported`, where)
53
+ if (segments.slice(1).some((_, i) => files.has(segments.slice(0, i + 1).join('/')))) throw new DeptreeError(`${quote(path)} runs through a file, which npm fails on`, where)
54
+ const file = files.get(path)
55
+ if (file === undefined) {
56
+ if (!dirs.has(path)) continue
57
+ throw new DeptreeError(`${quote(path)} is a directory, which is not supported`, where)
51
58
  }
59
+ changed.set(path, { data: fixShebang(file.data, 'a bin with a CRLF shebang that is not UTF-8, which npm rewrites with replacement characters, is not supported', where), mode: 0o755 })
60
+ }
61
+ return changed
62
+ }
63
+
64
+ // The files linking changes, by each package's location.
65
+ export function fixBins(nodes, fetched) {
66
+ const byLocation = new Map(nodes.map((node) => [node.location, node]))
67
+ const changed = new Map()
68
+ for (const [location, paths] of claimedBins(nodes)) {
69
+ const fixed = fixClaimed(location, paths, fetched.get(byLocation.get(location)))
70
+ if (fixed.size > 0) changed.set(location, fixed)
52
71
  }
53
72
  return changed
54
73
  }
@@ -22,42 +22,18 @@ export function registryTarball({ name, version, resolution }, where) {
22
22
 
23
23
  const FILES = new Set(['file', 'contiguous-file'])
24
24
 
25
- // The headers that stand ahead of an entry: pax, global, long name, long link.
26
- const EXTENDED = new Set([0x78, 0x67, 0x4c, 0x4b])
27
- const PAX = 0x78
28
- const BLOCK = 512
29
- const blocks = (size) => BLOCK * Math.ceil(size / BLOCK)
30
-
31
- // An extended header's size as the archive reader read it, which held it to
32
- // 1 MiB: base 256, or octal digits to a NUL, a blank field 0.
33
- function extendedSize(tar, at) {
34
- const field = tar.subarray(at + 124, at + 136)
35
- if (field[0] === 0x80 || field[0] === 0xff) return field.subarray(1).reduce((size, byte) => size * 256 + byte, 0)
36
- const digits = /^ *([0-7]*)/u.exec(String.fromCodePoint(...field).split('\0')[0])[1]
37
- return digits === '' ? 0 : Number.parseInt(digits, 8)
38
- }
39
-
40
25
  // Every tar release takes a pax size over the header's. Up to 7.5.15, as
41
26
  // npm 10.9.8 and 11.16 and before bundle it, tar reads it into each header
42
27
  // after the pax one up to its entry too, so a long name, a long link or a
43
28
  // global header between them is read by it, and all that follows otherwise
44
- // than later releases read it. The archive reader has checked the layout
45
- // whole, so each header is where the sizes it took say.
46
- function checkPaxSizes(tar, entries, where) {
47
- if (!entries.some(({ pax }) => pax.has('size'))) return
48
- let at = 0
49
- for (const { storedName, data, pax } of entries) {
50
- let afterPax = false
51
- let between = false
52
- for (let flag = tar[at + 156]; EXTENDED.has(flag); flag = tar[at + 156]) {
53
- between ||= afterPax
54
- afterPax ||= flag === PAX
55
- at += BLOCK + blocks(extendedSize(tar, at))
29
+ // than later releases read it. The archive reader lists the extended headers
30
+ // ahead of each entry, in their order.
31
+ function checkPaxSizes(entries, where) {
32
+ for (const { storedName, pax, extended } of entries) {
33
+ if (pax.has('size') && extended.findIndex(({ kind }) => kind === 'pax') < extended.length - 1) {
34
+ throw new DeptreeError(`${quote(storedName)} has a pax size ahead of another extended header, which tar's releases read otherwise`, where)
56
35
  }
57
- if (between && pax.has('size')) throw new DeptreeError(`${quote(storedName)} has a pax size ahead of another extended header, which tar's releases read otherwise`, where)
58
- at += BLOCK + blocks(data.length)
59
36
  }
60
- if (tar.length < at + 2 * BLOCK || tar.subarray(at, at + 2 * BLOCK).some((byte) => byte !== 0)) throw new Error('unreachable: no end of the archive where the archive reader found one')
61
37
  }
62
38
 
63
39
  function unpack(entries, where) {
@@ -89,8 +65,8 @@ function unpack(entries, where) {
89
65
  }
90
66
 
91
67
  export async function fetchNpmPackage({ name, version, integrity }, where, check, fetching) {
92
- const { bytes, tar, entries, inflated, about } = await fetchTarball(name, version, integrity, where, fetching)
68
+ const { bytes, entries, inflated, about } = await fetchTarball(name, version, integrity, where, fetching)
93
69
  await check?.(bytes, inflated, where)
94
- checkPaxSizes(tar, entries, where)
70
+ checkPaxSizes(entries, where)
95
71
  return { ...unpack(entries, where), about }
96
72
  }
package/src/npm/tree.js CHANGED
@@ -1,17 +1,20 @@
1
1
  // The tree `npm ci --ignore-scripts` makes, but node_modules/.bin and npm's
2
2
  // node_modules/.package-lock.json. With `sizeEstimateOnly`, its directories
3
3
  // and links alone, each package's sized by its version document, of which
4
- // nothing is fetched but those documents.
4
+ // nothing is fetched but those documents. With `lazy`, its directories and
5
+ // links alone too, fetching nothing, and each package unpacked into it as
6
+ // it is asked for (lazyUnpacker).
5
7
 
6
8
  import { parseNpmLockfile } from '@preventive/lockfile/npm.js'
7
9
  import { Vfs } from '@preventive/vfs'
8
10
  import { dirname, relative } from '@preventive/vfs/path.js'
9
11
  import { satisfies, valid, validRange } from '@preventive/upstream/semver.js'
10
- import { eachConcurrently } from '../concurrent.js'
11
- import { DeptreeError, quote } from '../error.js'
12
+ import { eachConcurrently, limited } from '../concurrent.js'
13
+ import { DeptreeError, quote, refusalOf } from '../error.js'
14
+ import { unpacker, writeInto } from '../lazy.js'
12
15
  import { checkNoModules, isInside, makeDirs, mount, writeFiles, writeLink } from '../mount.js'
13
- import { fetchSize, fetchingOf } from '../tarball.js'
14
- import { fixBins } from './bins.js'
16
+ import { NO_ABOUT, fetchSize, fetchingOf } from '../tarball.js'
17
+ import { claimedBins, fixBins, fixClaimed } from './bins.js'
15
18
  import { skippedOf } from './compat.js'
16
19
  import { graphOf } from './graph.js'
17
20
  import { checkHost, inputsOf } from './inputs.js'
@@ -50,9 +53,9 @@ function checkSpecs(lockfile, host) {
50
53
  }
51
54
  }
52
55
 
53
- // Every URL is checked before any is fetched. With `sizeEstimateOnly`, a
54
- // package's size alone, with no files.
55
- async function fetchAll(nodes, host, fetching) {
56
+ // Each tarball, with the packages it is, as it is fetched once for all of
57
+ // them. Every URL is checked before any is fetched.
58
+ function tarballsOf(nodes) {
56
59
  const tarballs = new Map()
57
60
  for (const node of nodes) {
58
61
  const tarball = registryTarball(node.pkg, whereOf(node))
@@ -60,6 +63,11 @@ async function fetchAll(nodes, host, fetching) {
60
63
  if (!tarballs.has(key)) tarballs.set(key, { tarball, where: whereOf(node), nodes: [] })
61
64
  tarballs.get(key).nodes.push(node)
62
65
  }
66
+ return tarballs
67
+ }
68
+
69
+ // With `sizeEstimateOnly`, a package's size alone, with no files.
70
+ async function fetchAll(tarballs, host, fetching) {
63
71
  const fetched = new Map()
64
72
  const fetch = (tarball, where) => (fetching.sizeEstimateOnly ? fetchSize(tarball.name, tarball.version, tarball.integrity, where, fetching) : fetchNpmPackage(tarball, where, host.ratio ? checkRatio : undefined, fetching))
65
73
  await eachConcurrently(tarballs.values(), async ({ tarball, where, nodes: copies }) => {
@@ -82,17 +90,17 @@ function residueOf(nodes, skipped) {
82
90
  }
83
91
 
84
92
  // With `sizeEstimateOnly`, each package's directory alone is made, and its
85
- // size counted.
86
- function writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly }) {
93
+ // size counted; with `lazy`, its directory alone.
94
+ function writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly, lazy }) {
87
95
  const vfs = new Vfs()
88
96
  const stats = { files: 0, bytes: 0, links: 0 }
89
97
  for (const node of kept) {
90
- const { files, dirs, size } = fetched.get(node)
91
- if (sizeEstimateOnly) {
98
+ if (sizeEstimateOnly || lazy) {
92
99
  makeDirs(vfs, node.location)
93
- stats.bytes += size ?? 0
100
+ if (sizeEstimateOnly) stats.bytes += fetched.get(node).size ?? 0
94
101
  continue
95
102
  }
103
+ const { files, dirs } = fetched.get(node)
96
104
  const fixed = changed.get(node.location)
97
105
  writeFiles(vfs, node.location, { dirs, files: fixed === undefined ? files : new Map([...files].map(([path, file]) => [path, fixed.get(path) ?? file])) }, stats)
98
106
  }
@@ -106,6 +114,49 @@ function writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly
106
114
  return { vfs, stats }
107
115
  }
108
116
 
117
+ // A lazy tree's unpack (../lazy.js): each tarball fetched once for all the
118
+ // packages it is, a few at a time, and held to what the full tree holds it
119
+ // to; each package written as the full tree writes it, with the bins it
120
+ // links fixed, which the lockfile alone tells. A tarball's files are let go
121
+ // once each of its packages is unpacked.
122
+ function lazyUnpacker({ vfs, kept, tarballOf, settings, host, fetching, stats, folded, entryOf }) {
123
+ const limit = limited()
124
+ const claimed = settings.binLinks ? claimedBins(kept) : new Map()
125
+ const left = new Map([...new Set(tarballOf.values())].map((group) => [group, group.nodes.length]))
126
+ const fetched = new Map()
127
+ const counted = new Set()
128
+ const fetchOnce = (group) => {
129
+ if (!fetched.has(group)) {
130
+ fetched.set(group, limit(() => fetchNpmPackage(group.tarball, group.where, host.ratio ? checkRatio : undefined, fetching)).then((got) => {
131
+ counted.add(group)
132
+ stats.tarballs = counted.size
133
+ return { ...got, integrity: group.tarball.integrity }
134
+ }, (error) => {
135
+ throw refusalOf(error, group.where)
136
+ }))
137
+ }
138
+ return fetched.get(group)
139
+ }
140
+ return unpacker(new Map(kept.map((node) => [node.location, node])), async (node) => {
141
+ const group = tarballOf.get(node)
142
+ const got = await fetchOnce(group)
143
+ const tree = new Vfs()
144
+ const written = { files: 0, bytes: 0, links: 0 }
145
+ try {
146
+ const fixed = claimed.has(node.location) ? fixClaimed(node.location, claimed.get(node.location), got) : new Map()
147
+ writeFiles(tree, node.location, { dirs: got.dirs, files: fixed.size === 0 ? got.files : new Map([...got.files].map(([path, file]) => [path, fixed.get(path) ?? file])) }, written)
148
+ writeInto(vfs, tree, folded)
149
+ } catch (error) {
150
+ throw refusalOf(error, whereOf(node))
151
+ }
152
+ stats.files += written.files
153
+ stats.bytes += written.bytes
154
+ left.set(group, left.get(group) - 1)
155
+ if (left.get(group) === 0) fetched.delete(group)
156
+ return entryOf(node, got)
157
+ })
158
+ }
159
+
109
160
  // The lockfile reader refuses what does not parse.
110
161
  function rootListsOf(text) {
111
162
  try {
@@ -120,6 +171,7 @@ export async function buildNpmTree(options) {
120
171
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
121
172
  const fetching = fetchingOf(options ?? {})
122
173
  if (fetching.sizeEstimateOnly && into !== undefined) throw new TypeError('vfs is not taken with sizeEstimateOnly, whose tree has no files to mount')
174
+ if (fetching.lazy && into !== undefined) throw new TypeError('vfs is not taken with lazy, whose tree is unpacked a package at a time')
123
175
  const host = checkHost(given)
124
176
  const folded = host.os === 'darwin'
125
177
  const inputs = inputsOf(options ?? {}, folded)
@@ -136,16 +188,21 @@ export async function buildNpmTree(options) {
136
188
  const nodes = graphOf(lockfile, manifests)
137
189
  const skipped = skippedOf(nodes, host, settings)
138
190
  const kept = [...nodes.values()].filter((node) => node.kind === 'package' && !skipped.has(node))
139
- const { fetched, tarballs } = await fetchAll(kept, host, fetching)
140
- const changed = settings.binLinks && !fetching.sizeEstimateOnly ? fixBins(kept, fetched) : new Map()
191
+ const tarballs = tarballsOf(kept)
192
+ const { fetched, tarballs: count } = fetching.lazy ? { fetched: new Map(), tarballs: 0 } : await fetchAll(tarballs, host, fetching)
193
+ const changed = settings.binLinks && !fetching.sizeEstimateOnly && !fetching.lazy ? fixBins(kept, fetched) : new Map()
141
194
  const residue = host.reuse ? residueOf(nodes, skipped) : new Set()
142
- const { vfs, stats: written } = writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly: fetching.sizeEstimateOnly })
195
+ const { vfs, stats: written } = writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly: fetching.sizeEstimateOnly, lazy: fetching.lazy })
143
196
  const packages = Object.keys(lockfile.packages).length
144
- const stats = { packages, installed: kept.length, skipped: packages - kept.length, tarballs, ...written }
145
- const installed = kept.map((node) => {
197
+ const stats = { packages, installed: kept.length, skipped: packages - kept.length, tarballs: count, ...written }
198
+ const entryOf = (node, { integrity, about, size }) => {
146
199
  const { name, version, dev, optional, devOptional, peer } = node.pkg
147
- const { integrity, about, size } = fetched.get(node)
148
200
  return { path: node.location, name, version, integrity, ...about, dev, optional, devOptional, peer, ...fetching.sizeEstimateOnly ? { size } : {} }
149
- })
150
- return { vfs: mount(vfs, into, folded), stats, installed }
201
+ }
202
+ const tarballOf = new Map([...tarballs.values()].flatMap((group) => group.nodes.map((node) => [node, group])))
203
+ // With `lazy`, by the lockfile's integrity, and nothing a document says yet.
204
+ const installed = kept.map((node) => entryOf(node, fetched.get(node) ?? { integrity: tarballOf.get(node).tarball.integrity, about: NO_ABOUT }))
205
+ const tree = mount(vfs, into, folded)
206
+ if (!fetching.lazy) return { vfs: tree, stats, installed }
207
+ return { vfs: tree, stats, installed, unpack: lazyUnpacker({ vfs: tree, kept, tarballOf, settings, host, fetching, stats, folded, entryOf }) }
151
208
  }
@@ -208,12 +208,13 @@ export function hoistedBuilds(byDir, projects, builds, { hardlinks, keepsModules
208
208
  // tarball tells, and puts hardlinks of it in place of the others, dropping
209
209
  // their node_modules. A package of more than one copy, one with a
210
210
  // node_modules, may lose it. `placed` are the copies, as hoistedLayout
211
- // places them.
212
- export function checkNoneDropped(placed, pnpm) {
211
+ // places them; `option` the one the tree is laid out with, which does not
212
+ // know it: sizeEstimateOnly or lazy.
213
+ export function checkNoneDropped(placed, pnpm, option = 'sizeEstimateOnly') {
213
214
  const placedIn = new Set(placed.values().map((node) => node.modules))
214
215
  for (const [key, copies] of Map.groupBy(placed.values(), (node) => node.key)) {
215
216
  const nested = copies.length > 1 ? copies.find((copy) => placedIn.has(`${copy.dir}/node_modules`)) : undefined
216
- if (nested !== undefined) throw new DeptreeError(`pnpm ${pnpm} builds one of its copies where any patch is configured, if it is patched or has an install script, and makes the others hardlinks of it, dropping their node_modules: ${quote(`${nested.dir}/node_modules`)} may be dropped, which with sizeEstimateOnly is not known, and is not supported`, quote(key))
217
+ if (nested !== undefined) throw new DeptreeError(`pnpm ${pnpm} builds one of its copies where any patch is configured, if it is patched or has an install script, and makes the others hardlinks of it, dropping their node_modules: ${quote(`${nested.dir}/node_modules`)} may be dropped, which with ${option} is not known, and is not supported`, quote(key))
217
218
  }
218
219
  }
219
220
 
@@ -0,0 +1,132 @@
1
+ // A lazy tree's unpack (../lazy.js), for pnpm: each package written as the
2
+ // full tree writes it once asked for, and only then fetched.
3
+
4
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
5
+ import { Vfs } from '@preventive/vfs'
6
+ import { eachConcurrently, limited } from '../concurrent.js'
7
+ import { quote, refusalOf } from '../error.js'
8
+ import { unpacker, writeInto } from '../lazy.js'
9
+ import { NO_ABOUT, crlfShebang } from '../tarball.js'
10
+ import { executableMode } from './bins.js'
11
+ import { binsOf } from './commands.js'
12
+ import { checkFetched, fetchPackage } from './package.js'
13
+ import { compose, writeNode } from './write.js'
14
+
15
+ // Whether what is done to a package's files turns on other packages', once
16
+ // fetched: with the hoisted linker where any patch is configured, pnpm's
17
+ // build pass builds it (`builds`), patched or with an install script, which
18
+ // turns on its other copies and what else is built; or which of its bins pnpm
19
+ // links could change them, one linked being fixed otherwise than it is, made
20
+ // executable or its CRLF `#!` line made LF; or pnpm 9 and 12 fail on one that
21
+ // is a directory; or the package is patched, which is held to its bins as
22
+ // linked; or its commands cannot be read alone. Else its files are as fetched
23
+ // and patched, whatever pnpm links of its bins, and of anything else's.
24
+ export function bound(node, major, builds) {
25
+ if (builds?.(node)) return true
26
+ let bins
27
+ try {
28
+ bins = binsOf(node, node.manifest, node.files, major)
29
+ } catch {
30
+ return true
31
+ }
32
+ if (bins.size === 0) return false
33
+ if (node.pkg.patchHash !== undefined) return true
34
+ for (const path of bins.keys()) {
35
+ if ((major < 10 || major >= 12) && (path === '' || node.files.keys().some((name) => name.startsWith(`${path}/`)))) return true
36
+ const file = node.files.get(path)
37
+ if (file?.data === undefined) continue
38
+ if (executableMode(file.mode, major) !== file.mode || (major < 12 && crlfShebang(file.data) !== -1)) return true
39
+ }
40
+ return false
41
+ }
42
+
43
+ // What an unpacked package's files were, read back from the tree, which holds
44
+ // one neither patched nor bound as it came: but what the directories of the
45
+ // others among `dirs` hold within its own.
46
+ function filesIn(vfs, dir, dirs) {
47
+ const files = new Map()
48
+ for (const { path, type } of vfs.walk(`/${dir}`)) {
49
+ if (type !== 'file') continue
50
+ const rel = path.slice(dir.length + 2)
51
+ const names = rel.split('/')
52
+ let nested = false
53
+ for (let i = 1; i < names.length && !nested; i++) nested = dirs.has(`${dir}/${names.slice(0, i).join('/')}`)
54
+ if (!nested) files.set(rel, { data: vfs.readFile(path), mode: vfs.lstat(path).mode })
55
+ }
56
+ return files
57
+ }
58
+
59
+ // Each registry package fetched once for all its snapshots, a few at a time,
60
+ // and held to what the full tree holds it to; each snapshot written as the
61
+ // full tree writes it, `patched` and `composing` being what compose takes, and
62
+ // listed by `entryOf`. What linking bins fixes of it turns on the other
63
+ // packages' bins only where a package is bound (above): the first such
64
+ // unpack fetches every package not yet unpacked, and reads them all by
65
+ // `fixes`, as the full tree does: one unpacked before is read back from the
66
+ // tree, where it is as it came. A package's files are let go once it is
67
+ // unpacked, and its tarball once each of its snapshots is, but a patched
68
+ // one's, and every one's once the fixes are read.
69
+ export function lazyUnpacker({ vfs, byDir, stats, fixes, builds, checks, patched, composing, entryOf, fetching, folded }) {
70
+ const { major } = composing
71
+ const limit = limited()
72
+ const fetched = new Map()
73
+ const counted = new Set()
74
+ const left = new Map()
75
+ for (const node of byDir.values()) left.set(packageKeyOf(node.key), (left.get(packageKeyOf(node.key)) ?? 0) + 1)
76
+ let made
77
+
78
+ const fetchOnce = (node) => {
79
+ const id = packageKeyOf(node.key)
80
+ if (!fetched.has(id)) {
81
+ fetched.set(id, limit(() => fetchPackage(node.pkg, quote(id), major, fetching)).then((got) => {
82
+ counted.add(id)
83
+ stats.tarballs = counted.size
84
+ return got
85
+ }, (error) => {
86
+ throw refusalOf(error, quote(id))
87
+ }))
88
+ }
89
+ return fetched.get(id)
90
+ }
91
+ // A directory's files are read with the tree.
92
+ const prepare = async (node) => {
93
+ if (node.files !== undefined) return
94
+ if (node.unpacked) {
95
+ node.files = filesIn(vfs, node.dir, byDir)
96
+ return
97
+ }
98
+ const got = await fetchOnce(node)
99
+ checkFetched(node, got, checks)
100
+ Object.assign(node, { files: got.files, manifest: got.manifest, about: got.about ?? NO_ABOUT })
101
+ }
102
+ const allFixes = () => {
103
+ made ??= (async () => {
104
+ await eachConcurrently(byDir.values(), prepare, (node) => quote(node.key))
105
+ return fixes()
106
+ })()
107
+ return made
108
+ }
109
+ const release = (node) => {
110
+ const id = packageKeyOf(node.key)
111
+ left.set(id, left.get(id) - 1)
112
+ if (left.get(id) === 0) fetched.delete(id)
113
+ if (made === undefined && node.pkg.resolution.type !== 'directory' && node.pkg.patchHash === undefined) Object.assign(node, { files: undefined, unpacked: true })
114
+ }
115
+
116
+ return unpacker(new Map([...byDir.values()].map((node) => [node.dir, node])), async (node) => {
117
+ await prepare(node)
118
+ const { targets, executable } = bound(node, major, builds) ? await allFixes() : { targets: new Map(), executable: new Map() }
119
+ const tree = new Vfs()
120
+ const written = { files: 0, bytes: 0 }
121
+ try {
122
+ writeNode(tree, node.dir, compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), written)
123
+ writeInto(vfs, tree, folded)
124
+ } catch (error) {
125
+ throw refusalOf(error, quote(node.key))
126
+ }
127
+ stats.files += written.files
128
+ stats.bytes += written.bytes
129
+ release(node)
130
+ return entryOf(node)
131
+ })
132
+ }
@@ -3,6 +3,7 @@
3
3
  // dependency the lockfile left out of a snapshot would leave the package to
4
4
  // find it wherever it is hoisted, if anywhere.
5
5
 
6
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
6
7
  import { normalize } from '@preventive/vfs/path.js'
7
8
  import { DeptreeError, quote } from '../error.js'
8
9
  import { checkNesting } from '../manifest.js'
@@ -120,6 +121,15 @@ export function checkDependencies(manifest, read, pkg, packages, where) {
120
121
  }
121
122
  }
122
123
 
124
+ // What is held of a package's files once fetched, for one of its snapshots:
125
+ // its package.json, as the hook has it, asks for what the snapshot gives it.
126
+ export function checkFetched(node, got, { lockfile, hook, fresh }) {
127
+ if (got.manifest === undefined) return
128
+ got.read ??= hook(got.manifest, `${quote(packageKeyOf(node.key))}: package.json`)
129
+ checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
130
+ fresh?.(node, got.read)
131
+ }
132
+
123
133
  export async function fetchPackage(pkg, where, major, fetching) {
124
134
  const { entries, about } = await fetchTarball(pkg.name, pkg.version, pkg.resolution.integrity, where, fetching)
125
135
  const files = filesOf(entries, where)
package/src/pnpm/tree.js CHANGED
@@ -4,6 +4,8 @@
4
4
  // not linked, though what linking does to their files is (bins.js). With
5
5
  // `sizeEstimateOnly`, its directories and links alone, each package's sized
6
6
  // by its version document, of which nothing is fetched but those documents.
7
+ // With `lazy`, its directories and links alone too, fetching nothing, and
8
+ // each package unpacked into it as it is asked for (lazy.js).
7
9
 
8
10
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
9
11
  import { compareVersions } from '@preventive/upstream/semver.js'
@@ -11,17 +13,17 @@ import { Vfs } from '@preventive/vfs'
11
13
  import { dirname, relative } from '@preventive/vfs/path.js'
12
14
  import { eachConcurrently } from '../concurrent.js'
13
15
  import { DeptreeError, quote, refusalOf } from '../error.js'
14
- import { checkNoModules, checkWrite, fold, isInside, makeDirs, mount, writeLink } from '../mount.js'
15
- import { applyPatch, parsePatch } from '../patch.js'
16
- import { checkProject, typeOf } from '../project.js'
16
+ import { checkNoModules, fold, makeDirs, mount, writeLink } from '../mount.js'
17
+ import { checkProject } from '../project.js'
17
18
  import { NO_ABOUT, REGISTRY, fetchSize, fetchingOf, tarballUrl } from '../tarball.js'
18
- import { binTargets, checkPatchOfBins, executableMode, fixBin, hoistedBinTargets, requiresBuild } from './bins.js'
19
+ import { binTargets, hoistedBinTargets, requiresBuild } from './bins.js'
19
20
  import { buildGraph } from './graph.js'
20
21
  import { hoist } from './hoist.js'
21
22
  import { checkNoneDropped, hoistedBuilds, hoistedLayout, hoistedModules, packageIdOf, prodPackages, workspaceHoists } from './hoisted.js'
22
23
  import { checkLocalOverrides, createFreshnessCheck, readDirectoryPackage, readLinked } from './local.js'
23
24
  import { createPatchedCheck, skippedSnapshots } from './install.js'
24
- import { checkDependencies, fetchPackage } from './package.js'
25
+ import { lazyUnpacker } from './lazy.js'
26
+ import { checkFetched, fetchPackage } from './package.js'
25
27
  import { checkLinks, checkOptional } from './checks.js'
26
28
  import { createHook } from './hook.js'
27
29
  import { listOverrides } from './overrides.js'
@@ -30,6 +32,7 @@ import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
30
32
  import { readSettings } from './settings.js'
31
33
  import { checkUpToDate } from './uptodate.js'
32
34
  import { checkWorkspace } from './workspace.js'
35
+ import { compose, parsedPatch, writeNode } from './write.js'
33
36
 
34
37
  // A project inside a node_modules would be inside the tree; on macOS, a
35
38
  // node_modules in any case is one.
@@ -71,8 +74,9 @@ const bytesOf = (files) => files.values().reduce((sum, file) => sum + file.data.
71
74
 
72
75
  // By name@version, as the lockfile reader gives a package's snapshots one
73
76
  // resolution and manifest. With `sizeEstimateOnly`, a registry package's size
74
- // alone, with no files or package.json; a directory is read whole all the
75
- // same, and its size is its files'.
77
+ // alone, with no files or package.json; with `lazy`, nothing of one, which is
78
+ // fetched as it is unpacked. A directory is read whole all the same, and its
79
+ // size is its files'.
76
80
  async function fetchAll(nodes, project, host, fetching) {
77
81
  const packages = new Map([...nodes.values()].map(({ key, pkg }) => [packageKeyOf(key), pkg]))
78
82
  const fetched = new Map()
@@ -82,26 +86,24 @@ async function fetchAll(nodes, project, host, fetching) {
82
86
  return fetching.sizeEstimateOnly ? { ...got, size: bytesOf(got.files) } : got
83
87
  }
84
88
  await eachConcurrently(packages, async ([id, pkg]) => {
85
- fetched.set(id, pkg.resolution.type === 'directory' ? read(pkg, quote(id)) : await fetch(pkg, quote(id)))
89
+ if (pkg.resolution.type === 'directory') fetched.set(id, read(pkg, quote(id)))
90
+ else if (!fetching.lazy) fetched.set(id, await fetch(pkg, quote(id)))
86
91
  }, ([id]) => quote(id))
87
92
  return fetched
88
93
  }
89
94
 
95
+ // With `lazy`, a registry package's snapshots have no files yet, and are held
96
+ // to them as each is unpacked; `checks` are what that takes.
90
97
  async function fetchNodes(nodes, lockfile, hook, project, host, fetching) {
91
98
  const fetched = await fetchAll(nodes, project, host, fetching)
92
- const fresh = createFreshnessCheck(lockfile, host.major)
99
+ const checks = { lockfile, hook, fresh: createFreshnessCheck(lockfile, host.major) }
93
100
  const byDir = new Map()
94
101
  for (const node of nodes.values()) {
95
- const id = packageKeyOf(node.key)
96
- const got = fetched.get(id)
97
- if (got.manifest !== undefined) {
98
- got.read ??= hook(got.manifest, `${quote(id)}: package.json`)
99
- checkDependencies(got.manifest, got.read, node.pkg, lockfile.packages, quote(node.key))
100
- fresh?.(node, got.read)
101
- }
102
- byDir.set(node.dir, { ...node, files: got.files, manifest: got.manifest, about: got.about ?? NO_ABOUT, size: got.size })
102
+ const got = fetched.get(packageKeyOf(node.key))
103
+ if (got !== undefined) checkFetched(node, got, checks)
104
+ byDir.set(node.dir, { ...node, files: got?.files, manifest: got?.manifest, about: got?.about ?? NO_ABOUT, size: got?.size })
103
105
  }
104
- return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length }
106
+ return { byDir, tarballs: [...fetched.values()].filter((got) => !got.local).length, checks }
105
107
  }
106
108
 
107
109
  // pnpm hardlinks a directory package's files into each of its snapshots, so a
@@ -119,65 +121,6 @@ function executableElsewhere(byDir, targets, packageImportMethod, major) {
119
121
  }))
120
122
  }
121
123
 
122
- // A patch of `patches`, parsed once.
123
- function parsedPatch(patches, hash) {
124
- const patch = patches.get(hash)
125
- patch.parsed ??= parsePatch(patch.text, patch.path)
126
- return patch
127
- }
128
-
129
- function compose(node, patches, { targets, executable }, { major, checkPatched }) {
130
- const where = quote(node.key)
131
- let files = node.files
132
- const { patchHash } = node.pkg
133
- if (patchHash !== undefined) {
134
- const patch = parsedPatch(patches, patchHash)
135
- patch.applied ??= new WeakMap()
136
- if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
137
- files = patch.applied.get(files)
138
- const manifest = checkPatchOfBins(node, files, targets, where, major)
139
- checkPatched?.(manifest, where)
140
- }
141
- if (targets.size === 0 && executable.size === 0) return files
142
- files = new Map(files)
143
- for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
144
- for (const path of executable) files.set(path, { ...files.get(path), mode: executableMode(files.get(path).mode, major) })
145
- return files
146
- }
147
-
148
- function addMade(made, dir) {
149
- for (let at = dir; !made.has(at) && at !== '/'; at = dirname(at)) made.add(at)
150
- }
151
-
152
- // Only this node writes under `dir`, and the tree holds no links yet, so `made`
153
- // knows every directory there and no write needs a look first, which costs a
154
- // thrown error where nothing is.
155
- function writeNode(vfs, dir, files, stats) {
156
- const root = `/${dir}`
157
- if (typeOf(vfs, root, false) !== undefined) throw new DeptreeError('would be written over with something else', quote(dir))
158
- const real = new Set()
159
- makeDirs(vfs, dir, real)
160
- const made = new Set([root])
161
- for (const [path, file] of files) {
162
- const at = `${root}/${path}`
163
- if (file.directory) {
164
- if (!isInside(path)) throw new DeptreeError('is not a path within the package', quote(at.slice(1)))
165
- makeDirs(vfs, at.slice(1), real)
166
- addMade(made, at)
167
- continue
168
- }
169
- if (made.has(at)) throw new DeptreeError('would be written over with something else', quote(at.slice(1)))
170
- const parent = dirname(at)
171
- if (!made.has(parent)) {
172
- makeDirs(vfs, parent.slice(1), real)
173
- addMade(made, parent)
174
- }
175
- vfs.writeFile(checkWrite(vfs, dir, path, real), file.data, { mode: file.mode })
176
- stats.files++
177
- stats.bytes += file.data.length
178
- }
179
- }
180
-
181
124
  // As pnpm's symlink-dir spells it. A target may climb out of the tree, so both
182
125
  // are resolved under as many dummy directories as it climbs.
183
126
  function linkTarget(path, target) {
@@ -235,8 +178,11 @@ const COPYING = new Set(['copy', 'clone', 'clone-or-copy'])
235
178
 
236
179
  // The hoisted layout of pnpm 10 and 11 (hoisted.js): nothing but the packages
237
180
  // and links, each copy a parent before what lands in its node_modules, as
238
- // pnpm keeps only its state in node_modules/.pnpm. With `sizeEstimateOnly`,
239
- // what pnpm's build pass does to the files is not followed.
181
+ // pnpm keeps only its state in node_modules/.pnpm. `fixes` are what linking
182
+ // bins does to the files, with what pnpm's build pass does to them, read once
183
+ // every package's files are at hand; with `sizeEstimateOnly` they are not
184
+ // followed, nor with `lazy` but where a package unpacked needs them. `builds`
185
+ // tells, where any patch is configured, what the build pass builds.
240
186
  async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching }) {
241
187
  const { major } = host
242
188
  const since = (version) => compareVersions(host.pnpm, version) >= 0
@@ -251,42 +197,47 @@ async function buildHoisted({ lockfile, settings, host, project, hook, installed
251
197
  const building = Object.keys(settings.patchedDependencies ?? {}).length > 0
252
198
  const hardlinks = since('10.21.0')
253
199
  const keepsModules = since('11.25.0')
254
- if (fetching.sizeEstimateOnly && building && hardlinks && !keepsModules) checkNoneDropped(placed, host.pnpm)
255
- const { byDir, tarballs } = await fetchNodes(placed, lockfile, hook, project, host, fetching)
200
+ if ((fetching.sizeEstimateOnly || fetching.lazy) && building && hardlinks && !keepsModules) checkNoneDropped(placed, host.pnpm, fetching.lazy ? 'lazy' : 'sizeEstimateOnly')
201
+ const { byDir, tarballs, checks } = await fetchNodes(placed, lockfile, hook, project, host, fetching)
256
202
  const linked = readLinked(links, byDir, manifests, project)
257
203
  const prod = prodPackages(lockfile, skipped, directories)
258
204
  const dev = (node) => !prod.has(packageIdOf(node.key, node.pkg, directories))
259
- if (fetching.sizeEstimateOnly) return { byDir, links, targets: new Map(), executable: new Map(), tarballs, dev }
260
- const idOf = since('11.23.0') ? (key) => packageIdOf(key, lockfile.packages[key], directories) : (key) => key
261
- const changesOf = (node) => parsedPatch(patched, node.pkg.patchHash).parsed
262
- const builds = building ? hoistedBuilds(byDir, new Set(projects), (node) => node.pkg.patchHash !== undefined || requiresBuild(node.manifest, node.files, major), { hardlinks, keepsModules, idOf, changesOf, pnpm: host.pnpm }) : []
263
- const targets = hoistedBinTargets({ nodes: byDir, projects: new Map([...manifests, ...linked]), modules: hoistedModules(byDir, links, projects, manifests, lockfile), builds, hardlinks, keepsModules, idOf, major })
264
- return { byDir, links, targets, executable: new Map(), tarballs, dev }
205
+ const builds = building ? (node) => node.pkg.patchHash !== undefined || requiresBuild(node.manifest, node.files, major) : undefined
206
+ const fixes = () => {
207
+ const idOf = since('11.23.0') ? (key) => packageIdOf(key, lockfile.packages[key], directories) : (key) => key
208
+ const changesOf = (node) => parsedPatch(patched, node.pkg.patchHash).parsed
209
+ const built = building ? hoistedBuilds(byDir, new Set(projects), builds, { hardlinks, keepsModules, idOf, changesOf, pnpm: host.pnpm }) : []
210
+ const targets = hoistedBinTargets({ nodes: byDir, projects: new Map([...manifests, ...linked]), modules: hoistedModules(byDir, links, projects, manifests, lockfile), builds: built, hardlinks, keepsModules, idOf, major })
211
+ return { targets, executable: new Map() }
212
+ }
213
+ return { byDir, links, fixes, builds, tarballs, dev, checks }
265
214
  }
266
215
 
267
216
  // The isolated layout: each package in node_modules/.pnpm, linked from what
268
- // needs it and where it is hoisted.
217
+ // needs it and where it is hoisted; `fixes` as buildHoisted's.
269
218
  async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped, fetching }) {
270
219
  const { major } = host
271
220
  const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
272
221
  for (const node of nodes.values()) checkSource(node, installed)
273
- const { byDir, tarballs } = await fetchNodes(nodes, lockfile, hook, project, host, fetching)
222
+ const { byDir, tarballs, checks } = await fetchNodes(nodes, lockfile, hook, project, host, fetching)
274
223
  const links = linksOf(byDir, direct, settings, names, major, hoisting)
275
224
  const linked = readLinked(links, byDir, manifests, project)
276
225
  const prod = reachedInProd(lockfile.importers, nodes, byDir)
277
226
  const dev = (node) => !prod.has(node.dir)
278
- if (fetching.sizeEstimateOnly) return { byDir, links, targets: new Map(), executable: new Map(), tarballs, dev }
279
- const targets = binTargets({
280
- nodes: byDir,
281
- projects: new Map([...manifests, ...linked]),
282
- direct,
283
- links,
284
- publicHoist: settings.publicHoistPattern?.length > 0,
285
- building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
286
- peers: settings.autoInstallPeers,
287
- major,
288
- })
289
- return { byDir, links, targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major), tarballs, dev }
227
+ const fixes = () => {
228
+ const targets = binTargets({
229
+ nodes: byDir,
230
+ projects: new Map([...manifests, ...linked]),
231
+ direct,
232
+ links,
233
+ publicHoist: settings.publicHoistPattern?.length > 0,
234
+ building: Object.keys(settings.patchedDependencies ?? {}).length > 0,
235
+ peers: settings.autoInstallPeers,
236
+ major,
237
+ })
238
+ return { targets, executable: executableElsewhere(byDir, targets, settings.packageImportMethod, major) }
239
+ }
240
+ return { byDir, links, fixes, tarballs, dev, checks }
290
241
  }
291
242
 
292
243
  export async function buildPnpmTree(options) {
@@ -294,6 +245,7 @@ export async function buildPnpmTree(options) {
294
245
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
295
246
  const fetching = fetchingOf(options ?? {})
296
247
  if (fetching.sizeEstimateOnly && into !== undefined) throw new TypeError('vfs is not taken with sizeEstimateOnly, whose tree has no files to mount')
248
+ if (fetching.lazy && into !== undefined) throw new TypeError('vfs is not taken with lazy, whose tree is unpacked a package at a time')
297
249
  if (project !== undefined) checkProject(project)
298
250
  const machine = checkHost(given)
299
251
  const folded = machine.os === 'darwin'
@@ -326,7 +278,9 @@ export async function buildPnpmTree(options) {
326
278
  const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
327
279
  const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
328
280
  const hoisted = settings.nodeLinker === 'hoisted'
329
- const { byDir, links, targets, executable, tarballs, dev } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
281
+ const { byDir, links, fixes, builds, tarballs, dev, checks } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
282
+ const laidOut = fetching.sizeEstimateOnly || fetching.lazy
283
+ const { targets, executable } = laidOut ? { targets: new Map(), executable: new Map() } : fixes()
330
284
 
331
285
  const vfs = new Vfs()
332
286
  if (!hoisted) makeDirs(vfs, 'node_modules/.pnpm')
@@ -335,11 +289,11 @@ export async function buildPnpmTree(options) {
335
289
  const composing = { major, checkPatched: createPatchedCheck({ host, settings }) }
336
290
  // Each node is let go once written, and a package's files with its last.
337
291
  // With `sizeEstimateOnly`, its directory alone is made, and its size
338
- // counted.
292
+ // counted; with `lazy`, its directory alone, and the node is kept to unpack.
339
293
  for (const node of byDir.values()) {
340
- byDir.delete(node.dir)
294
+ if (!fetching.lazy) byDir.delete(node.dir)
341
295
  try {
342
- writeNode(vfs, node.dir, fetching.sizeEstimateOnly ? new Map() : compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
296
+ writeNode(vfs, node.dir, laidOut ? new Map() : compose(node, patched, { targets: targets.get(node.dir) ?? new Set(), executable: executable.get(node.dir) ?? new Set() }, composing), stats)
343
297
  } catch (error) {
344
298
  throw refusalOf(error, quote(node.key))
345
299
  }
@@ -354,5 +308,8 @@ export async function buildPnpmTree(options) {
354
308
  }
355
309
  }
356
310
  checkLinks(vfs, links)
357
- return { vfs: mount(vfs, into, folded), stats, installed: listed }
311
+ const tree = mount(vfs, into, folded)
312
+ if (!fetching.lazy) return { vfs: tree, stats, installed: listed }
313
+ const entryOf = (node) => installedOf(node, dev(node), patched, false)
314
+ return { vfs: tree, stats, installed: listed, unpack: lazyUnpacker({ vfs: tree, byDir, stats, fixes, builds, checks, patched, composing, entryOf, fetching, folded }) }
358
315
  }
@@ -0,0 +1,69 @@
1
+ // How a snapshot's files are written: patched, and fixed as linking bins
2
+ // fixes them, then each into the tree, as the full tree and a lazy one
3
+ // write them.
4
+
5
+ import { dirname } from '@preventive/vfs/path.js'
6
+ import { DeptreeError, quote } from '../error.js'
7
+ import { checkWrite, isInside, makeDirs } from '../mount.js'
8
+ import { applyPatch, parsePatch } from '../patch.js'
9
+ import { typeOf } from '../project.js'
10
+ import { checkPatchOfBins, executableMode, fixBin } from './bins.js'
11
+
12
+ // A patch of `patches`, parsed once.
13
+ export function parsedPatch(patches, hash) {
14
+ const patch = patches.get(hash)
15
+ patch.parsed ??= parsePatch(patch.text, patch.path)
16
+ return patch
17
+ }
18
+
19
+ export function compose(node, patches, { targets, executable }, { major, checkPatched }) {
20
+ const where = quote(node.key)
21
+ let files = node.files
22
+ const { patchHash } = node.pkg
23
+ if (patchHash !== undefined) {
24
+ const patch = parsedPatch(patches, patchHash)
25
+ patch.applied ??= new WeakMap()
26
+ if (!patch.applied.has(files)) patch.applied.set(files, applyPatch(files, patch.parsed, { createdMode: major >= 12 ? 0o644 : undefined }))
27
+ files = patch.applied.get(files)
28
+ const manifest = checkPatchOfBins(node, files, targets, where, major)
29
+ checkPatched?.(manifest, where)
30
+ }
31
+ if (targets.size === 0 && executable.size === 0) return files
32
+ files = new Map(files)
33
+ for (const path of targets) files.set(path, fixBin(files.get(path), `${where}: ${quote(path)}`, major))
34
+ for (const path of executable) files.set(path, { ...files.get(path), mode: executableMode(files.get(path).mode, major) })
35
+ return files
36
+ }
37
+
38
+ function addMade(made, dir) {
39
+ for (let at = dir; !made.has(at) && at !== '/'; at = dirname(at)) made.add(at)
40
+ }
41
+
42
+ // Only this node writes under `dir`, and the tree holds no links yet, so `made`
43
+ // knows every directory there and no write needs a look first, which costs a
44
+ // thrown error where nothing is.
45
+ export function writeNode(vfs, dir, files, stats) {
46
+ const root = `/${dir}`
47
+ if (typeOf(vfs, root, false) !== undefined) throw new DeptreeError('would be written over with something else', quote(dir))
48
+ const real = new Set()
49
+ makeDirs(vfs, dir, real)
50
+ const made = new Set([root])
51
+ for (const [path, file] of files) {
52
+ const at = `${root}/${path}`
53
+ if (file.directory) {
54
+ if (!isInside(path)) throw new DeptreeError('is not a path within the package', quote(at.slice(1)))
55
+ makeDirs(vfs, at.slice(1), real)
56
+ addMade(made, at)
57
+ continue
58
+ }
59
+ if (made.has(at)) throw new DeptreeError('would be written over with something else', quote(at.slice(1)))
60
+ const parent = dirname(at)
61
+ if (!made.has(parent)) {
62
+ makeDirs(vfs, parent.slice(1), real)
63
+ addMade(made, parent)
64
+ }
65
+ vfs.writeFile(checkWrite(vfs, dir, path, real), file.data, { mode: file.mode })
66
+ stats.files++
67
+ stats.bytes += file.data.length
68
+ }
69
+ }
package/src/tarball.js CHANGED
@@ -89,16 +89,20 @@ export const NO_ABOUT = Object.freeze(aboutOf({}))
89
89
 
90
90
  // What a tree's options say of what it fetches from npm's registry:
91
91
  // `metadata`, true unless given false; `cache`, as upstream's CacheOptions
92
- // take it, which keeps each version's document and tarball; and
92
+ // take it, which keeps each version's document and tarball;
93
93
  // `sizeEstimateOnly`, false unless given true, for each version's document
94
- // alone (fetchSize).
95
- export function fetchingOf({ metadata = true, cache, sizeEstimateOnly = false }) {
94
+ // alone (fetchSize); and `lazy`, false unless given true, for nothing until a
95
+ // package is unpacked, and then its tarball, as without it. The two are
96
+ // refused together: a tree is laid out with sizes alone, or to be unpacked.
97
+ export function fetchingOf({ metadata = true, cache, sizeEstimateOnly = false, lazy = false }) {
96
98
  if (typeof metadata !== 'boolean') throw new TypeError('metadata must be a boolean, or left out')
97
99
  if (cache !== undefined && cache !== false && (typeof cache?.read !== 'function' || typeof cache?.write !== 'function')) {
98
100
  throw new TypeError('cache must be false, or a store with read and write, or left out')
99
101
  }
100
102
  if (typeof sizeEstimateOnly !== 'boolean') throw new TypeError('sizeEstimateOnly must be a boolean, or left out')
101
- return { metadata, cache, sizeEstimateOnly }
103
+ if (typeof lazy !== 'boolean') throw new TypeError('lazy must be a boolean, or left out')
104
+ if (lazy && sizeEstimateOnly) throw new TypeError('lazy is not taken with sizeEstimateOnly, which fetches no tarball to unpack')
105
+ return { metadata, cache, sizeEstimateOnly, lazy }
102
106
  }
103
107
 
104
108
  const SHA512 = /^sha512-[\d+/A-Za-z]{86}==$/u
package/src/yarn1/tree.js CHANGED
@@ -195,7 +195,9 @@ export async function buildYarn1Tree(options) {
195
195
  const { host: given, vfs: into } = options ?? {}
196
196
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
197
197
  const fetching = fetchingOf(options ?? {})
198
- if (fetching.sizeEstimateOnly) throw new TypeError('sizeEstimateOnly is not taken for yarn 1, which hoists and leaves out packages by what their package.json says, which only their tarballs hold')
198
+ for (const option of ['sizeEstimateOnly', 'lazy']) {
199
+ if (fetching[option]) throw new TypeError(`${option} is not taken for yarn 1, which hoists and leaves out packages by what their package.json says, which only their tarballs hold`)
200
+ }
199
201
  const inputs = inputsOf(options ?? {})
200
202
  const host = checkHost(given, inputs.manifests.get('.'))
201
203
  const folded = host.os === 'darwin'
package/yarn1.d.ts CHANGED
@@ -144,10 +144,10 @@ export interface Yarn1Project {
144
144
  // cache is read all the same. Other tools' caches are read for tarballs
145
145
  // whatever it is. A TypeError is thrown for anything else.
146
146
  //
147
- // `sizeEstimateOnly`, which buildPnpmTree and buildNpmTree take for a tree's
148
- // directories and links alone, is not taken, as yarn hoists and leaves out
149
- // packages by what their package.json says, which only their tarballs
150
- // hold: a TypeError is thrown for it given true.
147
+ // `sizeEstimateOnly` and `lazy`, which buildPnpmTree and buildNpmTree take
148
+ // for a tree's directories and links alone, are not taken, as yarn hoists
149
+ // and leaves out packages by what their package.json says, which only their
150
+ // tarballs hold: a TypeError is thrown for either given true.
151
151
  //
152
152
  // The two ways the files come, one or the other: given, with `lockfile`
153
153
  // and `manifests`; or read, with `project` and none of them. `project`