nx 24.1.0-beta.0 → 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 (116) hide show
  1. package/dist/bin/init-local.js +2 -4
  2. package/dist/bin/nx-cloud.js +2 -1
  3. package/dist/bin/nx.js +12 -14
  4. package/dist/bin/run-executor.js +5 -0
  5. package/dist/src/adapter/compat.d.ts +1 -1
  6. package/dist/src/adapter/compat.js +1 -0
  7. package/dist/src/command-line/completion/scripts/bash.sh +9 -2
  8. package/dist/src/command-line/completion/scripts/fish.fish +10 -2
  9. package/dist/src/command-line/completion/scripts/zsh.zsh +8 -2
  10. package/dist/src/command-line/completion/scripts.js +18 -8
  11. package/dist/src/command-line/conformance/command-object.d.ts +3 -0
  12. package/dist/src/command-line/conformance/command-object.js +66 -0
  13. package/dist/src/command-line/generate/generate.js +2 -4
  14. package/dist/src/command-line/generate/generator-utils.d.ts +1 -0
  15. package/dist/src/command-line/generate/generator-utils.js +9 -0
  16. package/dist/src/command-line/import/import.js +26 -2
  17. package/dist/src/command-line/import/utils/ai-output.d.ts +9 -1
  18. package/dist/src/command-line/import/utils/ai-output.js +20 -1
  19. package/dist/src/command-line/nx-commands.d.ts +1 -1
  20. package/dist/src/command-line/nx-commands.js +82 -132
  21. package/dist/src/command-line/release/command-object.d.ts +1 -0
  22. package/dist/src/command-line/release/command-object.js +4 -0
  23. package/dist/src/command-line/release/release.js +6 -4
  24. package/dist/src/command-line/release/utils/repository-git-tags.js +3 -3
  25. package/dist/src/command-line/release/utils/resolve-nx-json-error-message.js +2 -24
  26. package/dist/src/command-line/report/report.js +1 -1
  27. package/dist/src/command-line/reset/reset.js +51 -2
  28. package/dist/src/config/nx-json.d.ts +117 -0
  29. package/dist/src/config/workspace-json-project-json.d.ts +6 -7
  30. package/dist/src/daemon/client/daemon-environment.js +15 -0
  31. package/dist/src/daemon/server/project-graph-incremental-recomputation.js +13 -20
  32. package/dist/src/devkit-exports.d.ts +1 -1
  33. package/dist/src/devkit-internals.d.ts +14 -7
  34. package/dist/src/devkit-internals.js +29 -4
  35. package/dist/src/executors/run-commands/run-commands.impl.d.ts +1 -1
  36. package/dist/src/executors/run-commands/run-commands.impl.js +35 -13
  37. package/dist/src/generators/utils/glob.js +3 -3
  38. package/dist/src/hasher/hash-task.d.ts +3 -1
  39. package/dist/src/hasher/hash-task.js +3 -2
  40. package/dist/src/migrations/update-24-1-0/replace-powerpack-conformance.d.ts +4 -0
  41. package/dist/src/migrations/update-24-1-0/replace-powerpack-conformance.js +117 -0
  42. package/dist/src/migrations/update-24-1-0/replace-powerpack-conformance.md +38 -0
  43. package/dist/src/native/index.d.ts +6 -8
  44. package/dist/src/native/index.js +18 -0
  45. package/dist/src/native/native-bindings.js +1 -0
  46. package/dist/src/native/nx.wasm32-wasi.debug.wasm +0 -0
  47. package/dist/src/native/nx.wasm32-wasi.wasm +0 -0
  48. package/dist/src/native/transform-objects.d.ts +2 -0
  49. package/dist/src/native/transform-objects.js +15 -0
  50. package/dist/src/plugins/js/index.js +24 -9
  51. package/dist/src/plugins/js/lock-file/bun-parser.d.ts +75 -4
  52. package/dist/src/plugins/js/lock-file/bun-parser.js +976 -142
  53. package/dist/src/plugins/js/lock-file/lock-file-names.d.ts +6 -0
  54. package/dist/src/plugins/js/lock-file/lock-file-names.js +16 -0
  55. package/dist/src/plugins/js/lock-file/lock-file.d.ts +33 -14
  56. package/dist/src/plugins/js/lock-file/lock-file.js +213 -74
  57. package/dist/src/plugins/js/lock-file/npm-parser.d.ts +1 -0
  58. package/dist/src/plugins/js/lock-file/npm-parser.js +66 -2
  59. package/dist/src/plugins/js/lock-file/pnpm-parser.d.ts +5 -1
  60. package/dist/src/plugins/js/lock-file/pnpm-parser.js +107 -54
  61. package/dist/src/plugins/js/lock-file/pruned-output.d.ts +52 -10
  62. package/dist/src/plugins/js/lock-file/pruned-output.js +132 -66
  63. package/dist/src/plugins/js/lock-file/utils/local-path-hashes.d.ts +27 -0
  64. package/dist/src/plugins/js/lock-file/utils/local-path-hashes.js +155 -0
  65. package/dist/src/plugins/js/lock-file/utils/package-json.d.ts +1 -1
  66. package/dist/src/plugins/js/lock-file/utils/package-json.js +2 -1
  67. package/dist/src/plugins/js/package-json/create-package-json.d.ts +1 -0
  68. package/dist/src/plugins/js/package-json/create-package-json.js +197 -8
  69. package/dist/src/plugins/js/project-graph/affected/npm-packages.js +50 -2
  70. package/dist/src/plugins/js/project-graph/build-dependencies/build-dependencies.d.ts +1 -1
  71. package/dist/src/plugins/js/project-graph/build-dependencies/build-dependencies.js +2 -2
  72. package/dist/src/plugins/js/project-graph/build-dependencies/explicit-package-json-dependencies.js +16 -9
  73. package/dist/src/plugins/js/project-graph/build-dependencies/explicit-project-dependencies.js +17 -28
  74. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.d.ts +52 -1
  75. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.js +336 -28
  76. package/dist/src/plugins/js/utils/register.js +13 -6
  77. package/dist/src/project-graph/build-project-graph.js +5 -2
  78. package/dist/src/project-graph/error-types.d.ts +2 -2
  79. package/dist/src/project-graph/error-types.js +2 -2
  80. package/dist/src/project-graph/nx-deps-cache.d.ts +3 -2
  81. package/dist/src/project-graph/nx-deps-cache.js +8 -2
  82. package/dist/src/project-graph/utils/project-graph-paths.d.ts +8 -0
  83. package/dist/src/project-graph/utils/project-graph-paths.js +170 -0
  84. package/dist/src/tasks-runner/batch/run-batch.js +3 -13
  85. package/dist/src/tasks-runner/cache.js +19 -18
  86. package/dist/src/tasks-runner/init-tasks-runner.js +23 -17
  87. package/dist/src/tasks-runner/run-command.js +6 -3
  88. package/dist/src/tasks-runner/task-orchestrator.d.ts +1 -0
  89. package/dist/src/tasks-runner/task-orchestrator.js +29 -4
  90. package/dist/src/tasks-runner/tasks-schedule.js +1 -1
  91. package/dist/src/tasks-runner/utils.d.ts +2 -1
  92. package/dist/src/tasks-runner/utils.js +2 -1
  93. package/dist/src/utils/child-process.js +2 -1
  94. package/dist/src/utils/find-matching-projects.js +7 -9
  95. package/dist/src/utils/find-workspace-root.js +2 -4
  96. package/dist/src/utils/git-utils.d.ts +5 -0
  97. package/dist/src/utils/git-utils.js +23 -1
  98. package/dist/src/utils/handle-import.js +14 -2
  99. package/dist/src/utils/installation-directory.d.ts +16 -0
  100. package/dist/src/utils/installation-directory.js +96 -2
  101. package/dist/src/utils/json.d.ts +7 -0
  102. package/dist/src/utils/json.js +32 -0
  103. package/dist/src/utils/nx-key.js +11 -8
  104. package/dist/src/utils/output.d.ts +5 -0
  105. package/dist/src/utils/output.js +11 -4
  106. package/dist/src/utils/owned-private-dir.d.ts +10 -0
  107. package/dist/src/utils/owned-private-dir.js +28 -0
  108. package/dist/src/utils/package-json.d.ts +7 -0
  109. package/dist/src/utils/package-json.js +9 -0
  110. package/dist/src/utils/require-nx-key.js +6 -4
  111. package/dist/src/utils/workspace-root.d.ts +12 -0
  112. package/dist/src/utils/workspace-root.js +56 -7
  113. package/migrations.json +6 -0
  114. package/package.json +15 -12
  115. package/schemas/nx-schema.json +75 -9
  116. package/schemas/project-schema.json +5 -0
@@ -5,19 +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");
27
+ const lock_file_names_1 = require("./lock-file-names");
28
+ const pruned_output_1 = require("./pruned-output");
15
29
  // Highest bun.lock version this parser has been verified against:
16
30
  // - 1: workspace packages are no longer listed with their dependencies
17
31
  // - 2: identical content, stricter validation in Bun's own reader
18
32
  // - 3: values in "overrides" may be objects holding rules scoped to a parent
19
33
  // package (`"parent": { "child": "1.0.0" }`) and keys may carry a version
20
- // selector (`"parent@1"`, `"child@<2"`). This parser never reads
34
+ // selector (`"parent@1"`, `"child@<2"`). The graph never reads
21
35
  // "overrides"; the resolved packages are listed in "packages" as before.
22
36
  // Newer versions are parsed on a best-effort basis instead of being rejected
23
37
  // outright.
@@ -28,8 +42,9 @@ const DEPENDENCY_TYPES = [
28
42
  'optionalDependencies',
29
43
  'peerDependencies',
30
44
  ];
31
- exports.BUN_LOCK_FILE = 'bun.lockb';
32
- exports.BUN_TEXT_LOCK_FILE = 'bun.lock';
45
+ var lock_file_names_2 = require("./lock-file-names");
46
+ Object.defineProperty(exports, "BUN_LOCK_FILE", { enumerable: true, get: function () { return lock_file_names_2.BUN_LOCK_FILE; } });
47
+ Object.defineProperty(exports, "BUN_TEXT_LOCK_FILE", { enumerable: true, get: function () { return lock_file_names_2.BUN_TEXT_LOCK_FILE; } });
33
48
  let currentLockFileHash;
34
49
  let cachedParsedLockFile;
35
50
  let cachedPackageIndex;
@@ -49,7 +64,7 @@ class BunLockfileParseError extends Error {
49
64
  }
50
65
  exports.BunLockfileParseError = BunLockfileParseError;
51
66
  function readBunLockFile(lockFilePath) {
52
- if (lockFilePath.endsWith(exports.BUN_TEXT_LOCK_FILE)) {
67
+ if (lockFilePath.endsWith(lock_file_names_1.BUN_TEXT_LOCK_FILE)) {
53
68
  return (0, node_fs_1.readFileSync)(lockFilePath, { encoding: 'utf-8' });
54
69
  }
55
70
  return (0, node_child_process_1.execSync)(`bun ${lockFilePath}`, {
@@ -124,12 +139,9 @@ function getProtocolFromResolvedSpec(resolvedSpec) {
124
139
  }
125
140
  function parseResolvedSpec(resolvedSpec) {
126
141
  // Handle different resolution formats:
127
- // - "package-name@npm:1.0.0"
128
- // - "@scope/package-name@npm:1.0.0"
129
142
  // - "package-name@github:user/repo#commit"
130
143
  // - "package-name@file:./path"
131
144
  // - "package-name@https://example.com/package.tgz"
132
- // - "alias-name@npm:actual-package@version" (ALIAS FORMAT)
133
145
  // Handle scoped packages properly - they have an extra @ at the beginning
134
146
  // Format: @scope/package@protocol:spec
135
147
  let name;
@@ -154,42 +166,22 @@ function parseResolvedSpec(resolvedSpec) {
154
166
  }
155
167
  // Parse protocol and spec
156
168
  const colonIndex = protocolAndSpec.indexOf(':');
157
- // 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
158
171
  if (colonIndex === -1) {
159
172
  // No protocol specified, treat as npm package with direct version
160
173
  return { name, version: protocolAndSpec };
161
174
  }
162
175
  const protocol = protocolAndSpec.substring(0, colonIndex);
163
176
  const spec = protocolAndSpec.substring(colonIndex + 1);
164
- if (protocol === 'npm') {
165
- // For npm protocol, spec should always be in format: package@version
166
- // Examples:
167
- // - Regular: "package@npm:package@1.0.0" -> version: "1.0.0"
168
- // - Alias: "alias@npm:real-package@1.0.0" -> version: "npm:real-package@1.0.0"
169
- // Extract the package name and version from the spec
170
- const atIndex = spec.lastIndexOf('@');
171
- if (atIndex === -1) {
172
- // Malformed spec, return as-is
173
- return { name, version: spec };
174
- }
175
- const specPackageName = spec.substring(0, atIndex);
176
- const specVersion = spec.substring(atIndex + 1);
177
- if (specPackageName === name) {
178
- // Regular npm package: "package@npm:package@1.0.0" -> version: "1.0.0"
179
- return { name, version: specVersion };
180
- }
181
- else {
182
- // Alias package: "alias@npm:real-package@1.0.0" -> version: "npm:real-package@1.0.0"
183
- return { name, version: `npm:${spec}` };
184
- }
185
- }
186
- else if (protocol === 'workspace') {
177
+ if (protocol === 'workspace') {
187
178
  // Workspace dependencies use the workspace path as version
188
179
  return { name, version: `workspace:${spec}` };
189
180
  }
190
- else if (protocol === 'github' || protocol === 'git') {
181
+ else if (protocol === 'github' || protocol.startsWith('git+')) {
191
182
  // Extract commit hash from GitHub/Git reference
192
- // 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:)
193
185
  const gitMatch = spec.match(/^(.+?)#(.+)$/);
194
186
  if (gitMatch) {
195
187
  const [, repo, commit] = gitMatch;
@@ -212,17 +204,10 @@ function parseResolvedSpec(resolvedSpec) {
212
204
  return { name, version: resolvedSpec };
213
205
  }
214
206
  }
215
- function calculatePackageHash(packageData, lockFile, name, version) {
207
+ function calculatePackageHash(packageData) {
216
208
  const [resolvedSpec, tarballUrl, metadata, hash] = packageData;
217
209
  // For NPM packages (4 elements), use the integrity hash
218
210
  if (packageData.length === 4 && hash && typeof hash === 'string') {
219
- // Use better hash from manifests if available
220
- if (lockFile.manifests && lockFile.manifests[`${name}@${version}`]) {
221
- const manifest = lockFile.manifests[`${name}@${version}`];
222
- if (manifest.dist && manifest.dist.shasum) {
223
- return manifest.dist.shasum;
224
- }
225
- }
226
211
  return hash;
227
212
  }
228
213
  // For other package types, calculate hash from available data
@@ -235,6 +220,9 @@ function calculatePackageHash(packageData, lockFile, name, version) {
235
220
  hashData.push(hash);
236
221
  return (0, file_hasher_1.hashArray)(hashData);
237
222
  }
223
+ function withPatchHash(hash, patchHash) {
224
+ return patchHash === undefined ? hash : (0, file_hasher_1.hashArray)([hash, patchHash]);
225
+ }
238
226
  /**
239
227
  * Determines if a package is an alias by comparing the package key with the resolved spec name
240
228
  * In Bun lockfiles, aliases are identified when the package key differs from the resolved package name
@@ -252,7 +240,6 @@ function buildPackageIndex(lockFile) {
252
240
  const workspaceNames = new Set();
253
241
  const workspacePaths = new Set();
254
242
  const packagesWithWorkspaceVariants = new Set();
255
- const patchedPackages = new Set();
256
243
  // Collect workspace paths
257
244
  if (lockFile.workspaces) {
258
245
  for (const workspacePath of Object.keys(lockFile.workspaces)) {
@@ -261,19 +248,9 @@ function buildPackageIndex(lockFile) {
261
248
  }
262
249
  }
263
250
  }
264
- // Collect workspace package names from workspacePackages field
265
- if (lockFile.workspacePackages) {
266
- for (const packageInfo of Object.values(lockFile.workspacePackages)) {
267
- workspaceNames.add(packageInfo.name);
268
- }
269
- }
270
- // Collect patched package names
271
- if (lockFile.patches) {
272
- for (const packageName of Object.keys(lockFile.patches)) {
273
- patchedPackages.add(packageName);
274
- }
275
- }
276
- // 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.
277
254
  if (lockFile.workspaces) {
278
255
  for (const workspace of Object.values(lockFile.workspaces)) {
279
256
  const allDeps = {
@@ -283,8 +260,7 @@ function buildPackageIndex(lockFile) {
283
260
  ...workspace.peerDependencies,
284
261
  };
285
262
  for (const [depName, depVersion] of Object.entries(allDeps)) {
286
- if (depVersion.startsWith('workspace:') ||
287
- depVersion.startsWith('file:')) {
263
+ if (depVersion.startsWith('workspace:')) {
288
264
  workspaceNames.add(depName);
289
265
  }
290
266
  }
@@ -305,7 +281,7 @@ function buildPackageIndex(lockFile) {
305
281
  continue;
306
282
  }
307
283
  // Track workspace packages from packages section
308
- if (protocol === 'workspace' || protocol === 'file') {
284
+ if (protocol === 'workspace') {
309
285
  workspaceNames.add(name);
310
286
  }
311
287
  // Check if this is a workspace-specific variant (e.g., "@quz/pkg1/lodash")
@@ -331,7 +307,7 @@ function buildPackageIndex(lockFile) {
331
307
  byName.set(name, entries);
332
308
  }
333
309
  // Calculate hash once
334
- const hash = calculatePackageHash(packageData, lockFile, name, version);
310
+ const hash = calculatePackageHash(packageData);
335
311
  entries.push({ version, packageKey, hash });
336
312
  }
337
313
  }
@@ -340,9 +316,100 @@ function buildPackageIndex(lockFile) {
340
316
  workspaceNames,
341
317
  workspacePaths,
342
318
  packagesWithWorkspaceVariants,
343
- patchedPackages,
319
+ localPathSources: getBunLocalPathSources(lockFile),
344
320
  };
345
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
+ }
346
413
  function parseLockFile(lockFileContent, lockFileHash) {
347
414
  if (currentLockFileHash === lockFileHash &&
348
415
  cachedParsedLockFile &&
@@ -351,10 +418,7 @@ function parseLockFile(lockFileContent, lockFileHash) {
351
418
  }
352
419
  clearCache();
353
420
  try {
354
- const result = (0, json_1.parseJson)(lockFileContent, {
355
- allowTrailingComma: true,
356
- expectComments: true,
357
- });
421
+ const result = parseBunLockFile(lockFileContent);
358
422
  // Validate basic structure
359
423
  if (!result || typeof result !== 'object') {
360
424
  throw new Error('Lockfile root must be an object');
@@ -378,42 +442,6 @@ function parseLockFile(lockFileContent, lockFileHash) {
378
442
  if (!result.workspaces || typeof result.workspaces !== 'object') {
379
443
  throw new Error('Lockfile workspaces section must be an object');
380
444
  }
381
- // Validate optional sections
382
- if (result.patches && typeof result.patches !== 'object') {
383
- throw new Error('Lockfile patches section must be an object');
384
- }
385
- if (result.manifests && typeof result.manifests !== 'object') {
386
- throw new Error('Lockfile manifests section must be an object');
387
- }
388
- if (result.workspacePackages &&
389
- typeof result.workspacePackages !== 'object') {
390
- throw new Error('Lockfile workspacePackages section must be an object');
391
- }
392
- // Validate structure of patches entries
393
- if (result.patches) {
394
- for (const [packageName, patchInfo] of Object.entries(result.patches)) {
395
- if (!patchInfo || typeof patchInfo !== 'object') {
396
- throw new Error(`Invalid patch entry for package "${packageName}": must be an object`);
397
- }
398
- if (!patchInfo.path || typeof patchInfo.path !== 'string') {
399
- throw new Error(`Invalid patch entry for package "${packageName}": path must be a string`);
400
- }
401
- }
402
- }
403
- // Validate structure of workspace packages entries
404
- if (result.workspacePackages) {
405
- for (const [packageName, packageInfo] of Object.entries(result.workspacePackages)) {
406
- if (!packageInfo || typeof packageInfo !== 'object') {
407
- throw new Error(`Invalid workspace package entry for "${packageName}": must be an object`);
408
- }
409
- if (!packageInfo.name || typeof packageInfo.name !== 'string') {
410
- throw new Error(`Invalid workspace package entry for "${packageName}": name must be a string`);
411
- }
412
- if (!packageInfo.version || typeof packageInfo.version !== 'string') {
413
- throw new Error(`Invalid workspace package entry for "${packageName}": version must be a string`);
414
- }
415
- }
416
- }
417
445
  cachedParsedLockFile = result;
418
446
  currentLockFileHash = lockFileHash;
419
447
  // Build the optimized index
@@ -435,7 +463,12 @@ function parseLockFile(lockFileContent, lockFileHash) {
435
463
  }
436
464
  }
437
465
  // ===== MAIN EXPORT FUNCTIONS =====
438
- 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) {
439
472
  try {
440
473
  const { lockFile, index } = parseLockFile(lockFileContent, lockFileHash);
441
474
  const nodes = {};
@@ -443,9 +476,16 @@ function getBunTextLockfileNodes(lockFileContent, lockFileHash) {
443
476
  if (!lockFile.packages || Object.keys(lockFile.packages).length === 0) {
444
477
  return nodes;
445
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
+ }
446
486
  const packageEntries = Object.entries(lockFile.packages);
447
487
  for (const [packageKey, packageData] of packageEntries) {
448
- const result = processPackageEntry(packageKey, packageData, lockFile, index, keyMap, nodes, localPackageVersions);
488
+ const result = processPackageEntry(packageKey, packageData, lockFile, index, keyMap, nodes, localPackageVersions, patchHashes);
449
489
  if (result.shouldContinue) {
450
490
  continue;
451
491
  }
@@ -460,7 +500,80 @@ function getBunTextLockfileNodes(lockFileContent, lockFileHash) {
460
500
  throw new Error(`Failed to get Bun lockfile nodes: ${error.message}`);
461
501
  }
462
502
  }
463
- 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) {
464
577
  try {
465
578
  if (!Array.isArray(packageData) ||
466
579
  packageData.length < 1 ||
@@ -478,11 +591,10 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
478
591
  console.warn(`Lockfile contains unrecognized package format. Try regenerating the lockfile with 'bun install --force'.\nDebug: could not parse resolved spec '${resolvedSpec}'`);
479
592
  return { shouldContinue: true };
480
593
  }
481
- // O(1) lookups using index
482
- if (index.workspaceNames.has(name)) {
483
- return { shouldContinue: true };
484
- }
485
- 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)) {
486
598
  return { shouldContinue: true };
487
599
  }
488
600
  if (protocol === 'workspace') {
@@ -493,6 +605,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
493
605
  const aliasName = packageKey;
494
606
  const actualPackageName = name;
495
607
  const actualVersion = version;
608
+ const hash = withPatchHash(calculatePackageHash(packageData), patchHashes.get(`${actualPackageName}@${actualVersion}`));
496
609
  const aliasNodeKey = `npm:${aliasName}`;
497
610
  if (!keyMap.has(aliasNodeKey)) {
498
611
  const aliasNode = {
@@ -501,7 +614,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
501
614
  data: {
502
615
  version: `npm:${actualPackageName}@${actualVersion}`,
503
616
  packageName: aliasName,
504
- hash: calculatePackageHash(packageData, lockFile, aliasName, `npm:${actualPackageName}@${actualVersion}`),
617
+ hash,
505
618
  },
506
619
  };
507
620
  keyMap.set(aliasNodeKey, aliasNode);
@@ -515,7 +628,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
515
628
  data: {
516
629
  version: actualVersion,
517
630
  packageName: actualPackageName,
518
- hash: calculatePackageHash(packageData, lockFile, actualPackageName, actualVersion),
631
+ hash,
519
632
  },
520
633
  };
521
634
  keyMap.set(targetNodeKey, targetNode);
@@ -542,7 +655,7 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
542
655
  nodes[nodeKey] = keyMap.get(nodeKey);
543
656
  return { shouldContinue: false };
544
657
  }
545
- const nodeHash = calculatePackageHash(packageData, lockFile, name, version);
658
+ const nodeHash = withPatchHash(calculatePackageHash(packageData), patchHashes.get(`${name}@${version}`));
546
659
  const node = {
547
660
  type: 'npm',
548
661
  name: nodeKey,
@@ -562,10 +675,12 @@ function processPackageEntry(packageKey, packageData, lockFile, index, keyMap, n
562
675
  return { shouldContinue: true };
563
676
  }
564
677
  }
565
- function isWorkspaceOrPatchedPackage(packageName, index, workspacePackages) {
566
- return (workspacePackages.has(packageName) ||
567
- index.workspaceNames.has(packageName) ||
568
- 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));
569
684
  }
570
685
  function resolveAliasTarget(versionSpec) {
571
686
  if (!versionSpec.startsWith('npm:'))
@@ -595,9 +710,12 @@ function processPackageToPackageDependencies(lockFile, index, ctx, workspacePack
595
710
  return dependencies;
596
711
  }
597
712
  function processPackageForDependencies(packageKey, packageData, lockFile, index, ctx, workspacePackages) {
598
- // O(1) checks using index
599
- if (index.workspaceNames.has(packageKey) ||
600
- 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) {
601
719
  return [];
602
720
  }
603
721
  if (!Array.isArray(packageData) || packageData.length < 1) {
@@ -611,9 +729,6 @@ function processPackageForDependencies(packageKey, packageData, lockFile, index,
611
729
  if (!sourcePackageName || !sourceVersion) {
612
730
  return [];
613
731
  }
614
- if (index.patchedPackages.has(sourcePackageName)) {
615
- return [];
616
- }
617
732
  const sourceNodeName = `npm:${sourcePackageName}@${sourceVersion}`;
618
733
  if (!ctx.externalNodes[sourceNodeName]) {
619
734
  return [];
@@ -630,6 +745,26 @@ function processPackageForDependencies(packageKey, packageData, lockFile, index,
630
745
  const depDependencies = processDependencyEntries(deps, packageKey, sourceNodeName, lockFile, index, ctx, workspacePackages);
631
746
  dependencies.push(...depDependencies);
632
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
+ }
633
768
  return dependencies;
634
769
  }
635
770
  function extractPackageDependencies(packageData) {
@@ -665,8 +800,10 @@ function processSingleDependency(packageName, versionSpec, sourcePackageKey, sou
665
800
  if (typeof packageName !== 'string' || typeof versionSpec !== 'string') {
666
801
  return null;
667
802
  }
668
- // O(1) check using index
669
- 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)) {
670
807
  return null;
671
808
  }
672
809
  if (versionSpec.startsWith('workspace:')) {
@@ -689,7 +826,7 @@ function processSingleDependency(packageName, versionSpec, sourcePackageKey, sou
689
826
  }
690
827
  else {
691
828
  // O(1) lookup using index instead of O(n) scan
692
- const resolvedVersion = findResolvedVersion(packageName, versionSpec, index, lockFile.manifests);
829
+ const resolvedVersion = findResolvedVersion(packageName, versionSpec, index);
693
830
  if (!resolvedVersion) {
694
831
  return null;
695
832
  }
@@ -738,6 +875,9 @@ function resolveTargetNodeName(targetPackageName, targetVersion, ctx) {
738
875
  // ===== HOISTING-RELATED FUNCTIONS =====
739
876
  function createHoistedNodes(packageVersions, lockFile, index, keyMap, nodes) {
740
877
  for (const [packageName, versions] of packageVersions.entries()) {
878
+ if (index.workspaceNames.has(packageName)) {
879
+ continue;
880
+ }
741
881
  const hoistedNodeKey = `npm:${packageName}`;
742
882
  if (shouldCreateHoistedNode(packageName, lockFile, index)) {
743
883
  const hoistedVersion = getHoistedVersion(packageName, versions, index);
@@ -862,36 +1002,22 @@ function getHoistedVersion(packageName, availableVersions, index) {
862
1002
  *
863
1003
  * O(1) lookup using pre-computed index instead of O(n) scan through all packages
864
1004
  */
865
- function findResolvedVersion(packageName, versionSpec, index, manifests) {
1005
+ function findResolvedVersion(packageName, versionSpec, index) {
866
1006
  // Resolution depends only on (packageName, versionSpec) for a given lockfile
867
- // (index and manifests are constant per parse), so memoize across edges.
1007
+ // (the index is constant per parse), so memoize across edges.
868
1008
  const cacheKey = `${packageName}\n${versionSpec}`;
869
1009
  const cached = resolvedVersionCache.get(cacheKey);
870
1010
  if (cached !== undefined) {
871
1011
  return cached;
872
1012
  }
873
- const resolved = computeResolvedVersion(packageName, versionSpec, index, manifests);
1013
+ const resolved = computeResolvedVersion(packageName, versionSpec, index);
874
1014
  resolvedVersionCache.set(cacheKey, resolved);
875
1015
  return resolved;
876
1016
  }
877
- function computeResolvedVersion(packageName, versionSpec, index, manifests) {
1017
+ function computeResolvedVersion(packageName, versionSpec, index) {
878
1018
  // O(1) lookup
879
1019
  const candidates = index.byName.get(packageName);
880
1020
  if (!candidates || candidates.length === 0) {
881
- // Try to find in manifests as fallback
882
- if (manifests) {
883
- const exactManifestKey = `${packageName}@${versionSpec}`;
884
- if (manifests[exactManifestKey]) {
885
- return versionSpec;
886
- }
887
- const manifestKey = Object.keys(manifests).find((key) => key.startsWith(`${packageName}@`));
888
- if (manifestKey) {
889
- const manifest = manifests[manifestKey];
890
- if (manifest.version) {
891
- return manifest.version;
892
- }
893
- }
894
- }
895
1021
  return null;
896
1022
  }
897
1023
  // Check for exact version match first (most common case)
@@ -988,3 +1114,711 @@ function findBestVersionMatch(versionSpec, candidates) {
988
1114
  }
989
1115
  return best.version;
990
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
+ }