@preventive/deptree 1.2.0 → 1.3.1

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/bin/deptree.js CHANGED
@@ -47,6 +47,8 @@ GITHUB_TOKEN or GH_TOKEN, else anonymously.
47
47
  packageManager pins, or Soldeer 0.12.0; npm's and
48
48
  cargo's are needed
49
49
  --node <version> the Node it installed with; by default this one
50
+ --production devDependencies were left out, as by pnpm install
51
+ --prod, npm ci --omit=dev or yarn install --production
50
52
  --metadata fetch each package's version document from npm's
51
53
  registry too, and hold its tarball's dist to it
52
54
  --all list what is left out too
@@ -63,6 +65,7 @@ const OPTIONS = {
63
65
  cargo: { type: 'string' },
64
66
  node: { type: 'string' },
65
67
  metadata: { type: 'boolean', default: false },
68
+ production: { type: 'boolean', default: false },
66
69
  all: { type: 'boolean' },
67
70
  diff: { type: 'boolean' },
68
71
  help: { type: 'boolean', short: 'h' },
@@ -70,7 +73,8 @@ const OPTIONS = {
70
73
 
71
74
  // Each package manager by its version flag: its lockfile, the folder it
72
75
  // installs into in each project it finds, and the version where the flag is
73
- // left out and nothing pins one, or, `unpinned`, that the flag is needed.
76
+ // left out and nothing pins one, or, `unpinned`, that the flag is needed;
77
+ // `development`, that it installs every dependency, there being no other kind.
74
78
  const MANAGERS = {
75
79
  pnpm: { lockfile: 'pnpm-lock.yaml', folder: 'node_modules', projects: findPnpmProjects, build: buildPnpmTree },
76
80
  yarn: { lockfile: 'yarn.lock', folder: 'node_modules', projects: findYarn1Workspaces, build: buildYarn1Tree },
@@ -79,10 +83,11 @@ const MANAGERS = {
79
83
  lockfile: 'soldeer.lock',
80
84
  folder: 'dependencies',
81
85
  version: '0.12.0',
86
+ development: true,
82
87
  projects: () => ['.'],
83
88
  build: (options) => buildSoldeerTree({ ...options, github: createClient({ token: process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null }) }),
84
89
  },
85
- cargo: { lockfile: 'Cargo.lock', folder: 'vendor', unpinned: true, projects: () => ['.'], build: buildCargoTree },
90
+ cargo: { lockfile: 'Cargo.lock', folder: 'vendor', unpinned: true, development: true, projects: () => ['.'], build: buildCargoTree },
86
91
  }
87
92
 
88
93
  async function main(argv) {
@@ -96,6 +101,7 @@ async function main(argv) {
96
101
  const project = projectView(resolve(dir))
97
102
  const name = managerOf(project, dir, values)
98
103
  const manager = MANAGERS[name]
104
+ if (values.production && manager.development) fail(`deptree: ${manager.lockfile}: --production is not taken: ${name === 'cargo' ? 'cargo vendor vendors dev-dependencies too' : 'Soldeer has no devDependencies to leave out'}\n`)
99
105
  if (defaultCacheDir !== undefined) setCacheDir()
100
106
  // upstream reads it for each request, and sends it for a scoped package.
101
107
  process.env.NPM_TOKEN ||= userToken() ?? ''
@@ -108,7 +114,7 @@ async function main(argv) {
108
114
  const disk = readSide(project, dirs)
109
115
  const files = [...disk.values()].filter((entry) => entry.type === 'file')
110
116
  note(`${manager.folder} on disk: ${files.length} files, ${size(files.reduce((sum, file) => sum + file.data.length, 0))}`)
111
- const tree = await manager.build({ project, host, metadata: values.metadata })
117
+ const tree = await manager.build({ project, host, metadata: values.metadata, ...values.production ? { production: true } : {} })
112
118
  note(`${manager.lockfile}: ${tree.stats.files} files, ${size(tree.stats.bytes)} built`)
113
119
  const built = readSide(tree.vfs, dirs)
114
120
  const changes = difference(disk, built)
package/npm.d.ts CHANGED
@@ -92,7 +92,8 @@ export interface NpmProject {
92
92
  // otherwise. omit, include, production, dev, only, also, optional, os,
93
93
  // cpu, libc, workspace, workspaces, location, umask, prefix, globalconfig,
94
94
  // userconfig, allow-scripts and a credential not scoped to a registry are
95
- // refused, whatever their value; so are two settings npm takes as
95
+ // refused, whatever their value, which of the dependencies are installed
96
+ // being `production`'s to say; so are two settings npm takes as
96
97
  // exclusive, set together, and a section. Any other setting is passed
97
98
  // over: npm reads it for where it fetches from, how, what it prints, or
98
99
  // another command, and the tree is held to the lockfile's integrities
@@ -152,6 +153,18 @@ export interface NpmProject {
152
153
  // a lockfile one of those checks would refuse is laid out all the same, and
153
154
  // refused where that package is unpacked. A `vfs` is not taken with it, nor
154
155
  // `sizeEstimateOnly`.
156
+ //
157
+ // `production`, false unless given true, builds the tree `npm ci
158
+ // --omit=dev` makes: each package the lockfile's flags, as npm takes them,
159
+ // say dev dependencies alone reach is left out, as is what is beneath it,
160
+ // and its bins are linked by none of its names. npm 10 makes every
161
+ // package's directory before it leaves those out, and so leaves the
162
+ // directories they were in, a scope's or a workspace's node_modules, which
163
+ // the tree has too, empty; it holds each of them that is not optional to
164
+ // the host as without it, and leaves out nothing for one that is and that
165
+ // the host cannot run. npm 11 holds to the host none of them but those that
166
+ // are optional, each left out with its optionalSet where the host cannot
167
+ // run it, as without it. A workspace is linked all the same.
155
168
  export type NpmTreeOptions = NpmTreeGiven | NpmTreeRead
156
169
 
157
170
  export type NpmLayoutOptions = NpmTreeOptions & { sizeEstimateOnly: true, vfs?: undefined }
@@ -169,6 +182,7 @@ export interface NpmTreeGiven {
169
182
  cache?: CacheOptions['cache']
170
183
  sizeEstimateOnly?: boolean
171
184
  lazy?: boolean
185
+ production?: boolean
172
186
  }
173
187
 
174
188
  export interface NpmTreeRead {
@@ -182,6 +196,7 @@ export interface NpmTreeRead {
182
196
  cache?: CacheOptions['cache']
183
197
  sizeEstimateOnly?: boolean
184
198
  lazy?: boolean
199
+ production?: boolean
185
200
  }
186
201
 
187
202
  // What buildNpmTree counts, all of it plain numbers: `packages` the
@@ -193,7 +208,8 @@ export interface NpmTreeRead {
193
208
  // is 0, as none is written, and `bytes` what the sizes of those installed
194
209
  // add up to, each copy's, of those with one. With `lazy`, `tarballs`,
195
210
  // `files` and `bytes` count what is unpacked, each 0 until `unpack` is
196
- // asked, which adds to them.
211
+ // asked, which adds to them. With `production`, those it leaves out are
212
+ // counted in neither `installed` nor `skipped`.
197
213
  export interface NpmTreeStats {
198
214
  packages: number
199
215
  installed: number
@@ -218,7 +234,8 @@ export interface NpmTreeStats {
218
234
  // those
219
235
  // npm installs by, the lockfile's as npm 10 takes them and as npm 11 works
220
236
  // them out again: `dev` is whether dev dependencies alone reach it, which
221
- // --omit=dev leaves out; `optional` whether optional dependencies alone
237
+ // --omit=dev leaves out, and so none is with `production`; `optional`
238
+ // whether optional dependencies alone
222
239
  // reach it, which --omit=optional leaves out; `devOptional` whether either
223
240
  // is, or both together, which --omit=dev with --omit=optional leaves out;
224
241
  // `peer` whether peer dependencies alone reach it, which --omit=peer
@@ -276,13 +293,13 @@ export interface NpmLazyTree extends NpmTree {
276
293
  unpack(paths: Iterable<string>): Promise<NpmInstalled[]>
277
294
  }
278
295
 
279
- // The node_modules tree `npm ci --ignore-scripts` makes, with host.npm,
280
- // into a project with no node_modules yet: rooted at the lockfile's
281
- // directory, each package's files unpacked where the lockfile puts it,
282
- // and each workspace linked as node_modules/<its name>, by a relative link
283
- // to its directory, with what the lockfile puts beneath it in that
284
- // directory's own node_modules. The tree holds node_modules and nothing
285
- // else of the projects.
296
+ // The node_modules tree `npm ci --ignore-scripts` makes, with `production`
297
+ // --omit=dev too, with host.npm, into a project with no node_modules yet:
298
+ // rooted at the lockfile's directory, each package's files unpacked where
299
+ // the lockfile puts it, and each workspace linked as node_modules/<its
300
+ // name>, by a relative link to its directory, with what the lockfile puts
301
+ // beneath it in that directory's own node_modules. The tree holds
302
+ // node_modules and nothing else of the projects.
286
303
  //
287
304
  // Each package is unpacked as npm's tar unpacks it: the first segment of
288
305
  // each name dropped; a file alone kept, so that a link, a device and a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/deptree",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "In-memory dependency tree, as a package manager installs it",
5
5
  "type": "module",
6
6
  "exports": {
@@ -94,6 +94,7 @@
94
94
  "src/pnpm/package.js",
95
95
  "src/pnpm/packlist.js",
96
96
  "src/pnpm/patches.js",
97
+ "src/pnpm/production.js",
97
98
  "src/pnpm/projects.js",
98
99
  "src/pnpm/readers.js",
99
100
  "src/pnpm/settings.js",
@@ -147,11 +148,11 @@
147
148
  "dependencies": {
148
149
  "@chalker/queue": "^1.0.1",
149
150
  "@exodus/bytes": "^1.16.0",
150
- "@preventive/archive": "^1.2.0",
151
+ "@preventive/archive": "^1.2.1",
151
152
  "@preventive/compare": "^1.2.11",
152
153
  "@preventive/diff": "^1.1.0",
153
154
  "@preventive/lockfile": "^1.2.0",
154
155
  "@preventive/upstream": "^1.3.0",
155
- "@preventive/vfs": "1.0.0-beta.4"
156
+ "@preventive/vfs": "^1.0.0"
156
157
  }
157
158
  }
package/pnpm.d.ts CHANGED
@@ -302,6 +302,27 @@ export interface PnpmProject {
302
302
  // pnpm builds the package. A
303
303
  // `vfs` is not taken with it, nor `sizeEstimateOnly`.
304
304
  //
305
+ // `production`, false unless given true, builds the tree `pnpm install
306
+ // --prod` makes, from the lockfile pnpm leaves of it: each project's
307
+ // devDependencies dropped, a `link:` among them, and of the snapshots
308
+ // those the rest reach, through dependencies, optionalDependencies and the
309
+ // projects they link to. The tree is laid out of those alone -- what the
310
+ // host cannot run left out as pnpm walks them, hoisted, its bins linked --
311
+ // as without it, save that pnpm 9 keeps from hoisting each name the root's
312
+ // specifiers have, a devDependency's among them. Nothing else is fetched,
313
+ // nor its files checked; all else is held to the whole lockfile, as
314
+ // without it. From pnpm 11.28.0, and in pnpm 12, an edge to an optional
315
+ // peer, which the snapshot is linked to only as each project that reaches it
316
+ // lists the peer itself, or as the peer is among the root's devDependencies
317
+ // and resolvePeersFromWorkspaceRoot is set, is not walked, and is linked
318
+ // only where the rest reach the peer: a devDependency only there to satisfy
319
+ // an optional peer of a production dependency is left out. From 11.28.7 and
320
+ // 12.15.0, such an edge is one to a peer the snapshot's key binds, or to any
321
+ // of a key with a hash in place of its peers; before, any dependency by the
322
+ // name of one of the snapshot's optional peers, though the snapshot
323
+ // resolved it as its own and its package.json asks for it, as the lockfile
324
+ // pnpm 11.28.7 and 12.15.0 on write records.
325
+ //
305
326
  // The two ways the files come, one or the other: given, with `lockfile`
306
327
  // and `manifests`, `project` read only for directories; or read, with
307
328
  // `project` and none of them.
@@ -324,6 +345,7 @@ export interface PnpmTreeGiven {
324
345
  cache?: CacheOptions['cache']
325
346
  sizeEstimateOnly?: boolean
326
347
  lazy?: boolean
348
+ production?: boolean
327
349
  }
328
350
 
329
351
  export interface PnpmTreeRead {
@@ -339,6 +361,7 @@ export interface PnpmTreeRead {
339
361
  cache?: CacheOptions['cache']
340
362
  sizeEstimateOnly?: boolean
341
363
  lazy?: boolean
364
+ production?: boolean
342
365
  }
343
366
 
344
367
  // What buildPnpmTree counts, all of it plain numbers: `projects` the
@@ -382,7 +405,8 @@ export interface PnpmTreeStats {
382
405
  // to no repository.
383
406
  // `dev` is whether devDependencies alone reach it: no project's
384
407
  // dependencies or optionalDependencies do, through what is installed, so
385
- // `pnpm install --prod` would leave it out. `optional` is whether optional
408
+ // `pnpm install --prod` would leave it out, and so none is with
409
+ // `production`. `optional` is whether optional
386
410
  // dependencies alone reach it, as the lockfile records it. `patch` is the
387
411
  // patch applied to it, by pnpm's hash of it and the path the settings name
388
412
  // it by: of two patches of one text, the first they name.
@@ -442,12 +466,12 @@ export interface PnpmLazyTree extends PnpmTree {
442
466
  unpack(paths: Iterable<string>): Promise<PnpmInstalled[]>
443
467
  }
444
468
 
445
- // The node_modules tree `pnpm install --frozen-lockfile --ignore-scripts`
446
- // makes with the isolated linker of host.pnpm, 9, 10, 11 or 12, or the
447
- // hoisted one of pnpm 10 or 11, and no other install: whatever the
448
- // settings say of frozen lockfiles, the install is frozen, which is also
449
- // the only one that hoists by the lockfile's graph alone. It is rooted at
450
- // the lockfile's directory: each package's
469
+ // The node_modules tree `pnpm install --frozen-lockfile --ignore-scripts`,
470
+ // with `production` --prod too, makes with the isolated linker of
471
+ // host.pnpm, 9, 10, 11 or 12, or the hoisted one of pnpm 10 or 11, and no
472
+ // other install: whatever the settings say of frozen lockfiles, the install
473
+ // is frozen, which is also the only one that hoists by the lockfile's graph
474
+ // alone. It is rooted at the lockfile's directory: each package's
451
475
  // files at node_modules/.pnpm/<dir>/node_modules/<name>, its dependencies
452
476
  // linked beside it, the hoisted aliases, and each project's own
453
477
  // node_modules of links. Links are relative; a `link:` dependency leads
package/src/npm/compat.js CHANGED
@@ -75,16 +75,19 @@ const whereOf = (node) => `packages[${quote(node.location)}]`
75
75
 
76
76
  // npm 11 checks optional packages in inventory order, passing over one an
77
77
  // earlier set took; npm 10 checks them all as it extracts. What is in the
78
- // node_modules of a node left out goes with it.
79
- export function skippedOf(nodes, host, settings) {
78
+ // node_modules of a node left out goes with it. Of those `omitted` leaves
79
+ // out, npm 10 checks only those that are not optional, before it extracts,
80
+ // and npm 11 only those that are.
81
+ export function skippedOf(nodes, host, settings, omitted = new Set()) {
80
82
  const skipped = new Set()
81
83
  for (const node of nodes.values()) {
82
84
  if (node.kind !== 'package') continue
83
85
  const where = whereOf(node)
84
86
  if (!node.pkg.optional) {
85
- checkRuns(node.manifest, host, where, settings.engineStrict, ', and it is not optional')
87
+ if (host.reuse || !omitted.has(node)) checkRuns(node.manifest, host, where, settings.engineStrict, ', and it is not optional')
86
88
  continue
87
89
  }
90
+ if (host.reuse && omitted.has(node)) continue
88
91
  if (!host.reuse && skipped.has(node)) continue
89
92
  if (checkEngine(node.manifest, host) === undefined && checkPlatform(node.manifest, host, where) === undefined) continue
90
93
  for (const member of optionalSet(node, host, skipped)) skipped.add(member)
@@ -92,6 +95,16 @@ export function skippedOf(nodes, host, settings) {
92
95
  for (const node of skipped) {
93
96
  if (node.kind !== 'package') throw new DeptreeError('left out with an optional package the host cannot run, which is not supported', node.kind === 'link' ? whereOf(node) : `importers[${quote(node.location)}]`)
94
97
  }
95
- const under = (node) => node.parent !== undefined && (skipped.has(nodes.get(node.parent)) || under(nodes.get(node.parent)))
96
- return new Set([...nodes.values()].filter((node) => skipped.has(node) || under(node)))
98
+ return withBeneath(nodes, skipped)
97
99
  }
100
+
101
+ // `set`, and what is in the node_modules of each of its nodes.
102
+ function withBeneath(nodes, set) {
103
+ const under = (node) => node.parent !== undefined && (set.has(nodes.get(node.parent)) || under(nodes.get(node.parent)))
104
+ return new Set([...nodes.values()].filter((node) => set.has(node) || under(node)))
105
+ }
106
+
107
+ // What --omit=dev leaves out: each package the lockfile's flags say only dev
108
+ // dependencies reach, and so what is beneath it, as the lockfile reader holds
109
+ // the flags to what depends on each.
110
+ export const omittedOf = (nodes) => new Set([...nodes.values()].filter((node) => node.kind === 'package' && node.pkg.dev))
package/src/npm/tree.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // and links alone, each package's sized by its version document, of which
4
4
  // nothing is fetched but those documents. With `lazy`, its directories and
5
5
  // links alone too, fetching nothing, and each package unpacked into it as
6
- // it is asked for (lazyUnpacker).
6
+ // it is asked for (lazyUnpacker). With `production`, as --omit=dev leaves it.
7
7
 
8
8
  import { parseNpmLockfile } from '@preventive/lockfile/npm.js'
9
9
  import { Vfs } from '@preventive/vfs'
@@ -13,9 +13,10 @@ import { eachConcurrently, limited } from '../concurrent.js'
13
13
  import { DeptreeError, quote, refusalOf } from '../error.js'
14
14
  import { unpacker, writeInto } from '../lazy.js'
15
15
  import { checkNoModules, isInside, makeDirs, mount, writeFiles, writeLink } from '../mount.js'
16
+ import { productionOf } from '../project.js'
16
17
  import { NO_ABOUT, fetchSize, fetchingOf } from '../tarball.js'
17
18
  import { claimedBins, fixBins, fixClaimed } from './bins.js'
18
- import { skippedOf } from './compat.js'
19
+ import { omittedOf, skippedOf } from './compat.js'
19
20
  import { graphOf } from './graph.js'
20
21
  import { checkHost, inputsOf } from './inputs.js'
21
22
  import { checkManifests, recalculates, rootEdgesOf } from './manifests.js'
@@ -74,14 +75,17 @@ async function fetchAll(tarballs, host, fetching) {
74
75
  const pkg = { ...await fetch(tarball, where), integrity: tarball.integrity }
75
76
  for (const node of copies) fetched.set(node, pkg)
76
77
  }, ({ where }) => where)
77
- return { fetched, tarballs: tarballs.size }
78
+ return fetched
78
79
  }
79
80
 
80
81
  // npm 10 makes every package's directory before leaving out those the host
81
- // cannot run, and leaves the directories they were in.
82
- function residueOf(nodes, skipped) {
83
- const removed = [...skipped].map((node) => node.location)
84
- const inRemoved = (dir) => removed.some((location) => dir === location || dir.startsWith(`${location}/`))
82
+ // cannot run, or --omit=dev omits, and leaves the directories they were in.
83
+ function residueOf(nodes, left) {
84
+ const removed = new Set([...left].map((node) => node.location))
85
+ const inRemoved = (dir) => {
86
+ for (let at = dir; at !== '.'; at = dirname(at)) if (removed.has(at)) return true
87
+ return false
88
+ }
85
89
  const dirs = new Set()
86
90
  for (const location of removed) {
87
91
  for (let dir = dirname(location); dir !== '.' && !nodes.has(dir) && !inRemoved(dir); dir = dirname(dir)) dirs.add(dir)
@@ -89,6 +93,9 @@ function residueOf(nodes, skipped) {
89
93
  return dirs
90
94
  }
91
95
 
96
+ // A package's files with those `fixed` by linking its bins in their place.
97
+ const withFixed = (files, fixed) => (fixed === undefined || fixed.size === 0 ? files : new Map([...files].map(([path, file]) => [path, fixed.get(path) ?? file])))
98
+
92
99
  // With `sizeEstimateOnly`, each package's directory alone is made, and its
93
100
  // size counted; with `lazy`, its directory alone.
94
101
  function writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly, lazy }) {
@@ -101,8 +108,7 @@ function writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly
101
108
  continue
102
109
  }
103
110
  const { files, dirs } = fetched.get(node)
104
- const fixed = changed.get(node.location)
105
- writeFiles(vfs, node.location, { dirs, files: fixed === undefined ? files : new Map([...files].map(([path, file]) => [path, fixed.get(path) ?? file])) }, stats)
111
+ writeFiles(vfs, node.location, { dirs, files: withFixed(files, changed.get(node.location)) }, stats)
106
112
  }
107
113
  // checkLinks has each a workspace's, in the project.
108
114
  for (const [location, target] of Object.entries(lockfile.links)) {
@@ -144,7 +150,7 @@ function lazyUnpacker({ vfs, kept, tarballOf, settings, host, fetching, stats, f
144
150
  const written = { files: 0, bytes: 0, links: 0 }
145
151
  try {
146
152
  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)
153
+ writeFiles(tree, node.location, { dirs: got.dirs, files: withFixed(got.files, fixed) }, written)
148
154
  writeInto(vfs, tree, folded)
149
155
  } catch (error) {
150
156
  throw refusalOf(error, whereOf(node))
@@ -169,9 +175,8 @@ function rootListsOf(text) {
169
175
  export async function buildNpmTree(options) {
170
176
  const { host: given, vfs: into } = options ?? {}
171
177
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
172
- const fetching = fetchingOf(options ?? {})
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')
178
+ const fetching = fetchingOf(options ?? {}, into)
179
+ const production = productionOf(options ?? {})
175
180
  const host = checkHost(given)
176
181
  const folded = host.os === 'darwin'
177
182
  const inputs = inputsOf(options ?? {}, folded)
@@ -186,15 +191,16 @@ export async function buildNpmTree(options) {
186
191
  checkLinks(lockfile)
187
192
  checkSpecs(lockfile, host)
188
193
  const nodes = graphOf(lockfile, manifests)
189
- const skipped = skippedOf(nodes, host, settings)
190
- const kept = [...nodes.values()].filter((node) => node.kind === 'package' && !skipped.has(node))
194
+ const omitted = production ? omittedOf(nodes) : new Set()
195
+ const skipped = skippedOf(nodes, host, settings, omitted)
196
+ const kept = [...nodes.values()].filter((node) => node.kind === 'package' && !skipped.has(node) && !omitted.has(node))
191
197
  const tarballs = tarballsOf(kept)
192
- const { fetched, tarballs: count } = fetching.lazy ? { fetched: new Map(), tarballs: 0 } : await fetchAll(tarballs, host, fetching)
198
+ const fetched = fetching.lazy ? new Map() : await fetchAll(tarballs, host, fetching)
193
199
  const changed = settings.binLinks && !fetching.sizeEstimateOnly && !fetching.lazy ? fixBins(kept, fetched) : new Map()
194
- const residue = host.reuse ? residueOf(nodes, skipped) : new Set()
200
+ const residue = host.reuse ? residueOf(nodes, new Set([...skipped, ...omitted])) : new Set()
195
201
  const { vfs, stats: written } = writeTree({ lockfile, kept, fetched, changed, residue, sizeEstimateOnly: fetching.sizeEstimateOnly, lazy: fetching.lazy })
196
202
  const packages = Object.keys(lockfile.packages).length
197
- const stats = { packages, installed: kept.length, skipped: packages - kept.length, tarballs: count, ...written }
203
+ const stats = { packages, installed: kept.length, skipped: packages - kept.length - omitted.size, tarballs: fetching.lazy ? 0 : tarballs.size, ...written }
198
204
  const entryOf = (node, { integrity, about, size }) => {
199
205
  const { name, version, dev, optional, devOptional, peer } = node.pkg
200
206
  return { path: node.location, name, version, integrity, ...about, dev, optional, devOptional, peer, ...fetching.sizeEstimateOnly ? { size } : {} }
package/src/pnpm/bins.js CHANGED
@@ -84,11 +84,20 @@ function commandReader(nodes, projects, major) {
84
84
  }
85
85
  }
86
86
 
87
+ // The lockfile has no hasBin for a directory, whose bins pnpm 12 reads.
88
+ const mayHaveBinIn = (nodes) => (dir) => nodes.get(dir)?.pkg.hasBin === true || nodes.get(dir)?.pkg.resolution.type === 'directory'
89
+
90
+ // The names a project of `manifest` depends on itself.
91
+ const ownNames = (manifest) => new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
92
+
93
+ // A package's link in the root's node_modules, where pnpm hoists publicly.
94
+ const PUBLIC = /^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u
95
+
87
96
  // pnpm's preferDirectCmds for a project of `manifest`: of the commands of
88
97
  // `entries`, [alias, directory], those of its own dependencies, then of the
89
98
  // others those whose names none of them has.
90
99
  function preferOwn(entries, manifest, commandsOfDir) {
91
- const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
100
+ const own = ownNames(manifest)
92
101
  const commands = entries.flatMap(([alias, dir]) => commandsOfDir(dir).map((command) => ({ ...command, direct: own.has(alias) })))
93
102
  const names = new Set(commands.filter((command) => command.direct).map(({ name }) => name))
94
103
  return [...commands.filter((command) => command.direct), ...commands.filter((command) => !names.has(command.name))]
@@ -98,8 +107,7 @@ function preferOwn(entries, manifest, commandsOfDir) {
98
107
  // `building` is whether any patch is configured, `peers` autoInstallPeers.
99
108
  export function binTargets({ nodes, projects, direct, links, publicHoist, building, peers, major }) {
100
109
  const commandsOfDir = commandReader(nodes, projects, major)
101
- // The lockfile has no hasBin for a directory, whose bins pnpm 12 reads.
102
- const mayHaveBin = (dir) => nodes.get(dir)?.pkg.hasBin === true || nodes.get(dir)?.pkg.resolution.type === 'directory'
110
+ const mayHaveBin = mayHaveBinIn(nodes)
103
111
 
104
112
  const { fixed, contested, link } = linker(major)
105
113
 
@@ -135,11 +143,10 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
135
143
  let linked
136
144
  if (id === '.' && publicHoist) {
137
145
  const manifest = projects.get('.')
138
- const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
146
+ const own = ownNames(manifest)
139
147
  const isOwn = (path) => own.has(path.slice('node_modules/'.length))
140
148
  // pnpm 12 links what it hoists of the projects apart, before.
141
- const entries = [...links].filter(([path, dir]) => /^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u.test(path)
142
- && (major < 12 || isOwn(path) || mayHaveBin(dir)))
149
+ const entries = [...links].filter(([path, dir]) => PUBLIC.test(path) && (major < 12 || isOwn(path) || mayHaveBin(dir)))
143
150
  relink ||= major >= 12 && entries.some(([path, dir]) => !isOwn(path) && mayHaveBin(dir))
144
151
  linked = link(preferOwn(entries.map(([path, dir]) => [path.slice('node_modules/'.length), dir]), manifest, commandsOfDir), { ordered: false, where, fixNode: relink })
145
152
  } else {
@@ -163,7 +170,7 @@ export function binTargets({ nodes, projects, direct, links, publicHoist, buildi
163
170
  // again what their first link did, and fixes nothing of theirs. The others
164
171
  // are read as having no bins (lazy.js).
165
172
  export function binReads({ nodes, projects, direct, links, publicHoist, peers, major }) {
166
- const mayHaveBin = (dir) => nodes.get(dir)?.pkg.hasBin === true || nodes.get(dir)?.pkg.resolution.type === 'directory'
173
+ const mayHaveBin = mayHaveBinIn(nodes)
167
174
  const reads = new Set()
168
175
  for (const node of nodes.values()) {
169
176
  if (mayHaveBin(node.dir) || node.pkg.bundledDependencies !== undefined) reads.add(node.dir)
@@ -173,10 +180,9 @@ export function binReads({ nodes, projects, direct, links, publicHoist, peers, m
173
180
  for (const [id, children] of direct) {
174
181
  if (major >= 11 && peers) for (const dir of peersOf(children, nodes)) reads.add(dir)
175
182
  if (id === '.' && publicHoist) {
176
- const manifest = projects.get('.')
177
- const own = new Set(Object.keys({ ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }))
183
+ const own = ownNames(projects.get('.'))
178
184
  for (const [path, dir] of links) {
179
- if (/^node_modules\/(?:@[^/]+\/)?[^/@.][^/]*$/u.test(path) && (major < 12 || own.has(path.slice('node_modules/'.length)))) reads.add(dir)
185
+ if (PUBLIC.test(path) && (major < 12 || own.has(path.slice('node_modules/'.length)))) reads.add(dir)
180
186
  }
181
187
  } else if (major < 11) {
182
188
  for (const dir of children.values()) reads.add(dir)
@@ -213,8 +219,8 @@ function linkCopies(builds, phases, fixed, contested, { keepsModules, major }) {
213
219
  for (const [target, { owner, why }] of phaseContested) mark(target, owner, before, why)
214
220
  }
215
221
  for (const [build, marks] of groups) {
216
- for (const rel of new Set(marks.map((item) => item.rel))) {
217
- const mine = marks.filter((item) => item.rel === rel && (!item.before || build.candidates.includes(item.owner)))
222
+ for (const [rel, marked] of Map.groupBy(marks, (item) => item.rel)) {
223
+ const mine = marked.filter((item) => !item.before || build.candidates.includes(item.owner))
218
224
  const after = mine.filter((item) => !item.before)
219
225
  const before = mine.filter((item) => item.before)
220
226
  const beforeFixed = new Set(before.filter((item) => item.why === undefined).map(({ owner }) => owner))
@@ -296,14 +302,16 @@ export function hoistedBinTargets({ nodes, projects, modules, builds = [], hardl
296
302
  return fixedFiles(nodes, fixed, contested, major)
297
303
  }
298
304
 
305
+ // pnpm 9 and 12 read each linked file's `#!` line. '' is the package.
306
+ export function failsAsDirectory(node, path, major) {
307
+ if (major >= 10 && major < 12) return false
308
+ const prefix = `${path}/`
309
+ return path === '' || node.files.keys().some((name) => name.startsWith(prefix))
310
+ }
311
+
299
312
  function fixedFiles(nodes, fixed, contested, major) {
300
- // pnpm 9 and 12 read each linked file's `#!` line. '' is the package.
301
313
  const checkDirectory = (node, path) => {
302
- if (major >= 10 && major < 12) return
303
- const prefix = `${path}/`
304
- if (path === '' || node.files.keys().some((name) => name.startsWith(prefix))) {
305
- throw new DeptreeError(`its bin ${quote(path === '' ? '.' : path)} is a directory, which pnpm ${major} fails on`, quote(node.key))
306
- }
314
+ if (failsAsDirectory(node, path, major)) throw new DeptreeError(`its bin ${quote(path === '' ? '.' : path)} is a directory, which pnpm ${major} fails on`, quote(node.key))
307
315
  }
308
316
  for (const [target, { owner, why }] of contested) {
309
317
  const node = nodes.get(owner)
@@ -311,7 +319,7 @@ function fixedFiles(nodes, fixed, contested, major) {
311
319
  checkDirectory(node, path)
312
320
  const file = node.files.get(path)
313
321
  if (fixed.has(target) || file?.data === undefined) continue
314
- if (executableMode(file.mode, major) === file.mode && (major >= 12 || (crlfShebang(file.data) === -1 && node.pkg.patchHash === undefined))) continue
322
+ if (!fixChanges(file, major) && (major >= 12 || node.pkg.patchHash === undefined)) continue
315
323
  throw new DeptreeError(`whether pnpm makes ${quote(path)} executable turns on ${why}`, quote(node.key))
316
324
  }
317
325
  const byNode = new Map()
@@ -327,6 +335,9 @@ function fixedFiles(nodes, fixed, contested, major) {
327
335
 
328
336
  export const executableMode = (mode, major) => (major >= 11 ? mode | 0o111 : 0o755)
329
337
 
338
+ // Whether fixBin changes `file`.
339
+ export const fixChanges = (file, major) => executableMode(file.mode, major) !== file.mode || (major < 12 && crlfShebang(file.data) !== -1)
340
+
330
341
  // pnpm reads and writes the file as UTF-8, which changes one that is not.
331
342
  export function fixBin(file, where, major) {
332
343
  const mode = executableMode(file.mode, major)
@@ -166,11 +166,8 @@ export function workspaceHoists(placed, lockfile, { hoistPattern, publicHoistPat
166
166
  // of a patched one's patch; `pnpm` the version, for what is refused.
167
167
  export function hoistedBuilds(byDir, projects, builds, { hardlinks, keepsModules = false, idOf = (key) => key, changesOf, pnpm = '10' }) {
168
168
  const first = new Map()
169
- const placedIn = new Set()
170
- for (const node of byDir.values()) {
171
- if (!first.has(idOf(node.key))) first.set(idOf(node.key), node.dir)
172
- placedIn.add(node.modules)
173
- }
169
+ for (const node of byDir.values()) if (!first.has(idOf(node.key))) first.set(idOf(node.key), node.dir)
170
+ const dropping = mayDrop(byDir)
174
171
  const childrenOf = (node) => Object.entries({ ...node.pkg.dependencies, ...node.pkg.optionalDependencies }).map(([alias, key]) => [alias, first.get(idOf(key))]).filter(([, dir]) => dir !== undefined)
175
172
  const tops = [...byDir.values()].filter((node) => projects.has(node.modules)).map((node) => node.dir)
176
173
  const reached = reachable(tops, (dir) => childrenOf(byDir.get(dir)).map(([, child]) => child))
@@ -194,7 +191,7 @@ export function hoistedBuilds(byDir, projects, builds, { hardlinks, keepsModules
194
191
  } else if (copies.length > 1) {
195
192
  const own = node.files.keys().find((path) => path.split('/').includes('node_modules'))
196
193
  if (own !== undefined) throw new DeptreeError(`pnpm ${pnpm} builds one of its copies where any patch is configured, and makes the others hardlinks of it, with no ${quote(own)}, which is not supported`, quote(key))
197
- const nested = copies.find((copy) => placedIn.has(`${copy.dir}/node_modules`))
194
+ const nested = dropping.get(key)
198
195
  if (nested !== undefined) throw new DeptreeError(`pnpm ${pnpm} builds one of its copies where any patch is configured, and makes the others hardlinks of it, dropping their node_modules: ${quote(`${nested.dir}/node_modules`)} may be dropped, which is not supported`, quote(key))
199
196
  }
200
197
  built.push({ key, copies: copies.map((copy) => copy.dir), candidates, children: childrenOf(node) })
package/src/pnpm/lazy.js CHANGED
@@ -6,8 +6,8 @@ import { Vfs } from '@preventive/vfs'
6
6
  import { eachConcurrently, limited } from '../concurrent.js'
7
7
  import { quote, refusalOf } from '../error.js'
8
8
  import { unpacker, writeInto } from '../lazy.js'
9
- import { NO_ABOUT, crlfShebang } from '../tarball.js'
10
- import { executableMode } from './bins.js'
9
+ import { NO_ABOUT } from '../tarball.js'
10
+ import { failsAsDirectory, fixChanges } from './bins.js'
11
11
  import { binsOf } from './commands.js'
12
12
  import { checkFetched, fetchPackage } from './package.js'
13
13
  import { compose, writeNode } from './write.js'
@@ -21,7 +21,7 @@ import { compose, writeNode } from './write.js'
21
21
  // is a directory; or the package is patched, which is held to its bins as
22
22
  // linked; or its commands cannot be read alone. Else its files are as fetched
23
23
  // and patched, whatever pnpm links of its bins, and of anything else's.
24
- export function bound(node, major, builds) {
24
+ function bound(node, major, builds) {
25
25
  if (builds?.(node)) return true
26
26
  let bins
27
27
  try {
@@ -32,10 +32,10 @@ export function bound(node, major, builds) {
32
32
  if (bins.size === 0) return false
33
33
  if (node.pkg.patchHash !== undefined) return true
34
34
  for (const path of bins.keys()) {
35
- if ((major < 10 || major >= 12) && (path === '' || node.files.keys().some((name) => name.startsWith(`${path}/`)))) return true
35
+ if (failsAsDirectory(node, path, major)) return true
36
36
  const file = node.files.get(path)
37
37
  if (file?.data === undefined) continue
38
- if (executableMode(file.mode, major) !== file.mode || (major < 12 && crlfShebang(file.data) !== -1)) return true
38
+ if (fixChanges(file, major)) return true
39
39
  }
40
40
  return false
41
41
  }
@@ -134,7 +134,7 @@ export async function lazyUnpacker({ vfs, byDir, stats, fixes, reads, builds, ea
134
134
  await eachConcurrently(early.nodes, prepare, (node) => quote(node.key))
135
135
  early.check()
136
136
  }
137
- return unpacker(new Map([...byDir.values()].map((node) => [node.dir, node])), async (node) => {
137
+ return unpacker(byDir, async (node) => {
138
138
  await prepare(node)
139
139
  const { targets, executable } = bound(node, major, builds) ? await fixesFor(node) : { targets: new Map(), executable: new Map() }
140
140
  const tree = new Vfs()
package/src/pnpm/local.js CHANGED
@@ -115,6 +115,6 @@ export function createFreshnessCheck(lockfile, major) {
115
115
  }
116
116
  }
117
117
  return (node, read) => {
118
- if (direct.has(node.key)) checkFresh(read, node.pkg, lockfile.packages, quote(node.key))
118
+ if (direct.has(node.key)) checkFresh(read, lockfile.packages[node.key], lockfile.packages, quote(node.key))
119
119
  }
120
120
  }
@@ -6,6 +6,7 @@
6
6
  import { valid } from '@preventive/upstream/semver.js'
7
7
  import { join } from '@preventive/vfs/path.js'
8
8
  import { DeptreeError, quote } from '../error.js'
9
+ import { own } from '../manifest.js'
9
10
 
10
11
  // From validate-npm-package-name 5, by which pnpm reads a selector's name.
11
12
  const SCOPED = /^(?:@([^/]+?)\/)?([^/]+?)$/u
@@ -37,12 +38,12 @@ export function parseSelector(selector, where) {
37
38
 
38
39
  // A layer's overrides with each `$name` replaced from the root package.json.
39
40
  export function replaceReferences(overrides, manifest, where) {
40
- const own = { ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }
41
+ const deps = { ...manifest.devDependencies, ...manifest.dependencies, ...manifest.optionalDependencies }
41
42
  const replaced = Object.create(null)
42
43
  for (const [selector, spec] of Object.entries(overrides)) {
43
44
  if (typeof spec !== 'string') throw new DeptreeError(`expected a string for ${quote(selector)}`, where)
44
45
  if (!spec.startsWith('$')) { replaced[selector] = spec; continue }
45
- const found = Object.hasOwn(own, spec.slice(1)) ? own[spec.slice(1)] : undefined
46
+ const found = own(deps, spec.slice(1))
46
47
  if (typeof found !== 'string' || found === '') throw new DeptreeError(`${quote(spec)} names no dependency of the root package.json`, where)
47
48
  replaced[selector] = found
48
49
  }
@@ -53,7 +54,7 @@ const CATALOG = 'catalog:'
53
54
 
54
55
  export const catalogOf = (spec) => (spec.startsWith(CATALOG) ? spec.slice(CATALOG.length).trim() || 'default' : undefined)
55
56
 
56
- export const catalogEntry = (catalogs, catalog, name) => (Object.hasOwn(catalogs, catalog) && Object.hasOwn(catalogs[catalog], name) ? catalogs[catalog][name] : undefined)
57
+ export const catalogEntry = (catalogs, catalog, name) => own(own(catalogs, catalog), name)
57
58
 
58
59
  // @pnpm/catalogs.resolver's resolveFromCatalog.
59
60
  function fromCatalog(catalogs, spec, name, where, major) {
@@ -99,7 +99,7 @@ const listed = (bundled) => (bundled === false || (Array.isArray(bundled) && bun
99
99
 
100
100
  // `read` is the package.json as hook.js's hook has it, and `packages` the
101
101
  // lockfile's, by which a `file:` target is the directory it resolves to.
102
- export function checkDependencies(manifest, read, pkg, packages, where) {
102
+ function checkDependencies(manifest, read, pkg, packages, where) {
103
103
  const bundled = bundledOf(manifest)
104
104
  const given = new Set([...names(pkg.dependencies), ...names(pkg.optionalDependencies)])
105
105
  for (const name of [...names(read.dependencies), ...names(read.optionalDependencies)]) {
@@ -122,11 +122,12 @@ export function checkDependencies(manifest, read, pkg, packages, where) {
122
122
  }
123
123
 
124
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.
125
+ // its package.json, as the hook has it, asks for what the snapshot gives it,
126
+ // as `lockfile` has it, though the tree has fewer of its edges.
126
127
  export function checkFetched(node, got, { lockfile, hook, fresh }) {
127
128
  if (got.manifest === undefined) return
128
129
  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
+ checkDependencies(got.manifest, got.read, lockfile.packages[node.key], lockfile.packages, quote(node.key))
130
131
  fresh?.(node, got.read)
131
132
  }
132
133
 
@@ -89,13 +89,13 @@ const checkGlobs12 = (lines, what, where) => {
89
89
  // pnpm 12's `files` allowlist: its matcher, or undefined where no entry is
90
90
  // one, and the files it names outright.
91
91
  function filesOf12(view, files, where) {
92
- checkGlobs12(files ?? [], 'its package.json has `files`', where)
92
+ checkGlobs12(files, 'its package.json has `files`', where)
93
93
  const globs = []
94
- for (const entry of files ?? []) {
94
+ for (const entry of files) {
95
95
  const path = fieldPath(entry)
96
96
  if (path !== '') globs.push(gitignoreGlob(path.startsWith('!') ? path : `/${path}`, `${where}: files[${quote(entry)}]`))
97
97
  }
98
- const named = new Set((files ?? []).filter((entry) => !entry.startsWith('!') && !entry.endsWith('/') && !/[*?[\]{}]/u.test(entry)).map(fieldPath).filter((path) => path !== '' && !path.split('/').includes('..') && view.type(path) === 'file'))
98
+ const named = new Set(files.filter((entry) => !entry.startsWith('!') && !entry.endsWith('/') && !/[*?[\]{}]/u.test(entry)).map(fieldPath).filter((path) => path !== '' && !path.split('/').includes('..') && view.type(path) === 'file'))
99
99
  return { globs: globs.length > 0 ? globs : undefined, named }
100
100
  }
101
101
 
@@ -141,7 +141,7 @@ function walk12(view, { globs }, where) {
141
141
  }
142
142
 
143
143
  function pack12(view, manifest, where) {
144
- const files = Array.isArray(manifest.files) ? filesOf12(view, manifest.files, where) : { named: new Set() }
144
+ const files = Array.isArray(manifest.files) ? filesOf12(view, manifest.files, where) : {}
145
145
  const main = typeof manifest.main === 'string' ? [manifest.main] : []
146
146
  const bins = typeof manifest.bin === 'string' ? [manifest.bin] : manifest.bin !== null && typeof manifest.bin === 'object' && !Array.isArray(manifest.bin) ? Object.values(manifest.bin).filter((bin) => typeof bin === 'string') : []
147
147
  const fields = [...main, ...bins].map(fieldPath)
@@ -0,0 +1,132 @@
1
+ // What `pnpm install --prod` installs of a lockfile, as
2
+ // @pnpm/lockfile.filtering's filterLockfileByImportersAndEngine filters it
3
+ // with devDependencies left out: every project's devDependencies dropped, and
4
+ // of the snapshots those the rest reach, through dependencies,
5
+ // optionalDependencies and `link:`s, which lead only to projects, all of them
6
+ // installed anyway. The root's specifiers stay, which pnpm 9 hoists by.
7
+ //
8
+ // From pnpm 11.28 and 12.8.1 on (@pnpm/lockfile.peer-edges), an edge to an
9
+ // optional peer that a snapshot has only as the projects that reach it list
10
+ // the peer themselves is not walked, and is dropped from the snapshot where
11
+ // nothing else reaches the peer: a devDependency only there to satisfy an
12
+ // optional peer of a production one is left out. From 11.28.7 and 12.15.0,
13
+ // only an edge to a peer the snapshot's key binds is such an edge, or any of
14
+ // one whose key ends in a hash of its peers; before, any edge by the name of
15
+ // an optional peer was, though the snapshot resolved it as its own.
16
+
17
+ import { compareVersions } from '@preventive/upstream/semver.js'
18
+ import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
19
+ import { reachable } from './nm-hoist.js'
20
+
21
+ // undefined where there is no such edge; else whether the key must bind it.
22
+ function ruleOf(pnpm, major) {
23
+ const since = (version) => compareVersions(pnpm, version) >= 0
24
+ if (major < 11 || (major === 11 && !since('11.28.0'))) return undefined
25
+ return { bound: since(major === 11 ? '11.28.7' : '12.15.0') }
26
+ }
27
+
28
+ const edgesOf = (deps) => Object.values(deps).filter((target) => !target.startsWith('link:'))
29
+ const prodEdgesOf = ({ dependencies, optionalDependencies }) => edgesOf({ ...dependencies, ...optionalDependencies })
30
+
31
+ // The groups that end a key, each without its parentheses, the patch hash's
32
+ // first where the key has one; a key the lockfile reader takes has them
33
+ // balanced.
34
+ function groupsOf(key) {
35
+ const groups = []
36
+ let open = 0
37
+ let start = 0
38
+ const suffix = key.slice(packageKeyOf(key).length)
39
+ for (let i = 0; i < suffix.length; i++) {
40
+ if (suffix[i] === '(' && open++ === 0) start = i + 1
41
+ else if (suffix[i] === ')' && --open === 0) groups.push(suffix.slice(start, i))
42
+ }
43
+ return groups
44
+ }
45
+
46
+ const PATCH = 'patch_hash='
47
+
48
+ // pnpm's removePeersSuffix: a key with its patch hash and without its peers.
49
+ function withoutPeers(key) {
50
+ const [first] = groupsOf(key)
51
+ return packageKeyOf(key) + (first?.startsWith(PATCH) ? `(${first})` : '')
52
+ }
53
+
54
+ // pnpm's getBoundPeerProviders: null where the key has no peers, undefined
55
+ // where it has a hash in their place, else each peer it binds.
56
+ function boundOf(key) {
57
+ const peers = groupsOf(key).filter((group) => !group.startsWith(PATCH))
58
+ if (peers.length === 0) return null
59
+ if (peers.length === 1 && /^[\da-f]{32}$/u.test(peers[0])) return undefined
60
+ return new Set(peers.filter((peer) => peer.indexOf('@', 1) !== -1).map(withoutPeers))
61
+ }
62
+
63
+ // Each snapshot's edges to its optional peers, `bound` holding them to the
64
+ // peers its key binds.
65
+ function optionalPeerEdges(packages, bound) {
66
+ const entries = []
67
+ for (const [parent, pkg] of Object.entries(packages)) {
68
+ const providers = bound ? boundOf(parent) : undefined
69
+ if (providers === null) continue
70
+ for (const deps of [pkg.dependencies, pkg.optionalDependencies]) {
71
+ for (const [alias, target] of Object.entries(deps)) {
72
+ if (target.startsWith('link:') || !Object.hasOwn(pkg.peerDependencies, alias) || pkg.peerDependenciesMeta[alias]?.optional !== true) continue
73
+ if (providers === undefined || providers.has(withoutPeers(target))) entries.push({ parent, alias, target })
74
+ }
75
+ }
76
+ }
77
+ return entries
78
+ }
79
+
80
+ const directOf = ({ dependencies, devDependencies, optionalDependencies }) => edgesOf({ ...dependencies, ...devDependencies, ...optionalDependencies })
81
+
82
+ // pnpm's collectPeerSatisfactionEdges: by each edge's target, the projects
83
+ // that do not list it among their own (none, where it is the root's
84
+ // devDependency and resolvePeersFromWorkspaceRoot is set); an edge is one to
85
+ // skip where nothing those projects list reaches its snapshot.
86
+ function satisfactionEdges(lockfile, rule, fromRoot) {
87
+ const entries = optionalPeerEdges(lockfile.packages, rule.bound)
88
+ const edges = new Map()
89
+ if (entries.length === 0) return edges
90
+ const importers = Object.values(lockfile.importers)
91
+ const direct = importers.map((importer) => new Set(directOf(importer)))
92
+ const rootDev = fromRoot && lockfile.importers['.'] !== undefined ? new Set(edgesOf(lockfile.importers['.'].devDependencies)) : new Set()
93
+ const next = (key) => (key in lockfile.packages ? prodEdgesOf(lockfile.packages[key]) : [])
94
+ const groups = Map.groupBy(entries, ({ target }) => (rootDev.has(target) ? '' : direct.flatMap((keys, i) => (keys.has(target) ? [] : [i])).join(',')))
95
+ for (const [listing, group] of groups) {
96
+ const seeds = listing === '' ? [] : listing.split(',').flatMap((i) => directOf(importers[Number(i)]))
97
+ const reached = reachable(seeds, next)
98
+ for (const { parent, alias } of group) {
99
+ if (reached.has(parent)) continue
100
+ if (!edges.has(parent)) edges.set(parent, new Set())
101
+ edges.get(parent).add(alias)
102
+ }
103
+ }
104
+ return edges
105
+ }
106
+
107
+ // Each snapshot `edges` names, without those of its edges `drop` takes.
108
+ function without(packages, edges, drop) {
109
+ const kept = { ...packages }
110
+ for (const [parent, aliases] of edges) {
111
+ const pkg = packages[parent]
112
+ if (pkg === undefined) continue
113
+ const keep = (deps) => Object.fromEntries(Object.entries(deps).filter(([alias, target]) => !aliases.has(alias) || !drop(target)))
114
+ kept[parent] = { ...pkg, dependencies: keep(pkg.dependencies), optionalDependencies: keep(pkg.optionalDependencies) }
115
+ }
116
+ return kept
117
+ }
118
+
119
+ // `walked`, what pnpm walks to leave out what the host cannot run: every
120
+ // snapshot, but for the edges it does not walk; `installing`, the lockfile
121
+ // the tree is laid out from: the snapshots reached, each but for those edges
122
+ // to a snapshot not reached. Each importer's devDependencies are empty.
123
+ export function productionLockfile(lockfile, { pnpm, major, resolvePeersFromWorkspaceRoot }) {
124
+ const importers = Object.fromEntries(Object.entries(lockfile.importers).map(([id, importer]) => [id, { ...importer, devDependencies: {} }]))
125
+ const rule = ruleOf(pnpm, major)
126
+ const edges = rule === undefined ? new Map() : satisfactionEdges(lockfile, rule, resolvePeersFromWorkspaceRoot)
127
+ const walked = { ...lockfile, importers, packages: without(lockfile.packages, edges, () => true) }
128
+ const starts = Object.values(importers).flatMap(prodEdgesOf)
129
+ const picked = reachable(starts, (key) => prodEdgesOf(walked.packages[key]))
130
+ const packages = Object.fromEntries(Object.entries(lockfile.packages).filter(([key]) => picked.has(key)))
131
+ return { walked, installing: { ...lockfile, importers, packages: without(packages, edges, (target) => !picked.has(target)) } }
132
+ }
@@ -87,7 +87,7 @@ export const READ = {
87
87
  lockfile: only('boolean', true, 'the tree is the lockfile\'s'),
88
88
  packageLock: only('boolean', true, 'the tree is the lockfile\'s'),
89
89
  optional: only('boolean', true, 'optional dependencies are installed'),
90
- production: only('boolean', false, 'devDependencies are installed'),
90
+ production: only('boolean', false, 'whether devDependencies are installed is for the production option to say'),
91
91
  dev: only('boolean', false, 'dependencies are installed'),
92
92
  ignorePatchFailures: { ...only('boolean', false, 'a patch that does not apply is an error'), rc: false },
93
93
  force: only('boolean', false, 'optional packages the host cannot run are left out'),
@@ -99,7 +99,7 @@ export const READ = {
99
99
  mergeGitBranchLockfilesBranchPattern: { kind: 'texts', check: never('the lockfile is the one given') },
100
100
  lockfileDir: { kind: 'text', check: never('the lockfile is the one given, at the root of the tree') },
101
101
  lockfileDirectory: { kind: 'text', check: never('the lockfile is the one given, at the root of the tree') },
102
- only: { kind: 'text', check: never('dependencies and devDependencies are both installed') },
102
+ only: { kind: 'text', check: never('which of dependencies and devDependencies are installed is for the production option to say') },
103
103
  filter: { kind: 'texts', check: never('every project is installed') },
104
104
  filterProd: { kind: 'texts', check: never('every project is installed') },
105
105
  useNodeVersion: { kind: 'text', check: never('the Node a tree is built for is the host\'s, or nodeVersion') },
@@ -119,6 +119,8 @@ export const READ = {
119
119
  nodeVersion: { kind: 'text', check: checkNodeVersion },
120
120
  autoInstallPeers: { kind: 'boolean' },
121
121
  dedupePeers: { kind: 'boolean' },
122
+ // Which edges to optional peers pnpm 11 and 12 leave out with --prod (production.js).
123
+ resolvePeersFromWorkspaceRoot: { kind: 'boolean' },
122
124
  peersSuffixMaxLength: { kind: 'count' },
123
125
  // Whether a directory package's snapshots share hardlinked files (tree.js).
124
126
  packageImportMethod: { kind: 'importMethod' },
@@ -225,7 +227,7 @@ const IGNORED = new Set([
225
227
  'allowNonAppliedPatches', 'allowUnusedPatches', 'allowedDeprecatedVersions', 'blockExoticSubdeps', 'catalogMode',
226
228
  'dedupeInjectedDeps', 'dedupePeerDependents', 'ignoreCompatibilityDb', 'linkWorkspacePackages', 'lockfileIncludeTarballUrl',
227
229
  'minimumReleaseAge', 'minimumReleaseAgeExclude', 'peerDependencyRules', 'preferWorkspacePackages',
228
- 'registrySupportsTimeField', 'resolutionMode', 'resolvePeersFromWorkspaceRoot', 'saveExact', 'savePrefix',
230
+ 'registrySupportsTimeField', 'resolutionMode', 'saveExact', 'savePrefix',
229
231
  'saveWorkspaceProtocol', 'strictPeerDependencies',
230
232
  // the network and its credentials, which @preventive/upstream handles
231
233
  'alwaysAuth', 'ca', 'cafile', 'cert', 'email', 'fetchRetries', 'fetchRetryFactor', 'fetchRetryMaxtimeout',
@@ -139,6 +139,7 @@ function derive(get, major) {
139
139
  packageExtensions: get('packageExtensions'),
140
140
  ignoredOptionalDependencies: get('ignoredOptionalDependencies') ?? [],
141
141
  autoInstallPeers: get('autoInstallPeers') ?? true,
142
+ resolvePeersFromWorkspaceRoot: get('resolvePeersFromWorkspaceRoot') ?? true,
142
143
  dedupePeers: get('dedupePeers') ?? false,
143
144
  peersSuffixMaxLength: get('peersSuffixMaxLength') ?? 1000,
144
145
  packages: get('packages'),
package/src/pnpm/tree.js CHANGED
@@ -5,7 +5,9 @@
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
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).
8
+ // each package unpacked into it as it is asked for (lazy.js). With
9
+ // `production`, as --prod installs it (production.js): laid out from the
10
+ // lockfile it leaves, and held to the whole one.
9
11
 
10
12
  import { packageKeyOf } from '@preventive/lockfile/pnpm.js'
11
13
  import { compareVersions } from '@preventive/upstream/semver.js'
@@ -14,7 +16,7 @@ import { dirname, relative } from '@preventive/vfs/path.js'
14
16
  import { eachConcurrently } from '../concurrent.js'
15
17
  import { DeptreeError, quote, refusalOf } from '../error.js'
16
18
  import { checkNoModules, fold, makeDirs, mount, writeLink } from '../mount.js'
17
- import { checkProject } from '../project.js'
19
+ import { checkProject, productionOf } from '../project.js'
18
20
  import { NO_ABOUT, REGISTRY, fetchSize, fetchingOf, tarballUrl } from '../tarball.js'
19
21
  import { binReads, binTargets, hoistedBinReads, hoistedBinTargets, requiresBuild } from './bins.js'
20
22
  import { buildGraph } from './graph.js'
@@ -26,6 +28,7 @@ import { lazyUnpacker } from './lazy.js'
26
28
  import { checkFetched, fetchPackage } from './package.js'
27
29
  import { checkLinks, checkOptional } from './checks.js'
28
30
  import { createHook } from './hook.js'
31
+ import { productionLockfile } from './production.js'
29
32
  import { listOverrides } from './overrides.js'
30
33
  import { checkHost, inputsOf, manifestsOf, patchesOf, readLockfile } from './inputs.js'
31
34
  import { checkProjects, pinsPnpm, workspaceNames } from './projects.js'
@@ -93,10 +96,11 @@ async function fetchAll(nodes, project, host, fetching) {
93
96
  }
94
97
 
95
98
  // 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.
97
- async function fetchNodes(nodes, lockfile, hook, project, host, fetching) {
99
+ // to them as each is unpacked; `checks` are what that takes, of `checked`, the
100
+ // whole lockfile.
101
+ async function fetchNodes(nodes, checked, hook, project, host, fetching) {
98
102
  const fetched = await fetchAll(nodes, project, host, fetching)
99
- const checks = { lockfile, hook, fresh: createFreshnessCheck(lockfile, host.major) }
103
+ const checks = { lockfile: checked, hook, fresh: createFreshnessCheck(checked, host.major) }
100
104
  const byDir = new Map()
101
105
  for (const node of nodes.values()) {
102
106
  const got = fetched.get(packageKeyOf(node.key))
@@ -183,8 +187,9 @@ const COPYING = new Set(['copy', 'clone', 'clone-or-copy'])
183
187
  // every package's files are at hand; with `sizeEstimateOnly` they are not
184
188
  // followed, nor with `lazy` but where a package unpacked needs them. `builds`
185
189
  // tells, where any patch is configured, what the build pass builds; `reads`
186
- // the packages the fixes read the files of (hoistedBinReads).
187
- async function buildHoisted({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching }) {
190
+ // the packages the fixes read the files of (hoistedBinReads). `lockfile` is
191
+ // the one the tree is laid out from, and `checked` the whole one.
192
+ async function buildHoisted({ lockfile, checked, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching }) {
188
193
  const { major } = host
189
194
  const since = (version) => compareVersions(host.pnpm, version) >= 0
190
195
  if (!COPYING.has(settings.packageImportMethod)) {
@@ -200,7 +205,7 @@ async function buildHoisted({ lockfile, settings, host, project, hook, installed
200
205
  const keepsModules = since('11.25.0')
201
206
  const dropping = building && hardlinks && !keepsModules ? mayDrop(placed) : new Map()
202
207
  if (fetching.sizeEstimateOnly) checkNoneDropped(dropping, host.pnpm)
203
- const { byDir, tarballs, checks } = await fetchNodes(placed, lockfile, hook, project, host, fetching)
208
+ const { byDir, tarballs, checks } = await fetchNodes(placed, checked, hook, project, host, fetching)
204
209
  const linked = readLinked(links, byDir, manifests, project)
205
210
  const prod = prodPackages(lockfile, skipped, directories)
206
211
  const dev = (node) => !prod.has(packageIdOf(node.key, node.pkg, directories))
@@ -221,11 +226,11 @@ async function buildHoisted({ lockfile, settings, host, project, hook, installed
221
226
  // The isolated layout: each package in node_modules/.pnpm, linked from what
222
227
  // needs it and where it is hoisted; `fixes` as buildHoisted's, and `reads`
223
228
  // the packages they read the files of (binReads).
224
- async function buildIsolated({ lockfile, settings, host, project, hook, installed, manifests, names, skipped, fetching }) {
229
+ async function buildIsolated({ lockfile, checked, settings, host, project, hook, installed, manifests, names, skipped, fetching }) {
225
230
  const { major } = host
226
231
  const { nodes, direct, hoisting } = await buildGraph(lockfile, skipped, settings.virtualStoreDirMaxLength, major)
227
232
  for (const node of nodes.values()) checkSource(node, installed)
228
- const { byDir, tarballs, checks } = await fetchNodes(nodes, lockfile, hook, project, host, fetching)
233
+ const { byDir, tarballs, checks } = await fetchNodes(nodes, checked, hook, project, host, fetching)
229
234
  const links = linksOf(byDir, direct, settings, names, major, hoisting)
230
235
  const linked = readLinked(links, byDir, manifests, project)
231
236
  const prod = reachedInProd(lockfile.importers, nodes, byDir)
@@ -250,9 +255,8 @@ async function buildIsolated({ lockfile, settings, host, project, hook, installe
250
255
  export async function buildPnpmTree(options) {
251
256
  const { project, host: given, vfs: into } = options ?? {}
252
257
  if (into !== undefined && !(into instanceof Vfs)) throw new TypeError('vfs must be a Vfs, or left out')
253
- const fetching = fetchingOf(options ?? {})
254
- if (fetching.sizeEstimateOnly && into !== undefined) throw new TypeError('vfs is not taken with sizeEstimateOnly, whose tree has no files to mount')
255
- if (fetching.lazy && into !== undefined) throw new TypeError('vfs is not taken with lazy, whose tree is unpacked a package at a time')
258
+ const fetching = fetchingOf(options ?? {}, into)
259
+ const production = productionOf(options ?? {})
256
260
  if (project !== undefined) checkProject(project)
257
261
  const machine = checkHost(given)
258
262
  const folded = machine.os === 'darwin'
@@ -283,9 +287,10 @@ export async function buildPnpmTree(options) {
283
287
  checkProjects(lockfile, manifests, { hook, host, settings, env })
284
288
  checkOptional(lockfile)
285
289
  const names = settings.hoistWorkspacePackages ? workspaceNames(manifests) : new Map()
286
- const { skipped, incompatible } = skippedSnapshots(lockfile, { host, settings })
290
+ const { walked, installing } = production ? productionLockfile(lockfile, { ...host, resolvePeersFromWorkspaceRoot: settings.resolvePeersFromWorkspaceRoot }) : { walked: lockfile, installing: lockfile }
291
+ const { skipped, incompatible } = skippedSnapshots(walked, { host, settings })
287
292
  const hoisted = settings.nodeLinker === 'hoisted'
288
- const { byDir, links, fixes, reads, builds, early, tarballs, dev, checks } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
293
+ const { byDir, links, fixes, reads, builds, early, tarballs, dev, checks } = await (hoisted ? buildHoisted : buildIsolated)({ lockfile: installing, checked: lockfile, settings, host, project, hook, installed, manifests, names, patched, skipped, fetching })
289
294
  const laidOut = fetching.sizeEstimateOnly || fetching.lazy
290
295
  const { targets, executable } = laidOut ? { targets: new Map(), executable: new Map() } : fixes()
291
296
 
package/src/project.js CHANGED
@@ -48,6 +48,11 @@ export function checkHostKeys(host, keys, wanted) {
48
48
  if (host === null || typeof host !== 'object') throw new TypeError(`host must be an object with ${wanted}`)
49
49
  for (const key of keys) if (typeof host[key] !== 'string' || host[key] === '') throw new TypeError(`host.${key} must be a non-empty string`)
50
50
  }
51
+ // `production`, false unless given true, as each manager's builder takes it.
52
+ export function productionOf({ production = false }) {
53
+ if (typeof production !== 'boolean') throw new TypeError('production must be a boolean, or left out')
54
+ return production
55
+ }
51
56
  export function checkLeftOut(values, all = 'both') {
52
57
  for (const [name, value] of Object.entries(values)) if (value !== undefined) throw new TypeError(`${name} must be left out where lockfile is: ${all} are read from project`)
53
58
  }
package/src/tarball.js CHANGED
@@ -94,7 +94,8 @@ export const NO_ABOUT = Object.freeze(aboutOf({}))
94
94
  // alone (fetchSize); and `lazy`, false unless given true, for nothing until a
95
95
  // package is unpacked, and then its tarball, as without it. The two are
96
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 }) {
97
+ // Each is refused with `into`, a Vfs given to mount the tree's files into.
98
+ export function fetchingOf({ metadata = true, cache, sizeEstimateOnly = false, lazy = false }, into) {
98
99
  if (typeof metadata !== 'boolean') throw new TypeError('metadata must be a boolean, or left out')
99
100
  if (cache !== undefined && cache !== false && (typeof cache?.read !== 'function' || typeof cache?.write !== 'function')) {
100
101
  throw new TypeError('cache must be false, or a store with read and write, or left out')
@@ -102,6 +103,8 @@ export function fetchingOf({ metadata = true, cache, sizeEstimateOnly = false, l
102
103
  if (typeof sizeEstimateOnly !== 'boolean') throw new TypeError('sizeEstimateOnly must be a boolean, or left out')
103
104
  if (typeof lazy !== 'boolean') throw new TypeError('lazy must be a boolean, or left out')
104
105
  if (lazy && sizeEstimateOnly) throw new TypeError('lazy is not taken with sizeEstimateOnly, which fetches no tarball to unpack')
106
+ if (sizeEstimateOnly && into !== undefined) throw new TypeError('vfs is not taken with sizeEstimateOnly, whose tree has no files to mount')
107
+ if (lazy && into !== undefined) throw new TypeError('vfs is not taken with lazy, whose tree is unpacked a package at a time')
105
108
  return { metadata, cache, sizeEstimateOnly, lazy }
106
109
  }
107
110
 
@@ -78,7 +78,7 @@ export class Hoister {
78
78
  const ref = this.resolved(pattern)
79
79
  if (parent && !this.tree.get(parent.key)) return null
80
80
  const isIncompatible = ref.incompatible === true
81
- const isRequired = !isIncompatible && (isDirectRequire || parent?.isRequired === true)
81
+ const isRequired = !isIncompatible && ((isDirectRequire && !ref.ignore) || parent?.isRequired === true)
82
82
  const parts = (parent?.parts ?? []).concat(ref.name)
83
83
  const key = implode(parts)
84
84
  const info = { key, parts, ref, isDirectRequire, isRequired, isIncompatible }
@@ -53,7 +53,7 @@ const decoder = new TextDecoder('utf-8', { fatal: true })
53
53
  // 3.10.8, is the first it signed over one it made, and superstatic@6.0.0, at
54
54
  // 2018-08-03T20:22:28.120Z, the last over none. It has since made one for
55
55
  // every version published before too.
56
- export const SHA512_SINCE = '2018-08-05T14:58:16.253Z'
56
+ const SHA512_SINCE = '2018-08-05T14:58:16.253Z'
57
57
 
58
58
  // The hex of an integrity that is a sha1 alone.
59
59
  function sha1Of(integrity) {
@@ -57,11 +57,12 @@ function directoryOf(range, where) {
57
57
  }
58
58
 
59
59
  // What a package asks for, in yarn's order. A lockfile entry's are patterns;
60
- // one the lockfile reader links to a workspace has lost its range.
61
- function asked(info, where) {
60
+ // one the lockfile reader links to a workspace has lost its range. A
61
+ // workspace's devDependencies are asked for, but with --production.
62
+ function asked(info, where, production) {
62
63
  const workspace = info.kind === 'workspace'
63
64
  const lists = workspace ? info.workspace.manifest : info.entry
64
- const kinds = [['dependencies', false, false], ['optionalDependencies', true, false], ...workspace ? [['devDependencies', false, true]] : []]
65
+ const kinds = [['dependencies', false, false], ['optionalDependencies', true, false], ...workspace && !production ? [['devDependencies', false, true]] : []]
65
66
  return kinds.flatMap(([kind, optional, dev]) => Object.entries(lists[kind] ?? {}).map(([name, value]) => {
66
67
  if (!workspace && value.startsWith('link:')) throw new DeptreeError(`its dependency on ${quote(name)} is a workspace, which is not supported`, where)
67
68
  return { pattern: workspace ? `${name}@${value}` : value, optional, dev }
@@ -80,8 +81,8 @@ function locOf({ kind, name, version, entry, dir }) {
80
81
  }
81
82
 
82
83
  class Resolver {
83
- constructor({ lockfile, workspaces, rules, isDirectory }) {
84
- Object.assign(this, { lockfile, workspaces, rules, isDirectory })
84
+ constructor({ lockfile, workspaces, rules, isDirectory, production = false }) {
85
+ Object.assign(this, { lockfile, workspaces, rules, isDirectory, production })
85
86
  this.patterns = new Map()
86
87
  this.byName = new Map()
87
88
  this.delayed = []
@@ -160,7 +161,7 @@ class Resolver {
160
161
  dir: info.dir,
161
162
  patterns: [],
162
163
  requests: [request],
163
- asked: asked(info, quote(request.pattern)),
164
+ asked: asked(info, quote(request.pattern), this.production),
164
165
  optional: request.optional,
165
166
  }
166
167
  this.addPattern(request.pattern, ref)
package/src/yarn1/tree.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // A node_modules tree as `yarn install --frozen-lockfile --ignore-scripts`
2
- // makes it in a directory with no node_modules yet. Not written:
3
- // node_modules/.bin, yarn's .yarn-integrity, and anything a script builds.
2
+ // makes it in a directory with no node_modules yet, and with `production`, as
3
+ // --production does too. Not written: node_modules/.bin, yarn's
4
+ // .yarn-integrity, and anything a script builds.
4
5
 
5
6
  import { parseYarn1Lockfile } from '@preventive/lockfile/yarn1.js'
6
7
  import { Vfs } from '@preventive/vfs'
@@ -9,7 +10,7 @@ import { clean, satisfies, valid, validRange } from '@preventive/upstream/semver
9
10
  import { eachConcurrently } from '../concurrent.js'
10
11
  import { DeptreeError, quote } from '../error.js'
11
12
  import { checkNoModules, isInside, makeDirs, mount, writeFiles, writeLink } from '../mount.js'
12
- import { typeOf } from '../project.js'
13
+ import { productionOf, typeOf } from '../project.js'
13
14
  import { fetchingOf } from '../tarball.js'
14
15
  import { checkBinLinks } from './bins.js'
15
16
  import { incompatibility } from './compat.js'
@@ -37,7 +38,7 @@ async function fetchAll(refs, first, fetching) {
37
38
  const fetched = new Map()
38
39
  const times = new Map()
39
40
  const tarballs = new Map(refs.map((ref) => [ref, registryTarball(ref.entry, fetchedName(ref), whereOf(ref))]))
40
- await eachConcurrently([...first.values()], async (ref) => {
41
+ await eachConcurrently(first.values(), async (ref) => {
41
42
  fetched.set(ref, await fetchYarnPackage(tarballs.get(ref), whereOf(ref), times, fetching))
42
43
  }, whereOf)
43
44
  for (const ref of refs) {
@@ -67,7 +68,11 @@ function locationOf(names, workspaces) {
67
68
  return `node_modules/${names.join('/node_modules/')}`
68
69
  }
69
70
 
70
- function resolveProject(inputs, host) {
71
+ // With --production yarn asks for the root's devDependencies all the same,
72
+ // fetches and checks them, and hoists them, but marks each as ignored
73
+ // (install.js's markIgnored): it is installed only where something else
74
+ // needs it.
75
+ function resolveProject(inputs, host, production) {
71
76
  const lockfile = parseYarn1Lockfile(inputs.lockfile, { manifests: Object.fromEntries(inputs.manifests), semver: { clean, satisfies, valid, validRange } })
72
77
  const manifests = new Map([...inputs.manifests].map(([dir, manifest]) => [dir, fixLists(manifest)]))
73
78
  const root = manifests.get('.')
@@ -79,7 +84,9 @@ function resolveProject(inputs, host) {
79
84
  if (reason !== undefined) throw new DeptreeError(reason, 'manifests["."]')
80
85
  const { project } = inputs
81
86
  const isDirectory = project === undefined ? () => undefined : (tag) => typeOf(project, `/${tag}/package.json`) !== undefined
82
- return { workspaces, asked, resolved: resolve({ lockfile, workspaces, rules, top: requests, isDirectory }) }
87
+ const resolved = resolve({ lockfile, workspaces, rules, top: requests, isDirectory, production })
88
+ if (production) for (const { pattern, dev } of asked) if (dev) resolved.patterns.get(pattern).ignore = true
89
+ return { workspaces, asked, resolved }
83
90
  }
84
91
 
85
92
  // As in yarn, every package is fetched before any is checked, in the order
@@ -198,13 +205,14 @@ export async function buildYarn1Tree(options) {
198
205
  for (const option of ['sizeEstimateOnly', 'lazy']) {
199
206
  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
207
  }
208
+ const production = productionOf(options ?? {})
201
209
  const inputs = inputsOf(options ?? {})
202
210
  const host = checkHost(given, inputs.manifests.get('.'))
203
211
  const folded = host.os === 'darwin'
204
212
  // Refused before anything is fetched; mount checks again.
205
213
  if (into !== undefined) checkNoModules(into, folded)
206
214
  checkRoot(inputs.manifests.get('.'))
207
- const { workspaces, asked, resolved } = resolveProject(inputs, host)
215
+ const { workspaces, asked, resolved } = resolveProject(inputs, host, production)
208
216
  const { packages, fetched, manifestOf } = await fetchChecked(resolved, host, inputs.settings, inputs.project, fetching)
209
217
  const { placed, hoister } = layout({ resolved, manifestOf, asked, workspaces })
210
218
  const { vfs, links, locations, copies, files, bytes } = writeTree(placed, fetched)
package/yarn1.d.ts CHANGED
@@ -149,6 +149,9 @@ export interface Yarn1Project {
149
149
  // and leaves out packages by what their package.json says, which only their
150
150
  // tarballs hold: a TypeError is thrown for either given true.
151
151
  //
152
+ // `production`, false unless given true, builds the tree `yarn install
153
+ // --production` makes, as below.
154
+ //
152
155
  // The two ways the files come, one or the other: given, with `lockfile`
153
156
  // and `manifests`; or read, with `project` and none of them. `project`
154
157
  // given with `lockfile` is read only to tell whether a tag a top-level
@@ -165,6 +168,7 @@ export interface Yarn1TreeGiven {
165
168
  vfs?: Vfs
166
169
  metadata?: boolean
167
170
  cache?: CacheOptions['cache']
171
+ production?: boolean
168
172
  }
169
173
 
170
174
  export interface Yarn1TreeRead {
@@ -177,6 +181,7 @@ export interface Yarn1TreeRead {
177
181
  vfs?: Vfs
178
182
  metadata?: boolean
179
183
  cache?: CacheOptions['cache']
184
+ production?: boolean
180
185
  }
181
186
 
182
187
  // What buildYarn1Tree counts, all of it plain numbers: `packages` the
@@ -213,8 +218,8 @@ export interface Yarn1TreeStats {
213
218
  // each peer yarn finds, looked for from where what asks for it is, as Node
214
219
  // finds it and yarn marks what an install requires, past what the host
215
220
  // cannot run. Two copies of one package may differ: one beneath a
216
- // devDependency that only it needs is dev. `optional` is whether optional
217
- // dependencies alone reach this copy, so.
221
+ // devDependency that only it needs is dev. With `production`, none is.
222
+ // `optional` is whether optional dependencies alone reach this copy, so.
218
223
  export interface Yarn1Installed {
219
224
  path: string
220
225
  name: string
@@ -240,12 +245,13 @@ export interface Yarn1Tree {
240
245
  }
241
246
 
242
247
  // The node_modules tree `yarn install --frozen-lockfile --ignore-scripts`
243
- // makes, with host.yarn's node_modules linker, into a project with no
244
- // node_modules yet: rooted at the lockfile's directory, each package's
245
- // files copied where yarn hoists it, and each workspace linked where yarn
246
- // hoists it, by a relative link to its directory, with what yarn hoists
247
- // beneath it in that directory's own node_modules. The tree holds
248
- // node_modules and nothing else of the projects.
248
+ // makes, with `production` --production too, with host.yarn's node_modules
249
+ // linker, into a project with no node_modules yet: rooted at the lockfile's
250
+ // directory, each package's files copied where yarn hoists it, and each
251
+ // workspace linked where yarn hoists it, by a relative link to its
252
+ // directory, with what yarn hoists beneath it in that directory's own
253
+ // node_modules. The tree holds node_modules and nothing else of the
254
+ // projects.
249
255
  //
250
256
  // The lockfile is resolved as yarn resolves it, in yarn's order, which
251
257
  // decides where a package goes: the resolutions' patterns, then the root's
@@ -259,6 +265,16 @@ export interface Yarn1Tree {
259
265
  // to a semver range, or to the registry's own tarball or a directory of
260
266
  // the project, as below.
261
267
  //
268
+ // With `production`, as --production has yarn install it: no workspace's
269
+ // devDependencies are asked for, nor their entries read; the root's are
270
+ // asked for all the same, resolved, fetched, checked and hoisted as without
271
+ // it, but marked ignored, as yarn marks them, so each copy is installed only
272
+ // where something else needs it, with what it alone needs left out. So a
273
+ // devDependency of the root still takes the place it is hoisted to, which a
274
+ // version another package needs is kept from, as without it; and one the
275
+ // host cannot run fails as it does without it, though the tree leaves it
276
+ // out.
277
+ //
262
278
  // Scripts are always ignored, as `--ignore-scripts` has yarn ignore them,
263
279
  // whatever the settings say. No .bin is written, nor yarn's own
264
280
  // .yarn-integrity; but each bin's target is made executable, chmod 755, in