nx 24.1.0-beta.1 → 24.1.0-beta.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.
Files changed (48) hide show
  1. package/dist/src/command-line/release/utils/repository-git-tags.js +3 -3
  2. package/dist/src/command-line/reset/reset.js +51 -2
  3. package/dist/src/daemon/client/daemon-environment.js +15 -0
  4. package/dist/src/devkit-internals.d.ts +3 -3
  5. package/dist/src/devkit-internals.js +6 -3
  6. package/dist/src/generators/utils/glob.js +3 -3
  7. package/dist/src/hasher/hash-task.d.ts +3 -1
  8. package/dist/src/hasher/hash-task.js +3 -2
  9. package/dist/src/native/index.d.ts +0 -4
  10. package/dist/src/native/index.js +13 -0
  11. package/dist/src/native/nx.wasm32-wasi.debug.wasm +0 -0
  12. package/dist/src/native/nx.wasm32-wasi.wasm +0 -0
  13. package/dist/src/plugins/js/index.js +24 -9
  14. package/dist/src/plugins/js/lock-file/bun-parser.d.ts +74 -2
  15. package/dist/src/plugins/js/lock-file/bun-parser.js +971 -139
  16. package/dist/src/plugins/js/lock-file/lock-file.d.ts +32 -12
  17. package/dist/src/plugins/js/lock-file/lock-file.js +189 -43
  18. package/dist/src/plugins/js/lock-file/npm-parser.d.ts +1 -0
  19. package/dist/src/plugins/js/lock-file/npm-parser.js +66 -2
  20. package/dist/src/plugins/js/lock-file/pnpm-parser.d.ts +5 -1
  21. package/dist/src/plugins/js/lock-file/pnpm-parser.js +107 -54
  22. package/dist/src/plugins/js/lock-file/pruned-output.d.ts +52 -10
  23. package/dist/src/plugins/js/lock-file/pruned-output.js +132 -66
  24. package/dist/src/plugins/js/lock-file/utils/local-path-hashes.d.ts +27 -0
  25. package/dist/src/plugins/js/lock-file/utils/local-path-hashes.js +155 -0
  26. package/dist/src/plugins/js/lock-file/utils/package-json.d.ts +1 -1
  27. package/dist/src/plugins/js/lock-file/utils/package-json.js +2 -1
  28. package/dist/src/plugins/js/package-json/create-package-json.d.ts +1 -0
  29. package/dist/src/plugins/js/package-json/create-package-json.js +197 -8
  30. package/dist/src/plugins/js/project-graph/build-dependencies/build-dependencies.d.ts +1 -1
  31. package/dist/src/plugins/js/project-graph/build-dependencies/build-dependencies.js +2 -2
  32. package/dist/src/plugins/js/project-graph/build-dependencies/explicit-package-json-dependencies.js +16 -9
  33. package/dist/src/plugins/js/project-graph/build-dependencies/explicit-project-dependencies.js +17 -28
  34. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.d.ts +47 -1
  35. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.js +261 -15
  36. package/dist/src/project-graph/error-types.d.ts +2 -2
  37. package/dist/src/project-graph/error-types.js +2 -2
  38. package/dist/src/tasks-runner/init-tasks-runner.js +23 -17
  39. package/dist/src/tasks-runner/task-orchestrator.js +16 -2
  40. package/dist/src/tasks-runner/tasks-schedule.js +1 -1
  41. package/dist/src/tasks-runner/utils.d.ts +2 -1
  42. package/dist/src/tasks-runner/utils.js +2 -1
  43. package/dist/src/utils/find-matching-projects.js +7 -9
  44. package/dist/src/utils/handle-import.js +8 -2
  45. package/dist/src/utils/json.js +5 -0
  46. package/dist/src/utils/package-json.d.ts +7 -0
  47. package/dist/src/utils/package-json.js +9 -0
  48. package/package.json +13 -12
@@ -5,20 +5,33 @@ exports.readBunLockFile = readBunLockFile;
5
5
  exports.getBunTextLockfileDependencies = getBunTextLockfileDependencies;
6
6
  exports.clearCache = clearCache;
7
7
  exports.getBunTextLockfileNodes = getBunTextLockfileNodes;
8
+ exports.getBunLocalPathNodeSources = getBunLocalPathNodeSources;
9
+ exports.getBunInstalledLocalPathNodes = getBunInstalledLocalPathNodes;
10
+ exports.stringifyBunLockfile = stringifyBunLockfile;
11
+ exports.getPrunedBunPatchArtifacts = getPrunedBunPatchArtifacts;
12
+ exports.getPrunedBunLocalPathTargets = getPrunedBunLocalPathTargets;
13
+ exports.validatePrunedBunLocalPathClosure = validatePrunedBunLocalPathClosure;
14
+ exports.getBunPatchFileHashes = getBunPatchFileHashes;
15
+ exports.getBunLockfilePatchKeys = getBunLockfilePatchKeys;
8
16
  const node_child_process_1 = require("node:child_process");
9
17
  const node_fs_1 = require("node:fs");
18
+ const node_path_1 = require("node:path");
10
19
  const semver_1 = require("semver");
11
20
  const project_graph_1 = require("../../../config/project-graph");
12
21
  const file_hasher_1 = require("../../../hasher/file-hasher");
13
22
  const project_graph_builder_1 = require("../../../project-graph/project-graph-builder");
23
+ const catalog_1 = require("../../../utils/catalog");
24
+ const fileutils_1 = require("../../../utils/fileutils");
14
25
  const json_1 = require("../../../utils/json");
26
+ const get_workspace_packages_from_graph_1 = require("../utils/get-workspace-packages-from-graph");
15
27
  const lock_file_names_1 = require("./lock-file-names");
28
+ const pruned_output_1 = require("./pruned-output");
16
29
  // Highest bun.lock version this parser has been verified against:
17
30
  // - 1: workspace packages are no longer listed with their dependencies
18
31
  // - 2: identical content, stricter validation in Bun's own reader
19
32
  // - 3: values in "overrides" may be objects holding rules scoped to a parent
20
33
  // package (`"parent": { "child": "1.0.0" }`) and keys may carry a version
21
- // selector (`"parent@1"`, `"child@<2"`). This parser never reads
34
+ // selector (`"parent@1"`, `"child@<2"`). The graph never reads
22
35
  // "overrides"; the resolved packages are listed in "packages" as before.
23
36
  // Newer versions are parsed on a best-effort basis instead of being rejected
24
37
  // outright.
@@ -126,12 +139,9 @@ function getProtocolFromResolvedSpec(resolvedSpec) {
126
139
  }
127
140
  function parseResolvedSpec(resolvedSpec) {
128
141
  // Handle different resolution formats:
129
- // - "package-name@npm:1.0.0"
130
- // - "@scope/package-name@npm:1.0.0"
131
142
  // - "package-name@github:user/repo#commit"
132
143
  // - "package-name@file:./path"
133
144
  // - "package-name@https://example.com/package.tgz"
134
- // - "alias-name@npm:actual-package@version" (ALIAS FORMAT)
135
145
  // Handle scoped packages properly - they have an extra @ at the beginning
136
146
  // Format: @scope/package@protocol:spec
137
147
  let name;
@@ -156,42 +166,22 @@ function parseResolvedSpec(resolvedSpec) {
156
166
  }
157
167
  // Parse protocol and spec
158
168
  const colonIndex = protocolAndSpec.indexOf(':');
159
- // Handle specs without protocol prefix (e.g., "package@1.0.0" instead of "package@npm:1.0.0")
169
+ // Handle specs without protocol prefix (e.g., "package@1.0.0"), which is how
170
+ // Bun records every registry package, aliases included
160
171
  if (colonIndex === -1) {
161
172
  // No protocol specified, treat as npm package with direct version
162
173
  return { name, version: protocolAndSpec };
163
174
  }
164
175
  const protocol = protocolAndSpec.substring(0, colonIndex);
165
176
  const spec = protocolAndSpec.substring(colonIndex + 1);
166
- if (protocol === 'npm') {
167
- // For npm protocol, spec should always be in format: package@version
168
- // Examples:
169
- // - Regular: "package@npm:package@1.0.0" -> version: "1.0.0"
170
- // - Alias: "alias@npm:real-package@1.0.0" -> version: "npm:real-package@1.0.0"
171
- // Extract the package name and version from the spec
172
- const atIndex = spec.lastIndexOf('@');
173
- if (atIndex === -1) {
174
- // Malformed spec, return as-is
175
- return { name, version: spec };
176
- }
177
- const specPackageName = spec.substring(0, atIndex);
178
- const specVersion = spec.substring(atIndex + 1);
179
- if (specPackageName === name) {
180
- // Regular npm package: "package@npm:package@1.0.0" -> version: "1.0.0"
181
- return { name, version: specVersion };
182
- }
183
- else {
184
- // Alias package: "alias@npm:real-package@1.0.0" -> version: "npm:real-package@1.0.0"
185
- return { name, version: `npm:${spec}` };
186
- }
187
- }
188
- else if (protocol === 'workspace') {
177
+ if (protocol === 'workspace') {
189
178
  // Workspace dependencies use the workspace path as version
190
179
  return { name, version: `workspace:${spec}` };
191
180
  }
192
- else if (protocol === 'github' || protocol === 'git') {
181
+ else if (protocol === 'github' || protocol.startsWith('git+')) {
193
182
  // Extract commit hash from GitHub/Git reference
194
- // Format: user/repo#commit-hash or repo-url#commit-hash
183
+ // Format: user/repo#commit-hash (github:) or repo-url#commit-hash
184
+ // (git+https:, git+ssh:, git+file:)
195
185
  const gitMatch = spec.match(/^(.+?)#(.+)$/);
196
186
  if (gitMatch) {
197
187
  const [, repo, commit] = gitMatch;
@@ -214,17 +204,10 @@ function parseResolvedSpec(resolvedSpec) {
214
204
  return { name, version: resolvedSpec };
215
205
  }
216
206
  }
217
- function calculatePackageHash(packageData, lockFile, name, version) {
207
+ function calculatePackageHash(packageData) {
218
208
  const [resolvedSpec, tarballUrl, metadata, hash] = packageData;
219
209
  // For NPM packages (4 elements), use the integrity hash
220
210
  if (packageData.length === 4 && hash && typeof hash === 'string') {
221
- // Use better hash from manifests if available
222
- if (lockFile.manifests && lockFile.manifests[`${name}@${version}`]) {
223
- const manifest = lockFile.manifests[`${name}@${version}`];
224
- if (manifest.dist && manifest.dist.shasum) {
225
- return manifest.dist.shasum;
226
- }
227
- }
228
211
  return hash;
229
212
  }
230
213
  // For other package types, calculate hash from available data
@@ -237,6 +220,9 @@ function calculatePackageHash(packageData, lockFile, name, version) {
237
220
  hashData.push(hash);
238
221
  return (0, file_hasher_1.hashArray)(hashData);
239
222
  }
223
+ function withPatchHash(hash, patchHash) {
224
+ return patchHash === undefined ? hash : (0, file_hasher_1.hashArray)([hash, patchHash]);
225
+ }
240
226
  /**
241
227
  * Determines if a package is an alias by comparing the package key with the resolved spec name
242
228
  * In Bun lockfiles, aliases are identified when the package key differs from the resolved package name
@@ -254,7 +240,6 @@ function buildPackageIndex(lockFile) {
254
240
  const workspaceNames = new Set();
255
241
  const workspacePaths = new Set();
256
242
  const packagesWithWorkspaceVariants = new Set();
257
- const patchedPackages = new Set();
258
243
  // Collect workspace paths
259
244
  if (lockFile.workspaces) {
260
245
  for (const workspacePath of Object.keys(lockFile.workspaces)) {
@@ -263,19 +248,9 @@ function buildPackageIndex(lockFile) {
263
248
  }
264
249
  }
265
250
  }
266
- // Collect workspace package names from workspacePackages field
267
- if (lockFile.workspacePackages) {
268
- for (const packageInfo of Object.values(lockFile.workspacePackages)) {
269
- workspaceNames.add(packageInfo.name);
270
- }
271
- }
272
- // Collect patched package names
273
- if (lockFile.patches) {
274
- for (const packageName of Object.keys(lockFile.patches)) {
275
- patchedPackages.add(packageName);
276
- }
277
- }
278
- // Collect workspace package names from workspace dependencies
251
+ // Collect workspace package names from workspace dependencies. A `file:`
252
+ // spec can name a vendored package, and a workspace it names is recorded as
253
+ // a `workspace:` package, which the pass below picks up.
279
254
  if (lockFile.workspaces) {
280
255
  for (const workspace of Object.values(lockFile.workspaces)) {
281
256
  const allDeps = {
@@ -285,8 +260,7 @@ function buildPackageIndex(lockFile) {
285
260
  ...workspace.peerDependencies,
286
261
  };
287
262
  for (const [depName, depVersion] of Object.entries(allDeps)) {
288
- if (depVersion.startsWith('workspace:') ||
289
- depVersion.startsWith('file:')) {
263
+ if (depVersion.startsWith('workspace:')) {
290
264
  workspaceNames.add(depName);
291
265
  }
292
266
  }
@@ -307,7 +281,7 @@ function buildPackageIndex(lockFile) {
307
281
  continue;
308
282
  }
309
283
  // Track workspace packages from packages section
310
- if (protocol === 'workspace' || protocol === 'file') {
284
+ if (protocol === 'workspace') {
311
285
  workspaceNames.add(name);
312
286
  }
313
287
  // Check if this is a workspace-specific variant (e.g., "@quz/pkg1/lodash")
@@ -333,7 +307,7 @@ function buildPackageIndex(lockFile) {
333
307
  byName.set(name, entries);
334
308
  }
335
309
  // Calculate hash once
336
- const hash = calculatePackageHash(packageData, lockFile, name, version);
310
+ const hash = calculatePackageHash(packageData);
337
311
  entries.push({ version, packageKey, hash });
338
312
  }
339
313
  }
@@ -342,9 +316,100 @@ function buildPackageIndex(lockFile) {
342
316
  workspaceNames,
343
317
  workspacePaths,
344
318
  packagesWithWorkspaceVariants,
345
- patchedPackages,
319
+ localPathSources: getBunLocalPathSources(lockFile),
346
320
  };
347
321
  }
322
+ function normalizeBunLocalPath(path) {
323
+ return node_path_1.posix.normalize(path.replace(/\\/g, '/')).replace(/(.)\/+$/, '$1');
324
+ }
325
+ /**
326
+ * The packages a bun.lock installs from the local file tree, keyed by package
327
+ * key. A directory or link entry records its path relative to the lockfile. A
328
+ * tarball entry records it relative to the dependent that declares it: the
329
+ * workspace or local directory whose lookup reaches the entry for a `file:`
330
+ * spec of that path. A tarball no declarer reaches is left out.
331
+ */
332
+ function getBunLocalPathSources(lockFile) {
333
+ const sources = new Map();
334
+ const packages = lockFile.packages ?? {};
335
+ const workspaces = lockFile.workspaces ?? {};
336
+ const tarballPaths = new Map();
337
+ for (const [key, tuple] of Object.entries(packages)) {
338
+ if (!Array.isArray(tuple) || typeof tuple[0] !== 'string') {
339
+ continue;
340
+ }
341
+ const { version, protocol } = getCachedSpecInfo(tuple[0]);
342
+ if (protocol === 'file' || protocol === 'link') {
343
+ const path = normalizeBunLocalPath(version.slice(protocol.length + 1));
344
+ if (protocol === 'file' &&
345
+ Object.prototype.hasOwnProperty.call(workspaces, path)) {
346
+ continue;
347
+ }
348
+ sources.set(key, {
349
+ kind: protocol === 'file' ? 'directory' : 'link',
350
+ path,
351
+ });
352
+ }
353
+ else if (protocol === 'npm' &&
354
+ tuple[1] !== null &&
355
+ typeof tuple[1] === 'object') {
356
+ // A registry entry records its registry URL there instead.
357
+ tarballPaths.set(key, normalizeBunLocalPath(version));
358
+ }
359
+ }
360
+ if (!tarballPaths.size) {
361
+ return sources;
362
+ }
363
+ const hasKey = (key) => Object.prototype.hasOwnProperty.call(packages, key);
364
+ const declarers = [];
365
+ for (const [path, workspace] of Object.entries(workspaces)) {
366
+ if (path === '' || workspace.name) {
367
+ declarers.push({
368
+ scope: path === '' ? [] : [workspace.name],
369
+ dir: path,
370
+ dependencies: workspace,
371
+ });
372
+ }
373
+ }
374
+ for (const [key, source] of sources) {
375
+ if (source.kind === 'directory') {
376
+ declarers.push({
377
+ scope: splitBunPackageKey(key),
378
+ dir: source.path,
379
+ dependencies: extractPackageDependencies(packages[key]),
380
+ });
381
+ }
382
+ }
383
+ for (const { scope, dir, dependencies } of declarers) {
384
+ for (const depType of DEPENDENCY_TYPES) {
385
+ for (const [name, spec] of Object.entries(dependencies?.[depType] ?? {})) {
386
+ if (typeof spec !== 'string' || !spec.startsWith('file:')) {
387
+ continue;
388
+ }
389
+ const key = findNearestBunPackageKey(scope, name, hasKey);
390
+ const recordedPath = key === undefined ? undefined : tarballPaths.get(key);
391
+ if (recordedPath === undefined ||
392
+ sources.has(key) ||
393
+ recordedPath !== normalizeBunLocalPath(spec.slice(5))) {
394
+ continue;
395
+ }
396
+ sources.set(key, {
397
+ kind: 'tarball',
398
+ path: node_path_1.posix.isAbsolute(recordedPath)
399
+ ? recordedPath
400
+ : normalizeBunLocalPath(node_path_1.posix.join(dir, recordedPath)),
401
+ });
402
+ }
403
+ }
404
+ }
405
+ return sources;
406
+ }
407
+ function parseBunLockFile(lockFileContent) {
408
+ return (0, json_1.parseJson)(lockFileContent, {
409
+ allowTrailingComma: true,
410
+ expectComments: true,
411
+ });
412
+ }
348
413
  function parseLockFile(lockFileContent, lockFileHash) {
349
414
  if (currentLockFileHash === lockFileHash &&
350
415
  cachedParsedLockFile &&
@@ -353,10 +418,7 @@ function parseLockFile(lockFileContent, lockFileHash) {
353
418
  }
354
419
  clearCache();
355
420
  try {
356
- const result = (0, json_1.parseJson)(lockFileContent, {
357
- allowTrailingComma: true,
358
- expectComments: true,
359
- });
421
+ const result = parseBunLockFile(lockFileContent);
360
422
  // Validate basic structure
361
423
  if (!result || typeof result !== 'object') {
362
424
  throw new Error('Lockfile root must be an object');
@@ -380,42 +442,6 @@ function parseLockFile(lockFileContent, lockFileHash) {
380
442
  if (!result.workspaces || typeof result.workspaces !== 'object') {
381
443
  throw new Error('Lockfile workspaces section must be an object');
382
444
  }
383
- // Validate optional sections
384
- if (result.patches && typeof result.patches !== 'object') {
385
- throw new Error('Lockfile patches section must be an object');
386
- }
387
- if (result.manifests && typeof result.manifests !== 'object') {
388
- throw new Error('Lockfile manifests section must be an object');
389
- }
390
- if (result.workspacePackages &&
391
- typeof result.workspacePackages !== 'object') {
392
- throw new Error('Lockfile workspacePackages section must be an object');
393
- }
394
- // Validate structure of patches entries
395
- if (result.patches) {
396
- for (const [packageName, patchInfo] of Object.entries(result.patches)) {
397
- if (!patchInfo || typeof patchInfo !== 'object') {
398
- throw new Error(`Invalid patch entry for package "${packageName}": must be an object`);
399
- }
400
- if (!patchInfo.path || typeof patchInfo.path !== 'string') {
401
- throw new Error(`Invalid patch entry for package "${packageName}": path must be a string`);
402
- }
403
- }
404
- }
405
- // Validate structure of workspace packages entries
406
- if (result.workspacePackages) {
407
- for (const [packageName, packageInfo] of Object.entries(result.workspacePackages)) {
408
- if (!packageInfo || typeof packageInfo !== 'object') {
409
- throw new Error(`Invalid workspace package entry for "${packageName}": must be an object`);
410
- }
411
- if (!packageInfo.name || typeof packageInfo.name !== 'string') {
412
- throw new Error(`Invalid workspace package entry for "${packageName}": name must be a string`);
413
- }
414
- if (!packageInfo.version || typeof packageInfo.version !== 'string') {
415
- throw new Error(`Invalid workspace package entry for "${packageName}": version must be a string`);
416
- }
417
- }
418
- }
419
445
  cachedParsedLockFile = result;
420
446
  currentLockFileHash = lockFileHash;
421
447
  // Build the optimized index
@@ -437,7 +463,12 @@ function parseLockFile(lockFileContent, lockFileHash) {
437
463
  }
438
464
  }
439
465
  // ===== MAIN EXPORT FUNCTIONS =====
440
- function getBunTextLockfileNodes(lockFileContent, lockFileHash) {
466
+ /**
467
+ * @param patchFileHashes the {@link getBunPatchFileHashes} that `lockFileHash`
468
+ * covers, folded into the hashes of the packages they patch. Omitted, patched
469
+ * packages hash like unpatched ones.
470
+ */
471
+ function getBunTextLockfileNodes(lockFileContent, lockFileHash, patchFileHashes) {
441
472
  try {
442
473
  const { lockFile, index } = parseLockFile(lockFileContent, lockFileHash);
443
474
  const nodes = {};
@@ -445,9 +476,16 @@ function getBunTextLockfileNodes(lockFileContent, lockFileHash) {
445
476
  if (!lockFile.packages || Object.keys(lockFile.packages).length === 0) {
446
477
  return nodes;
447
478
  }
479
+ const patchHashes = new Map();
480
+ for (const [resolution, patchPath] of Object.entries(lockFile.patchedDependencies ?? {})) {
481
+ const patchHash = patchFileHashes?.get(patchPath);
482
+ if (patchHash !== undefined) {
483
+ patchHashes.set(resolution, patchHash);
484
+ }
485
+ }
448
486
  const packageEntries = Object.entries(lockFile.packages);
449
487
  for (const [packageKey, packageData] of packageEntries) {
450
- const result = processPackageEntry(packageKey, packageData, lockFile, index, keyMap, nodes, localPackageVersions);
488
+ const result = processPackageEntry(packageKey, packageData, lockFile, index, keyMap, nodes, localPackageVersions, patchHashes);
451
489
  if (result.shouldContinue) {
452
490
  continue;
453
491
  }
@@ -462,7 +500,80 @@ function getBunTextLockfileNodes(lockFileContent, lockFileHash) {
462
500
  throw new Error(`Failed to get Bun lockfile nodes: ${error.message}`);
463
501
  }
464
502
  }
465
- function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, nodes, packageVersions) {
503
+ /**
504
+ * The workspace-relative sources of the `nodes` that install from the local
505
+ * file tree, keyed by node name. The lockfile records only their paths, so the
506
+ * contents of these sources are what change when the packages do.
507
+ */
508
+ function getBunLocalPathNodeSources(lockFileContent, lockFileHash, nodes) {
509
+ const { lockFile, index } = parseLockFile(lockFileContent, lockFileHash);
510
+ const sourcesByResolution = new Map();
511
+ for (const [key, source] of index.localPathSources) {
512
+ const { name, version } = getCachedSpecInfo(lockFile.packages[key][0]);
513
+ const resolution = `${name}@${version}`;
514
+ if (!sourcesByResolution.has(resolution)) {
515
+ sourcesByResolution.set(resolution, new Set());
516
+ }
517
+ sourcesByResolution.get(resolution).add(source.path);
518
+ }
519
+ const nodeSources = {};
520
+ if (!sourcesByResolution.size) {
521
+ return nodeSources;
522
+ }
523
+ for (const node of Object.values(nodes)) {
524
+ const aliasTarget = resolveAliasTarget(node.data.version);
525
+ const sources = sourcesByResolution.get(aliasTarget
526
+ ? `${aliasTarget.packageName}@${aliasTarget.version}`
527
+ : `${node.data.packageName}@${node.data.version}`);
528
+ if (sources) {
529
+ nodeSources[node.name] = [...sources].sort();
530
+ }
531
+ }
532
+ return nodeSources;
533
+ }
534
+ /**
535
+ * The local-path node each workspace installs per dependency name, keyed by
536
+ * its path ('.' for the root). Aliases are left out.
537
+ */
538
+ function getBunInstalledLocalPathNodes(lockFileContent, lockFileHash, nodes) {
539
+ const { lockFile, index } = parseLockFile(lockFileContent, lockFileHash);
540
+ const installed = {};
541
+ if (!index.localPathSources.size) {
542
+ return installed;
543
+ }
544
+ const packages = lockFile.packages ?? {};
545
+ const hasKey = (key) => Object.prototype.hasOwnProperty.call(packages, key);
546
+ for (const [path, workspace] of Object.entries(lockFile.workspaces ?? {})) {
547
+ // Bun keys a workspace's nested packages by its name
548
+ if (path !== '' && !workspace.name) {
549
+ continue;
550
+ }
551
+ const scope = path === '' ? [] : [workspace.name];
552
+ for (const depType of DEPENDENCY_TYPES) {
553
+ for (const depName of Object.keys(workspace[depType] ?? {})) {
554
+ const key = findNearestBunPackageKey(scope, depName, hasKey);
555
+ if (key === undefined || !index.localPathSources.has(key)) {
556
+ continue;
557
+ }
558
+ // Bun 1.3 can write the root's local copy under the key of the
559
+ // workspace package a `workspace:` spec installs. An override of that
560
+ // spec gets a key in the workspace's own scope.
561
+ if (scope.length &&
562
+ key === depName &&
563
+ workspace[depType][depName].startsWith('workspace:')) {
564
+ continue;
565
+ }
566
+ const { name, version } = getCachedSpecInfo(packages[key][0]);
567
+ const node = nodes[`npm:${name}@${version}`];
568
+ if (name === depName && node) {
569
+ (installed[path || '.'] ??= {})[depName] = node.name;
570
+ }
571
+ }
572
+ }
573
+ }
574
+ return installed;
575
+ }
576
+ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, nodes, packageVersions, patchHashes) {
466
577
  try {
467
578
  if (!Array.isArray(packageData) ||
468
579
  packageData.length < 1 ||
@@ -480,11 +591,10 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
480
591
  console.warn(`Lockfile contains unrecognized package format. Try regenerating the lockfile with 'bun install --force'.\nDebug: could not parse resolved spec '${resolvedSpec}'`);
481
592
  return { shouldContinue: true };
482
593
  }
483
- // O(1) lookups using index
484
- if (index.workspaceNames.has(name)) {
485
- return { shouldContinue: true };
486
- }
487
- if (index.patchedPackages.has(name)) {
594
+ // O(1) lookups using index. A local package can share a workspace
595
+ // package's name, and only its path tells whether it installs that one.
596
+ if (index.workspaceNames.has(name) &&
597
+ !isNonWorkspaceLocalPackage(packageKey, index)) {
488
598
  return { shouldContinue: true };
489
599
  }
490
600
  if (protocol === 'workspace') {
@@ -495,6 +605,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
495
605
  const aliasName = packageKey;
496
606
  const actualPackageName = name;
497
607
  const actualVersion = version;
608
+ const hash = withPatchHash(calculatePackageHash(packageData), patchHashes.get(`${actualPackageName}@${actualVersion}`));
498
609
  const aliasNodeKey = `npm:${aliasName}`;
499
610
  if (!keyMap.has(aliasNodeKey)) {
500
611
  const aliasNode = {
@@ -503,7 +614,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
503
614
  data: {
504
615
  version: `npm:${actualPackageName}@${actualVersion}`,
505
616
  packageName: aliasName,
506
- hash: calculatePackageHash(packageData, lockFile, aliasName, `npm:${actualPackageName}@${actualVersion}`),
617
+ hash,
507
618
  },
508
619
  };
509
620
  keyMap.set(aliasNodeKey, aliasNode);
@@ -517,7 +628,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
517
628
  data: {
518
629
  version: actualVersion,
519
630
  packageName: actualPackageName,
520
- hash: calculatePackageHash(packageData, lockFile, actualPackageName, actualVersion),
631
+ hash,
521
632
  },
522
633
  };
523
634
  keyMap.set(targetNodeKey, targetNode);
@@ -544,7 +655,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
544
655
  nodes[nodeKey] = keyMap.get(nodeKey);
545
656
  return { shouldContinue: false };
546
657
  }
547
- const nodeHash = calculatePackageHash(packageData, lockFile, name, version);
658
+ const nodeHash = withPatchHash(calculatePackageHash(packageData), patchHashes.get(`${name}@${version}`));
548
659
  const node = {
549
660
  type: 'npm',
550
661
  name: nodeKey,
@@ -564,10 +675,12 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
564
675
  return { shouldContinue: true };
565
676
  }
566
677
  }
567
- function isWorkspaceOrPatchedPackage(packageName, index, workspacePackages) {
568
- return (workspacePackages.has(packageName) ||
569
- index.workspaceNames.has(packageName) ||
570
- index.patchedPackages.has(packageName));
678
+ function isNonWorkspaceLocalPackage(packageKey, index) {
679
+ const source = index.localPathSources.get(packageKey);
680
+ return source !== undefined && !index.workspacePaths.has(source.path);
681
+ }
682
+ function isWorkspacePackage(packageName, index, workspacePackages) {
683
+ return (workspacePackages.has(packageName) || index.workspaceNames.has(packageName));
571
684
  }
572
685
  function resolveAliasTarget(versionSpec) {
573
686
  if (!versionSpec.startsWith('npm:'))
@@ -597,9 +710,12 @@ function processPackageToPackageDependencies(lockFile, index, ctx, workspacePack
597
710
  return dependencies;
598
711
  }
599
712
  function processPackageForDependencies(packageKey, packageData, lockFile, index, ctx, workspacePackages) {
600
- // O(1) checks using index
601
- if (index.workspaceNames.has(packageKey) ||
602
- isNestedPackageKey(packageKey, index)) {
713
+ // A local package is its own node, also when Bun keys it by a workspace
714
+ // package's name or nests it under the workspace that declares it.
715
+ const isLocalPackage = index.localPathSources.has(packageKey);
716
+ if ((index.workspaceNames.has(packageKey) ||
717
+ isNestedPackageKey(packageKey, index)) &&
718
+ !isLocalPackage) {
603
719
  return [];
604
720
  }
605
721
  if (!Array.isArray(packageData) || packageData.length < 1) {
@@ -613,9 +729,6 @@ function processPackageForDependencies(packageKey, packageData, lockFile, index,
613
729
  if (!sourcePackageName || !sourceVersion) {
614
730
  return [];
615
731
  }
616
- if (index.patchedPackages.has(sourcePackageName)) {
617
- return [];
618
- }
619
732
  const sourceNodeName = `npm:${sourcePackageName}@${sourceVersion}`;
620
733
  if (!ctx.externalNodes[sourceNodeName]) {
621
734
  return [];
@@ -632,6 +745,26 @@ function processPackageForDependencies(packageKey, packageData, lockFile, index,
632
745
  const depDependencies = processDependencyEntries(deps, packageKey, sourceNodeName, lockFile, index, ctx, workspacePackages);
633
746
  dependencies.push(...depDependencies);
634
747
  }
748
+ // An import can resolve to a local package's bare node, as the locator's
749
+ // last fallback, or to an aliased package's alias node, so both nodes carry
750
+ // the package's edges.
751
+ const edgeSources = [];
752
+ const bareNodeName = `npm:${sourcePackageName}`;
753
+ if (isLocalPackage &&
754
+ ctx.externalNodes[bareNodeName]?.data.version === sourceVersion) {
755
+ edgeSources.push(bareNodeName);
756
+ }
757
+ const aliasNodeName = `npm:${packageKey}`;
758
+ if (ctx.externalNodes[aliasNodeName]?.data.version ===
759
+ `npm:${sourcePackageName}@${sourceVersion}`) {
760
+ edgeSources.push(aliasNodeName);
761
+ }
762
+ const packageEdges = [...dependencies];
763
+ for (const source of edgeSources) {
764
+ for (const dependency of packageEdges) {
765
+ dependencies.push({ ...dependency, source });
766
+ }
767
+ }
635
768
  return dependencies;
636
769
  }
637
770
  function extractPackageDependencies(packageData) {
@@ -667,8 +800,10 @@ function processSingleDependency(packageName, versionSpec, sourcePackageKey, sou
667
800
  if (typeof packageName !== 'string' || typeof versionSpec !== 'string') {
668
801
  return null;
669
802
  }
670
- // O(1) check using index
671
- if (isWorkspaceOrPatchedPackage(packageName, index, workspacePackages)) {
803
+ // A local package can share a workspace package's name, and only the path
804
+ // this parent resolved it to tells whether it installs that one.
805
+ if (isWorkspacePackage(packageName, index, workspacePackages) &&
806
+ !isNonWorkspaceLocalPackage(`${sourcePackageKey}/${packageName}`, index)) {
672
807
  return null;
673
808
  }
674
809
  if (versionSpec.startsWith('workspace:')) {
@@ -691,7 +826,7 @@ function processSingleDependency(packageName, versionSpec, sourcePackageKey, sou
691
826
  }
692
827
  else {
693
828
  // O(1) lookup using index instead of O(n) scan
694
- const resolvedVersion = findResolvedVersion(packageName, versionSpec, index, lockFile.manifests);
829
+ const resolvedVersion = findResolvedVersion(packageName, versionSpec, index);
695
830
  if (!resolvedVersion) {
696
831
  return null;
697
832
  }
@@ -740,6 +875,9 @@ function resolveTargetNodeName(targetPackageName, targetVersion, ctx) {
740
875
  // ===== HOISTING-RELATED FUNCTIONS =====
741
876
  function createHoistedNodes(packageVersions, lockFile, index, keyMap, nodes) {
742
877
  for (const [packageName, versions] of packageVersions.entries()) {
878
+ if (index.workspaceNames.has(packageName)) {
879
+ continue;
880
+ }
743
881
  const hoistedNodeKey = `npm:${packageName}`;
744
882
  if (shouldCreateHoistedNode(packageName, lockFile, index)) {
745
883
  const hoistedVersion = getHoistedVersion(packageName, versions, index);
@@ -864,36 +1002,22 @@ function getHoistedVersion(packageName, availableVersions, index) {
864
1002
  *
865
1003
  * O(1) lookup using pre-computed index instead of O(n) scan through all packages
866
1004
  */
867
- function findResolvedVersion(packageName, versionSpec, index, manifests) {
1005
+ function findResolvedVersion(packageName, versionSpec, index) {
868
1006
  // Resolution depends only on (packageName, versionSpec) for a given lockfile
869
- // (index and manifests are constant per parse), so memoize across edges.
1007
+ // (the index is constant per parse), so memoize across edges.
870
1008
  const cacheKey = `${packageName}\n${versionSpec}`;
871
1009
  const cached = resolvedVersionCache.get(cacheKey);
872
1010
  if (cached !== undefined) {
873
1011
  return cached;
874
1012
  }
875
- const resolved = computeResolvedVersion(packageName, versionSpec, index, manifests);
1013
+ const resolved = computeResolvedVersion(packageName, versionSpec, index);
876
1014
  resolvedVersionCache.set(cacheKey, resolved);
877
1015
  return resolved;
878
1016
  }
879
- function computeResolvedVersion(packageName, versionSpec, index, manifests) {
1017
+ function computeResolvedVersion(packageName, versionSpec, index) {
880
1018
  // O(1) lookup
881
1019
  const candidates = index.byName.get(packageName);
882
1020
  if (!candidates || candidates.length === 0) {
883
- // Try to find in manifests as fallback
884
- if (manifests) {
885
- const exactManifestKey = `${packageName}@${versionSpec}`;
886
- if (manifests[exactManifestKey]) {
887
- return versionSpec;
888
- }
889
- const manifestKey = Object.keys(manifests).find((key) => key.startsWith(`${packageName}@`));
890
- if (manifestKey) {
891
- const manifest = manifests[manifestKey];
892
- if (manifest.version) {
893
- return manifest.version;
894
- }
895
- }
896
- }
897
1021
  return null;
898
1022
  }
899
1023
  // Check for exact version match first (most common case)
@@ -990,3 +1114,711 @@ function findBestVersionMatch(versionSpec, candidates) {
990
1114
  }
991
1115
  return best.version;
992
1116
  }
1117
+ // Bun resolutions that point into the workspace's own file tree. The pruned
1118
+ // output ships the local packages `getBunLocalPathSources` lists, and no other.
1119
+ const LOCAL_RESOLUTION_PROTOCOLS = new Set([
1120
+ 'root',
1121
+ 'workspace',
1122
+ 'file',
1123
+ 'link',
1124
+ ]);
1125
+ /**
1126
+ * Writes the bun.lock for a standalone install of `packageJson`, with every
1127
+ * package at the version the root lockfile installs for it. Dependencies are
1128
+ * resolved through the root lockfile's keys, since the project graph records
1129
+ * no dependencies of a nested package. The kept packages are laid out in a new
1130
+ * tree rooted at the pruned manifest. Bun rebuilds its hoisting on install, so
1131
+ * each dependency only has to resolve to the same package, except that a
1132
+ * bundled tree stays under its bundler.
1133
+ *
1134
+ * Workspace modules become `file:./workspace_modules/<name>` dependencies.
1135
+ * `projectRoot` is where the manifest's local-path specs resolve from, and it
1136
+ * locates the project's own workspace entry, whose resolutions are kept for
1137
+ * the specs it declares even where an override replaced them. `onPinnedSpec`
1138
+ * receives the locked version the output declares for such a dependency.
1139
+ * Returns an empty string for a manifest without dependencies, which gets no
1140
+ * lockfile.
1141
+ */
1142
+ function stringifyBunLockfile(graph, rootLockFileContent, packageJson, workspaceRootPath, projectRoot, onPinnedSpec) {
1143
+ const rootLockFile = parseBunLockFile(rootLockFileContent);
1144
+ if (!rootLockFile?.packages || !rootLockFile.workspaces) {
1145
+ throw new Error('Pruned lock file creation failed. The root bun.lock has no "packages" or "workspaces" section.');
1146
+ }
1147
+ const rootPackages = rootLockFile.packages;
1148
+ const hasRootPackage = (key) => Object.prototype.hasOwnProperty.call(rootPackages, key);
1149
+ const localSources = getBunLocalPathSources(rootLockFile);
1150
+ const workspacePackages = (0, get_workspace_packages_from_graph_1.getWorkspacePackagesFromGraph)(graph);
1151
+ const resolvesToWorkspaceModule = (name, spec, dependentRoot) => !!(0, pruned_output_1.resolveWorkspaceModuleDependency)(workspacePackages, name, spec, dependentRoot, workspaceRootPath);
1152
+ const catalogManager = (0, catalog_1.getCatalogManager)(workspaceRootPath);
1153
+ const resolveCatalog = (name, spec) => {
1154
+ if (!catalogManager?.isCatalogReference(spec)) {
1155
+ return spec;
1156
+ }
1157
+ const resolved = catalogManager.resolveCatalogReference(workspaceRootPath, name, spec);
1158
+ if (!resolved) {
1159
+ throw new Error(`Could not resolve catalog reference for ${name}@${spec}.`);
1160
+ }
1161
+ return resolved;
1162
+ };
1163
+ // `shippedSpec` is the spec the dependent's shipped manifest declares the
1164
+ // package under.
1165
+ const createPackage = (key, shippedSpec) => {
1166
+ const tuple = rootPackages[key];
1167
+ const resolution = tuple?.[0];
1168
+ if (typeof resolution !== 'string') {
1169
+ throw new Error(`Pruned lock file creation failed. The root lock file has an invalid entry for "${key}".`);
1170
+ }
1171
+ const source = localSources.get(key);
1172
+ if (!source &&
1173
+ LOCAL_RESOLUTION_PROTOCOLS.has(getCachedSpecInfo(resolution).protocol)) {
1174
+ throw new Error(`Pruned lock file creation failed. ${resolution} is a local package that the pruned output does not ship.`);
1175
+ }
1176
+ const shippedResolution = source
1177
+ ? getShippedLocalResolution(resolution, source, shippedSpec)
1178
+ : resolution;
1179
+ return {
1180
+ resolution: shippedResolution,
1181
+ tuple: source ? [shippedResolution, ...tuple.slice(1)] : tuple,
1182
+ rootScope: splitBunPackageKey(key),
1183
+ dependencies: extractPackageDependencies(tuple),
1184
+ isWorkspaceModule: false,
1185
+ };
1186
+ };
1187
+ // Mirrors the manifest copy-workspace-modules writes for the copy: catalog
1188
+ // references resolved and sibling modules pointed at their copies (a peer one
1189
+ // moved into dependencies). A frozen install takes a folder dependency's
1190
+ // dependencies from this entry. The entry leaves out devDependencies as the
1191
+ // copy does; otherwise Bun installs them and fails on a `workspace:` one.
1192
+ const getShippedModuleDependencies = (name, workspacePath, workspace) => {
1193
+ const shipped = {};
1194
+ for (const depType of DEPENDENCY_TYPES) {
1195
+ if (depType === 'devDependencies') {
1196
+ continue;
1197
+ }
1198
+ for (const [dep, spec] of Object.entries(workspace[depType] ?? {})) {
1199
+ if (resolvesToWorkspaceModule(dep, spec, workspacePath)) {
1200
+ const section = depType === 'peerDependencies' ? 'dependencies' : depType;
1201
+ (shipped[section] ??= {})[dep] = `file:${node_path_1.posix.relative(`workspace_modules/${name}`, `workspace_modules/${dep}`)}`;
1202
+ }
1203
+ else {
1204
+ // Bun resolves a folder dependency's local specs from its own
1205
+ // directory, so they follow the copy.
1206
+ const resolved = resolveCatalog(dep, spec);
1207
+ const relocation = (0, pruned_output_1.relocatePrunedLocalPathSpec)(resolved, workspacePath, `workspace_modules/${name}`);
1208
+ (shipped[depType] ??= {})[dep] =
1209
+ relocation && !relocation.reason ? relocation.spec : resolved;
1210
+ }
1211
+ }
1212
+ }
1213
+ const optionalPeers = workspace.optionalPeers?.filter((peer) => shipped.peerDependencies?.[peer]);
1214
+ if (optionalPeers?.length) {
1215
+ shipped.optionalPeers = optionalPeers;
1216
+ }
1217
+ const unresolved = workspace.unresolved?.filter((dep) => shipped.optionalDependencies?.[dep]);
1218
+ if (unresolved?.length) {
1219
+ shipped.unresolved = unresolved;
1220
+ }
1221
+ return sortDependencyGroups(shipped);
1222
+ };
1223
+ // Bun records a folder dependency of a folder dependency without its
1224
+ // dependencies and never installs them, so a nested module is not expanded.
1225
+ const createWorkspaceModule = (name, nested) => {
1226
+ const resolution = `${name}@file:workspace_modules/${name}`;
1227
+ if (nested) {
1228
+ return { resolution, tuple: [resolution, {}], isWorkspaceModule: true };
1229
+ }
1230
+ const [workspacePath, workspace] = Object.entries(rootLockFile.workspaces).find(([path, entry]) => path !== '' && entry.name === name) ?? [];
1231
+ if (!workspace) {
1232
+ throw new Error(`Pruned lock file creation failed. The workspace package ${name} was not found in the root lock file.`);
1233
+ }
1234
+ return {
1235
+ resolution,
1236
+ tuple: [
1237
+ resolution,
1238
+ getShippedModuleDependencies(name, workspacePath, workspace),
1239
+ ],
1240
+ rootScope: [name],
1241
+ dependencies: workspace,
1242
+ isWorkspaceModule: true,
1243
+ workspacePath,
1244
+ };
1245
+ };
1246
+ const placed = new Map();
1247
+ const queue = [];
1248
+ const place = (dependentPath, name, pkg, nestUnderDependent = false) => {
1249
+ const reachedKey = findNearestBunPackageKey(dependentPath, name, (key) => placed.has(key));
1250
+ if (placed.get(reachedKey)?.resolution === pkg.resolution) {
1251
+ return;
1252
+ }
1253
+ // The hoisted slot is safe while no key on the dependent's path resolves
1254
+ // the name. Otherwise nesting under the dependent shadows nothing, because
1255
+ // its subtree only gains packages as its own dependencies are placed here.
1256
+ const path = reachedKey || nestUnderDependent ? [...dependentPath, name] : [name];
1257
+ const prunedPackage = { ...pkg, path };
1258
+ placed.set(path.join('/'), prunedPackage);
1259
+ queue.push(prunedPackage);
1260
+ };
1261
+ // Bun lists a tarball's bundled tree under the bundler, as the tarball lays it
1262
+ // out, so that subtree keeps its root lockfile layout.
1263
+ const placeBundled = (bundle, pkg) => {
1264
+ const path = [
1265
+ ...bundle.path,
1266
+ ...pkg.rootScope.slice(bundle.rootScope.length),
1267
+ ];
1268
+ const key = path.join('/');
1269
+ const existing = placed.get(key);
1270
+ if (existing) {
1271
+ if (existing.resolution !== pkg.resolution) {
1272
+ throw new Error(`Pruned lock file creation failed. ${pkg.resolution}, bundled by ${bundle.path.join('/')}, conflicts with ${existing.resolution}.`);
1273
+ }
1274
+ return;
1275
+ }
1276
+ const prunedPackage = { ...pkg, path, bundle };
1277
+ placed.set(key, prunedPackage);
1278
+ queue.push(prunedPackage);
1279
+ };
1280
+ const rootWorkspace = {};
1281
+ // The project's own entry records what the root install resolved for the
1282
+ // specs it declares. Bun keys the root entry ''.
1283
+ const projectWorkspacePath = projectRoot !== undefined ? normalizeBunLocalPath(projectRoot) : undefined;
1284
+ const projectWorkspace = projectWorkspacePath !== undefined
1285
+ ? rootLockFile.workspaces[projectWorkspacePath === '.' ? '' : projectWorkspacePath]
1286
+ : undefined;
1287
+ const appWorkspace = projectWorkspace?.name === packageJson.name ? projectWorkspace : undefined;
1288
+ // The manifest name can belong to another workspace or a nested package, so
1289
+ // it scopes the app's resolutions only when it names the app's own workspace
1290
+ // entry, or any workspace when no `projectRoot` locates that entry. The
1291
+ // root's resolutions are unscoped.
1292
+ const isAppWorkspaceName = projectWorkspacePath !== undefined
1293
+ ? appWorkspace !== undefined && projectWorkspacePath !== '.'
1294
+ : Object.entries(rootLockFile.workspaces).some(([path, entry]) => path !== '' && entry.name === packageJson.name);
1295
+ const appScope = packageJson.name && isAppWorkspaceName ? [packageJson.name] : [];
1296
+ const unresolvedRootDependencies = [];
1297
+ const placedRootDependencies = new Set();
1298
+ for (const depType of DEPENDENCY_TYPES) {
1299
+ for (const [name, spec] of Object.entries(packageJson[depType] ?? {})) {
1300
+ const isWorkspaceModule = resolvesToWorkspaceModule(name, spec, projectRoot);
1301
+ if (isWorkspaceModule) {
1302
+ // Matches the manifest prune-lockfile writes, which also moves a
1303
+ // peer-declared module into dependencies.
1304
+ const section = depType === 'peerDependencies' ? 'dependencies' : depType;
1305
+ (rootWorkspace[section] ??= {})[name] =
1306
+ `file:./workspace_modules/${name}`;
1307
+ }
1308
+ else {
1309
+ (rootWorkspace[depType] ??= {})[name] = spec;
1310
+ }
1311
+ if (placedRootDependencies.has(name)) {
1312
+ continue;
1313
+ }
1314
+ placedRootDependencies.add(name);
1315
+ if (isWorkspaceModule) {
1316
+ place([], name, createWorkspaceModule(name, false));
1317
+ continue;
1318
+ }
1319
+ if (depType === 'peerDependencies' &&
1320
+ packageJson.peerDependenciesMeta?.[name]?.optional) {
1321
+ continue;
1322
+ }
1323
+ if (depType === 'optionalDependencies' &&
1324
+ appWorkspace?.unresolved?.includes(name)) {
1325
+ unresolvedRootDependencies.push(name);
1326
+ continue;
1327
+ }
1328
+ const resolvedSpec = resolveCatalog(name, spec);
1329
+ const appSpec = appWorkspace?.[depType]?.[name];
1330
+ const appResolvedSpec = appSpec !== undefined
1331
+ ? resolveLockfileCatalog(rootLockFile, name, appSpec)
1332
+ : undefined;
1333
+ // The manifest's local-path specs arrive relocated.
1334
+ const declaredByApp = appResolvedSpec !== undefined &&
1335
+ ((0, pruned_output_1.relocatePrunedLocalPathSpec)(appResolvedSpec, projectRoot, '')?.spec ??
1336
+ appResolvedSpec) === resolvedSpec;
1337
+ // A library's manifest takes the specs it doesn't declare from the
1338
+ // root, which installs them in its own scope.
1339
+ const declaredByRoot = !declaredByApp &&
1340
+ DEPENDENCY_TYPES.some((type) => {
1341
+ const rootSpec = rootLockFile.workspaces['']?.[type]?.[name];
1342
+ return (rootSpec !== undefined &&
1343
+ resolveLockfileCatalog(rootLockFile, name, rootSpec) ===
1344
+ resolvedSpec);
1345
+ });
1346
+ const declaredByInstaller = declaredByApp || declaredByRoot;
1347
+ const key = findManifestDependencyKey(rootPackages, localSources, declaredByRoot ? [] : appScope, name, resolvedSpec, declaredByInstaller);
1348
+ if (key) {
1349
+ place([], name, createPackage(key, resolvedSpec));
1350
+ const pinnedSpec = declaredByInstaller
1351
+ ? getOverriddenVersionSpec(rootPackages[key], resolvedSpec, depType === 'optionalDependencies')
1352
+ : undefined;
1353
+ if (pinnedSpec) {
1354
+ rootWorkspace[depType][name] = pinnedSpec;
1355
+ onPinnedSpec?.({ depType, name, spec: pinnedSpec });
1356
+ }
1357
+ }
1358
+ else if (depType !== 'optionalDependencies') {
1359
+ throw new Error(`Pruned lock file creation failed. The following package was not found in the root lock file: ${name}@${spec}`);
1360
+ }
1361
+ }
1362
+ }
1363
+ // Bun writes no lockfile for a manifest without dependencies, and a frozen
1364
+ // install rejects any lockfile there.
1365
+ if (DEPENDENCY_TYPES.every((depType) => !rootWorkspace[depType])) {
1366
+ return '';
1367
+ }
1368
+ const optionalRootPeers = Object.keys(rootWorkspace.peerDependencies ?? {})
1369
+ .filter((name) => packageJson.peerDependenciesMeta?.[name]?.optional)
1370
+ .sort(compareStrings);
1371
+ if (optionalRootPeers.length) {
1372
+ rootWorkspace.optionalPeers = optionalRootPeers;
1373
+ }
1374
+ for (let i = 0; i < queue.length; i++) {
1375
+ const pkg = queue[i];
1376
+ if (!pkg.rootScope) {
1377
+ continue;
1378
+ }
1379
+ const seen = new Set();
1380
+ for (const depType of DEPENDENCY_TYPES) {
1381
+ if (pkg.isWorkspaceModule && depType === 'devDependencies') {
1382
+ continue;
1383
+ }
1384
+ for (const name of Object.keys(pkg.dependencies?.[depType] ?? {})) {
1385
+ if (seen.has(name) ||
1386
+ (depType === 'optionalDependencies' &&
1387
+ pkg.dependencies.unresolved?.includes(name))) {
1388
+ continue;
1389
+ }
1390
+ seen.add(name);
1391
+ if (pkg.isWorkspaceModule &&
1392
+ resolvesToWorkspaceModule(name, pkg.dependencies[depType][name], pkg.workspacePath)) {
1393
+ place(pkg.path, name, createWorkspaceModule(name, true), true);
1394
+ continue;
1395
+ }
1396
+ const key = findNearestBunPackageKey(pkg.rootScope, name, hasRootPackage);
1397
+ // An optional peer the root lockfile resolves is kept, in range or
1398
+ // not, since the package loads that copy in the workspace.
1399
+ if (key) {
1400
+ const dependency = createPackage(key, extractPackageDependencies(pkg.tuple)?.[depType]?.[name]);
1401
+ const bundle = pkg.bundle &&
1402
+ isNestedUnder(dependency.rootScope, pkg.bundle.rootScope)
1403
+ ? pkg.bundle
1404
+ : dependency.dependencies?.bundled &&
1405
+ isNestedUnder(dependency.rootScope, pkg.rootScope)
1406
+ ? { rootScope: pkg.rootScope, path: pkg.path }
1407
+ : undefined;
1408
+ if (bundle) {
1409
+ placeBundled(bundle, dependency);
1410
+ }
1411
+ else {
1412
+ place(pkg.path, name, dependency);
1413
+ }
1414
+ }
1415
+ else if (depType !== 'optionalDependencies' &&
1416
+ depType !== 'peerDependencies') {
1417
+ throw new Error(`Pruned lock file creation failed. ${name}, a dependency of ${pkg.resolution}, was not found in the root lock file.`);
1418
+ }
1419
+ }
1420
+ }
1421
+ }
1422
+ const placedNames = new Set([...placed.values()].map(({ path }) => path[path.length - 1]));
1423
+ const rootUnresolved = unresolvedRootDependencies
1424
+ .filter((name) => placedNames.has(name))
1425
+ .sort(compareStrings);
1426
+ if (rootUnresolved.length) {
1427
+ rootWorkspace.unresolved = rootUnresolved;
1428
+ }
1429
+ const workspace = {
1430
+ ...(packageJson.name && { name: packageJson.name }),
1431
+ ...sortDependencyGroups(rootWorkspace),
1432
+ };
1433
+ const overrides = getPrunedOverrides(rootLockFile.overrides, packageJson);
1434
+ const trustedDependencies = getPrunedTrustedDependencies(packageJson.trustedDependencies, rootLockFile.trustedDependencies, new Set([...placed.values()].map(({ resolution }) => getCachedSpecInfo(resolution).name)));
1435
+ const patchedDependencies = getPrunedPatchedDependencies(rootLockFile.patchedDependencies, new Set([...placed.values()].map(({ resolution }) => resolution)));
1436
+ const packages = [...placed.values()]
1437
+ .sort(comparePrunedPackages)
1438
+ .map(({ path, tuple }) => ` ${JSON.stringify(path.join('/'))}: ${formatInlineBunLockfileValue(keepPlacedUnresolved(tuple, placedNames))},`);
1439
+ const lines = ['{', ` "lockfileVersion": ${rootLockFile.lockfileVersion},`];
1440
+ if (rootLockFile.configVersion !== undefined) {
1441
+ lines.push(` "configVersion": ${rootLockFile.configVersion},`);
1442
+ }
1443
+ lines.push(` "workspaces": ${formatBunLockfileValue({ '': workspace }, ' ')},`);
1444
+ if (trustedDependencies) {
1445
+ lines.push(` "trustedDependencies": ${formatBunLockfileValue(trustedDependencies, ' ')},`);
1446
+ }
1447
+ if (patchedDependencies) {
1448
+ lines.push(` "patchedDependencies": ${formatBunLockfileValue(patchedDependencies, ' ')},`);
1449
+ }
1450
+ if (overrides) {
1451
+ lines.push(` "overrides": ${formatBunLockfileValue(overrides, ' ')},`);
1452
+ }
1453
+ lines.push(packages.length
1454
+ ? [' "packages": {', packages.join('\n\n'), ' }'].join('\n')
1455
+ : ' "packages": {}', '}', '');
1456
+ return lines.join('\n');
1457
+ }
1458
+ // A scoped name (`@scope/name`) is one segment.
1459
+ function splitBunPackageKey(key) {
1460
+ const parts = key.split('/');
1461
+ const segments = [];
1462
+ for (let i = 0; i < parts.length; i++) {
1463
+ segments.push(parts[i].startsWith('@') && i + 1 < parts.length
1464
+ ? `${parts[i]}/${parts[++i]}`
1465
+ : parts[i]);
1466
+ }
1467
+ return segments;
1468
+ }
1469
+ function isNestedUnder(key, scope) {
1470
+ return (key.length > scope.length && scope.every((segment, i) => key[i] === segment));
1471
+ }
1472
+ // A bun.lock key is the package's path in the hoisted tree (`a/b` is `b` nested
1473
+ // under `a`), and a dependency resolves to the nearest key on its dependent's
1474
+ // path. A workspace's scope is its name, so `<workspace name>/<name>` comes first.
1475
+ function findNearestBunPackageKey(scope, name, hasKey) {
1476
+ for (let depth = scope.length; depth >= 0; depth--) {
1477
+ const key = [...scope.slice(0, depth), name].join('/');
1478
+ if (hasKey(key)) {
1479
+ return key;
1480
+ }
1481
+ }
1482
+ }
1483
+ /**
1484
+ * The root lockfile key for a dependency of the pruned manifest: the app's own
1485
+ * resolution when its workspace entry declares the spec (an override can
1486
+ * install outside the range). A git or tarball spec takes the key that
1487
+ * resolves to it exactly, if any, since the app's nearest key can hold another
1488
+ * copy.
1489
+ * Otherwise the app's resolution when it matches the spec, or the shallowest
1490
+ * matching key, since a dependency taken from a workspace library can resolve
1491
+ * under that library's scope. A local package matches by source.
1492
+ */
1493
+ function findManifestDependencyKey(packages, localSources, appScope, name, spec, declaredByApp) {
1494
+ const local = getLocalSpecSource(spec);
1495
+ const matches = (key) => {
1496
+ if (!local) {
1497
+ return resolvesToSpec(packages[key], spec);
1498
+ }
1499
+ const source = localSources.get(key);
1500
+ return (source?.path === local.path &&
1501
+ (source.kind === 'link') === (local.protocol === 'link'));
1502
+ };
1503
+ const key = findNearestBunPackageKey(appScope, name, (candidate) => Object.prototype.hasOwnProperty.call(packages, candidate));
1504
+ if (key && declaredByApp) {
1505
+ return key;
1506
+ }
1507
+ if (!local && !(0, semver_1.validRange)(spec)) {
1508
+ const resolvesExactly = (candidate) => typeof packages[candidate]?.[0] === 'string' &&
1509
+ getCachedSpecInfo(packages[candidate][0]).version === spec;
1510
+ const exact = findNearestBunPackageKey(appScope, name, resolvesExactly) ??
1511
+ findShallowestBunPackageKey(packages, name, resolvesExactly);
1512
+ if (exact) {
1513
+ return exact;
1514
+ }
1515
+ }
1516
+ if (key && matches(key)) {
1517
+ return key;
1518
+ }
1519
+ return findShallowestBunPackageKey(packages, name, matches);
1520
+ }
1521
+ function findShallowestBunPackageKey(packages, name, matches) {
1522
+ let match;
1523
+ for (const candidate of Object.keys(packages)) {
1524
+ const segments = splitBunPackageKey(candidate);
1525
+ if (segments[segments.length - 1] === name &&
1526
+ (!match || segments.length < match.length) &&
1527
+ matches(candidate)) {
1528
+ match = segments;
1529
+ }
1530
+ }
1531
+ return match?.join('/');
1532
+ }
1533
+ // The workspace source a relocated `file:`/`link:` spec of the pruned manifest
1534
+ // names.
1535
+ function getLocalSpecSource(spec) {
1536
+ const protocol = spec.startsWith('file:')
1537
+ ? 'file'
1538
+ : spec.startsWith('link:')
1539
+ ? 'link'
1540
+ : undefined;
1541
+ if (!protocol) {
1542
+ return undefined;
1543
+ }
1544
+ return {
1545
+ protocol,
1546
+ path: normalizeBunLocalPath((0, pruned_output_1.uncontainLocalPathSpec)(spec).slice(protocol.length + 1)),
1547
+ };
1548
+ }
1549
+ /**
1550
+ * A local package's resolution once its source ships under
1551
+ * `local_path_modules/`, which Bun records as it would for the output. A
1552
+ * tarball's path is relative to its dependent, so it is the path the
1553
+ * dependent's shipped spec declares. A source the output cannot ship keeps
1554
+ * its resolution.
1555
+ */
1556
+ function getShippedLocalResolution(resolution, source, shippedSpec) {
1557
+ const { name } = getCachedSpecInfo(resolution);
1558
+ if (source.kind === 'tarball') {
1559
+ return shippedSpec?.startsWith('file:')
1560
+ ? `${name}@${normalizeBunLocalPath(shippedSpec.slice('file:'.length))}`
1561
+ : resolution;
1562
+ }
1563
+ const relocation = (0, pruned_output_1.relocatePrunedLocalPathSpec)(`file:${source.path}`, '', '');
1564
+ if (relocation.reason) {
1565
+ return resolution;
1566
+ }
1567
+ const shippedPath = relocation.spec.slice('file:'.length);
1568
+ return source.kind === 'link'
1569
+ ? `${name}@link:./${shippedPath}`
1570
+ : `${name}@file:${shippedPath}`;
1571
+ }
1572
+ // A workspace entry keeps its `catalog:` specs as written, and the lockfile
1573
+ // records the catalogs the install resolved them against.
1574
+ function resolveLockfileCatalog(lockFile, name, spec) {
1575
+ if (!spec.startsWith('catalog:')) {
1576
+ return spec;
1577
+ }
1578
+ const catalogName = spec.slice('catalog:'.length);
1579
+ return catalogName
1580
+ ? lockFile.catalogs?.[catalogName]?.[name]
1581
+ : lockFile.catalog?.[name];
1582
+ }
1583
+ /**
1584
+ * The spec a pruned output declares for a dependency that an override or
1585
+ * resolution installed outside its declared range, or in place of its local
1586
+ * path. The output ships no overrides, and Bun 1.4.4 re-resolves a required
1587
+ * dependency of the root manifest whose locked registry version is outside its
1588
+ * range (1.4.3 keeps it). Bun checks no other resolution against the range, so
1589
+ * an optional one keeps the declared spec, unless that spec is a local path
1590
+ * the output ships no copy of.
1591
+ */
1592
+ function getOverriddenVersionSpec(tuple, spec, isOptional) {
1593
+ if (!getLocalSpecSource(spec) &&
1594
+ (isOptional || resolvesToSpec(tuple, spec))) {
1595
+ return undefined;
1596
+ }
1597
+ const { name, version, protocol } = getCachedSpecInfo(tuple[0]);
1598
+ if (protocol !== 'npm' || !(0, semver_1.valid)(version)) {
1599
+ return undefined;
1600
+ }
1601
+ return spec.startsWith('npm:') ? `npm:${name}@${version}` : version;
1602
+ }
1603
+ // Bun lists an unresolved optional dependency only while the tree holds a
1604
+ // package of that name, which loading would otherwise resolve it to.
1605
+ function keepPlacedUnresolved(tuple, placedNames) {
1606
+ const meta = extractPackageDependencies(tuple);
1607
+ if (!meta?.unresolved) {
1608
+ return tuple;
1609
+ }
1610
+ const unresolved = meta.unresolved.filter((name) => placedNames.has(name));
1611
+ if (unresolved.length === meta.unresolved.length) {
1612
+ return tuple;
1613
+ }
1614
+ const { unresolved: _, ...rest } = meta;
1615
+ const kept = unresolved.length ? { ...meta, unresolved } : rest;
1616
+ return tuple.map((value) => (value === meta ? kept : value));
1617
+ }
1618
+ // Only a semver range is checked: a git, tarball or tag spec trusts the
1619
+ // lockfile's resolution.
1620
+ function resolvesToSpec(tuple, spec) {
1621
+ if (typeof tuple?.[0] !== 'string') {
1622
+ return false;
1623
+ }
1624
+ let range = spec;
1625
+ let aliasedName;
1626
+ if (spec.startsWith('npm:')) {
1627
+ const versionAt = spec.lastIndexOf('@');
1628
+ aliasedName = versionAt > 4 ? spec.slice(4, versionAt) : spec.slice(4);
1629
+ range = versionAt > 4 ? spec.slice(versionAt + 1) : '*';
1630
+ }
1631
+ if (!(0, semver_1.validRange)(range)) {
1632
+ return true;
1633
+ }
1634
+ const { name, version } = getCachedSpecInfo(tuple[0]);
1635
+ return ((aliasedName === undefined || name === aliasedName) &&
1636
+ (0, semver_1.satisfies)(version, range));
1637
+ }
1638
+ // Bun records the manifest's trusted names that are installed. Bun picks its
1639
+ // own order, which a frozen install does not check, so this keeps the
1640
+ // manifest's. An empty manifest list is `[]` in a Bun 1.4.4 lockfile and
1641
+ // absent in earlier ones, so it follows the root lockfile.
1642
+ function getPrunedTrustedDependencies(declared, rootTrusted, installed) {
1643
+ if (!declared) {
1644
+ return undefined;
1645
+ }
1646
+ if (!declared.length) {
1647
+ return rootTrusted?.length === 0 ? [] : undefined;
1648
+ }
1649
+ const kept = declared.filter((name) => installed.has(name));
1650
+ return kept.length ? kept : undefined;
1651
+ }
1652
+ /**
1653
+ * The `.patch` files a pruned Bun output ships for the patches its bun.lock
1654
+ * keeps. Bun applies the patches the manifest declares, so the same entries
1655
+ * replace any `patchedDependencies` the manifest inherited.
1656
+ */
1657
+ function getPrunedBunPatchArtifacts(workspaceRootPath, lockFileContent, packageJson) {
1658
+ delete packageJson.patchedDependencies;
1659
+ const rootPackageJsonPath = (0, node_path_1.join)(workspaceRootPath, 'package.json');
1660
+ const keys = getBunLockfilePatchKeys(lockFileContent);
1661
+ if (!keys.length || !(0, node_fs_1.existsSync)(rootPackageJsonPath)) {
1662
+ return [];
1663
+ }
1664
+ const rootPatches = (0, fileutils_1.readJsonFile)(rootPackageJsonPath).patchedDependencies ?? {};
1665
+ const scoped = Object.fromEntries(keys.filter((key) => rootPatches[key]).map((key) => [key, rootPatches[key]]));
1666
+ if (!Object.keys(scoped).length) {
1667
+ return [];
1668
+ }
1669
+ packageJson.patchedDependencies = (0, pruned_output_1.normalizePrunedPatchedDependencies)(scoped);
1670
+ return (0, pruned_output_1.getPrunedPatchFiles)(workspaceRootPath, scoped);
1671
+ }
1672
+ /**
1673
+ * The local packages a pruned bun.lock installs, which the output ships under
1674
+ * `local_path_modules/` (see `getLocalPathArtifacts`). Copied workspace modules
1675
+ * ship through copy-workspace-modules instead.
1676
+ */
1677
+ function getPrunedBunLocalPathTargets(lockFileContent) {
1678
+ if (!lockFileContent) {
1679
+ return [];
1680
+ }
1681
+ const lockFile = parseBunLockFile(lockFileContent);
1682
+ const targets = [];
1683
+ for (const [key, source] of getBunLocalPathSources(lockFile)) {
1684
+ if (!(0, pruned_output_1.isUnderWorkspaceModules)(source.path)) {
1685
+ targets.push({
1686
+ kind: source.kind === 'tarball' ? 'file' : 'directory',
1687
+ shippedPath: source.path,
1688
+ origin: lockFile.packages[key][0],
1689
+ });
1690
+ }
1691
+ }
1692
+ return targets;
1693
+ }
1694
+ /**
1695
+ * Fails the pruned build when a `link:` package of the pruned bun.lock requires
1696
+ * a dependency the app does not install. Bun installs no dependencies of a
1697
+ * link, which loads them from the install root.
1698
+ */
1699
+ function validatePrunedBunLocalPathClosure(packageJson, workspaceRootPath, lockFileContent) {
1700
+ if (!lockFileContent) {
1701
+ return;
1702
+ }
1703
+ const lockFile = parseBunLockFile(lockFileContent);
1704
+ const targets = new Map();
1705
+ for (const source of getBunLocalPathSources(lockFile).values()) {
1706
+ if (source.kind === 'link') {
1707
+ targets.set((0, pruned_output_1.uncontainLocalPath)(source.path), 'link');
1708
+ }
1709
+ }
1710
+ (0, pruned_output_1.validateLocalPathClosures)(packageJson, workspaceRootPath, targets);
1711
+ }
1712
+ /**
1713
+ * Hashes the patch files the root package.json declares, keyed by the declared
1714
+ * path. bun.lock records only the path, so these hashes are what change when a
1715
+ * patch file does. A missing file gets its own hash, apart from an unpatched
1716
+ * package's.
1717
+ */
1718
+ function getBunPatchFileHashes(workspaceRootPath) {
1719
+ const hashes = new Map();
1720
+ const rootPackageJsonPath = (0, node_path_1.join)(workspaceRootPath, 'package.json');
1721
+ if (!(0, node_fs_1.existsSync)(rootPackageJsonPath)) {
1722
+ return hashes;
1723
+ }
1724
+ const { patchedDependencies } = (0, fileutils_1.readJsonFile)(rootPackageJsonPath);
1725
+ for (const patchPath of Object.values(patchedDependencies ?? {})) {
1726
+ if (typeof patchPath !== 'string' || hashes.has(patchPath)) {
1727
+ continue;
1728
+ }
1729
+ const source = (0, node_path_1.isAbsolute)(patchPath)
1730
+ ? patchPath
1731
+ : (0, node_path_1.join)(workspaceRootPath, patchPath);
1732
+ hashes.set(patchPath, (0, fileutils_1.fileExists)(source)
1733
+ ? (0, file_hasher_1.hashFile)(source)
1734
+ : (0, file_hasher_1.hashArray)([`missing patch ${patchPath}`]));
1735
+ }
1736
+ return hashes;
1737
+ }
1738
+ function getBunLockfilePatchKeys(lockFileContent) {
1739
+ if (!lockFileContent) {
1740
+ return [];
1741
+ }
1742
+ const { patchedDependencies } = parseBunLockFile(lockFileContent);
1743
+ return Object.keys(patchedDependencies ?? {});
1744
+ }
1745
+ // Bun records only the patches of installed packages, keyed by `name@version`.
1746
+ // They point at the paths the output ships the patch files under.
1747
+ function getPrunedPatchedDependencies(patchedDependencies, installed) {
1748
+ const kept = Object.fromEntries(Object.entries(patchedDependencies ?? {}).filter(([key]) => installed.has(key)));
1749
+ return Object.keys(kept).length
1750
+ ? (0, pruned_output_1.normalizePrunedPatchedDependencies)(kept)
1751
+ : undefined;
1752
+ }
1753
+ // Bun reads `overrides` when the manifest has it and `resolutions` otherwise,
1754
+ // stripping a `**/` prefix. A frozen install fails from Bun 1.4 when the
1755
+ // lockfile's overrides differ from the manifest's, so only the root entries the
1756
+ // pruned manifest still declares are kept.
1757
+ function getPrunedOverrides(overrides, packageJson) {
1758
+ const declared = packageJson.overrides ?? packageJson.resolutions;
1759
+ if (!overrides || !declared) {
1760
+ return undefined;
1761
+ }
1762
+ const declaredNames = new Set(Object.keys(declared).map((key) => key.startsWith('**/') ? key.slice(3) : key));
1763
+ const kept = Object.entries(overrides).filter(([name]) => declaredNames.has(name));
1764
+ return kept.length ? Object.fromEntries(kept) : undefined;
1765
+ }
1766
+ function sortDependencyGroups(groups) {
1767
+ const sorted = {};
1768
+ for (const depType of DEPENDENCY_TYPES) {
1769
+ if (groups[depType]) {
1770
+ sorted[depType] = Object.fromEntries(Object.entries(groups[depType]).sort(([a], [b]) => compareStrings(a, b)));
1771
+ }
1772
+ }
1773
+ if (groups.optionalPeers) {
1774
+ sorted.optionalPeers = groups.optionalPeers;
1775
+ }
1776
+ if (groups.unresolved) {
1777
+ sorted.unresolved = groups.unresolved;
1778
+ }
1779
+ return sorted;
1780
+ }
1781
+ // Bun's order: by depth, then by the dependent's path, then by name.
1782
+ function comparePrunedPackages(a, b) {
1783
+ return (a.path.length - b.path.length ||
1784
+ compareStrings(a.path.slice(0, -1).join('/'), b.path.slice(0, -1).join('/')) ||
1785
+ compareStrings(a.path[a.path.length - 1], b.path[b.path.length - 1]));
1786
+ }
1787
+ function compareStrings(a, b) {
1788
+ return a < b ? -1 : a > b ? 1 : 0;
1789
+ }
1790
+ // Bun's multi-line layout: two-space indent and a comma after every entry.
1791
+ function formatBunLockfileValue(value, indent) {
1792
+ const inner = `${indent} `;
1793
+ if (Array.isArray(value)) {
1794
+ return value.length
1795
+ ? `[\n${value
1796
+ .map((item) => `${inner}${formatBunLockfileValue(item, inner)},\n`)
1797
+ .join('')}${indent}]`
1798
+ : '[]';
1799
+ }
1800
+ if (value && typeof value === 'object') {
1801
+ const entries = Object.entries(value);
1802
+ return entries.length
1803
+ ? `{\n${entries
1804
+ .map(([key, item]) => `${inner}${JSON.stringify(key)}: ${formatBunLockfileValue(item, inner)},\n`)
1805
+ .join('')}${indent}}`
1806
+ : '{}';
1807
+ }
1808
+ return JSON.stringify(value);
1809
+ }
1810
+ // Bun's single-line layout for a `packages` entry.
1811
+ function formatInlineBunLockfileValue(value) {
1812
+ if (Array.isArray(value)) {
1813
+ return `[${value.map(formatInlineBunLockfileValue).join(', ')}]`;
1814
+ }
1815
+ if (value && typeof value === 'object') {
1816
+ const entries = Object.entries(value);
1817
+ return entries.length
1818
+ ? `{ ${entries
1819
+ .map(([key, item]) => `${JSON.stringify(key)}: ${formatInlineBunLockfileValue(item)}`)
1820
+ .join(', ')} }`
1821
+ : '{}';
1822
+ }
1823
+ return JSON.stringify(value);
1824
+ }