Skip to content

deps: migrate pnpm internals to v12 - #10508

Merged
zkochan merged 36 commits into
teambit:masterfrom
zkochan:pnpm11-fresh
Jul 31, 2026
Merged

zkochan merged 36 commits into
teambit:masterfrom
zkochan:pnpm11-fresh

Conversation

@zkochan

@zkochan zkochan commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Migrate Bit's pnpm integration to @pnpm/[email protected] and the pnpm v12 package split, including the new @pnpm/<domain>.<leaf> helper packages.
  • Add a small CJS-to-ESM loader for pnpm helper modules that are now ESM-only, and update config/auth/proxy/network handling to @pnpm/config.reader and typed config fields.
  • Port the pnpm install/resolve/rebuild/pack paths to the N-API surface, preserving Bit lockfile metadata across installs and adapting read-package hooks, rebuild behavior, script policies, and package-manager outputs.
  • Update dependency graph and lockfile conversion for the pnpm v12 lockfile shape: lazy-load ESM lockfile helpers, preserve valid workspace component package entries, scrub only unresolved unpublished workspace snaps, prune unreachable lockfile entries, and normalize merged peer-provider graphs.
  • Fix pnpm/root-component integration issues found during CI: app root manifests now include only the app's workspace dependency closure, injected absolute root-component paths are linked/written correctly, and compiled side effects are copied to all injected/root component dist dirs.
  • Keep install-time unpublished snap errors actionable under pnpm N-API resolver errors, including the new ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER path.
  • Fix CI PR lane branch detection for CircleCI/GitHub PR refs, including pull/<id>/merge, bounded GitHub API lookup, and regression coverage for the branch-ref matcher.
  • Harden CircleCI/BVM Bit CLI bundle publishing for pnpm N-API: copy packages into the release tarballs, verify target @pnpm/napi.* native binaries for linux/macos/windows bundles, and rebuild second-arch bundles from a clean install directory.
  • Refresh e2e/unit coverage and expectations for pnpm v12 lockfiles, deps-graph restore behavior, hoisting, package-manager config, tsconfig/env isolation, and review-comment regressions.

Test plan

  • bit compile teambit.dependencies/pnpm teambit.dependencies/dependency-resolver teambit.git/ci
  • bit test scopes/dependencies/pnpm/lynx.spec.ts scopes/dependencies/pnpm/lockfile-deps-graph-converter.spec.ts scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.spec.ts — 34/34 passed
  • bit test scopes/git/ci/pull-request-ref.spec.ts — 2/2 passed
  • npm run mocha-circleci -- e2e/harmony/deps-graph.e2e.ts --grep "two components with different peer dependencies( should| importing)" — 7 passing
  • npm run mocha-circleci -- e2e/harmony/dependencies/never-built-dependencies.e2e.ts --grep "using pnpm" — 1 passing
  • npm run mocha-circleci -- e2e/harmony/ci-commands.e2e.ts --grep "bit ci pr workflow" — 6 passing
  • npm run mocha-circleci -- e2e/harmony/root-components.e2e.ts --grep "pnpm hoisted linker" — 12 passing, 2 pending
  • Qodo review threads answered and resolved after fixes
  • Throwaway [email protected] hoisted/copy install of @pnpm/[email protected] --os=linux --cpu=arm64 verified the target pnpm-napi.node binary
  • .circleci/config.yml parsed with the repo yaml package
  • npm run lint-circle
  • bit test scopes/dependencies/pnpm/lynx.spec.ts scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.spec.ts — 13/13 passed after lint-only fixes
  • Broader e2e suite
  • CI green

Replaces #10293.

@zkochan zkochan mentioned this pull request Jul 20, 2026
5 of 7 tasks
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Migrate Bit’s pnpm integration to pnpm v12 (N-API) with ESM shims

✨ Enhancement 🧪 Tests ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Migrate Bit’s pnpm integration to pnpm v12 N-API and renamed @pnpm/* modules.
• Add ESM loading shims and lockfile/graph pruning to keep installs deterministic.
• Update e2e expectations, CI timeouts, and Node/Babel config for the new runtime.
Diagram

graph TD
  A["InstallMain"] --> B["PnpmPackageManager"] --> C["pnpm/lynx.ts"] --> D["@pnpm/napi"]
  B --> E["load-pnpm-esm.cjs"] --> F["pnpm ESM modules"]
  B --> G["lockfile-deps-graph-converter"] --> H["DependenciesGraph"] --> I[("pnpm-lock.yaml")]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Stay on pnpm v11 TypeScript engine (@pnpm/core/mutateModules)
  • ➕ More feature-complete parity (peer issues, rebuild selectors) without N-API gaps
  • ➕ Fewer ESM interop shims and fewer runtime constraints
  • ➖ Blocks upgrade to newer pnpm internals and naming split
  • ➖ Continues reliance on deprecated/reshuffled internals and older dependency graph APIs
2. Wrap pnpm CLI (shell out) instead of using internal APIs
  • ➕ Avoids tight coupling to internal package renames and TS/N-API signatures
  • ➕ ESM/CJS boundary becomes Node’s problem, not Bit’s
  • ➖ Harder to integrate with Bit’s lockfile graph conversion and custom hooks
  • ➖ Weaker performance/telemetry control; brittle output parsing
3. Centralize ESM bridging behind a single internal pnpm adapter package
  • ➕ Keeps ESM-only dynamic imports and structural typing in one place
  • ➕ Reduces repeated loadPnpmEsm/loadLockfileFs patterns across modules
  • ➖ Extra refactor cost in this already-large migration
  • ➖ May delay landing the pnpm v12 upgrade

Recommendation: The chosen direction (move to @pnpm/napi and selectively bridge ESM-only helpers) is the right long-term alignment with pnpm v12. The main follow-up to consider is consolidating ESM loading and structural typings into one adapter module to reduce duplication (e.g., repeated loadPnpmEsm/loadLockfileFs patterns) once the migration is stable. Avoid switching to CLI wrapping unless internal API churn becomes unmanageable, since Bit needs deep integration (hooks, graph/lockfile manipulation, and install-time policies).

Files changed (37) +1835 / -5728

Enhancement (11) +741 / -371
npm-ci-registry.tsLazy-load pnpm fetch via ESM-friendly dynamic import +1/-1

Lazy-load pnpm fetch via ESM-friendly dynamic import

• Removes static import of @pnpm/fetch and replaces it with a runtime dynamic import of @pnpm/network.fetch to align with pnpm package renames/ESM constraints.

components/legacy/e2e-helper/npm-ci-registry.ts

dependency-resolver.main.runtime.tsReplace pnpm bare-spec parser with local version-spec validation +10/-9

Replace pnpm bare-spec parser with local version-spec validation

• Drops @pnpm/npm-resolver’s parseBareSpecifier dependency and implements a local validator supporting semver/ranges, workspace/file/link/git protocols, registry tarball URLs, npm aliasing, and simple tags.

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts

get-proxy-config.tsAdapt proxy config lookup to config.reader authConfig/noProxy fields +5/-2

Adapt proxy config lookup to config.reader authConfig/noProxy fields

• Moves Config typing to @pnpm/config.reader and resolves noProxy from typed fields plus compatible fallbacks across authConfig/rawConfig keys.

scopes/dependencies/pnpm/get-proxy-config.ts

get-registries.tsUse config.authConfig and typed default registry for credentials +12/-7

Use config.authConfig and typed default registry for credentials

• Migrates from rawConfig to authConfig for credentials lookup and fixes original-auth selection using the typed default registry URI instead of reading registry from ini.

scopes/dependencies/pnpm/get-registries.ts

load-pnpm-esm.cjsAdd CJS shim to load pnpm ESM-only helper modules +19/-0

Add CJS shim to load pnpm ESM-only helper modules

• Introduces a native CommonJS loader that dynamically imports ESM-only pnpm packages and caches the result for reuse across the pnpm integration.

scopes/dependencies/pnpm/load-pnpm-esm.cjs

lockfile-deps-graph-converter.tsLoad ESM pnpm helpers lazily and prune unreachable lockfile entries +100/-8

Load ESM pnpm helpers lazily and prune unreachable lockfile entries

• Replaces direct imports with an init()-based dynamic loader for @pnpm/deps.path and @pnpm/lockfile.fs. Fixes resolve options to use rootDir, hardens integrity handling, scrubs failed workspace-component packages, and drops unreachable packages/snapshots (including Bit build metadata) from generated lockfiles.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts

lynx.tsPort pnpm integration to @pnpm/napi (install/resolve/rebuild/pack) +419/-294

Port pnpm integration to @pnpm/napi (install/resolve/rebuild/pack)

• Replaces the old @pnpm/core/client/store-controller flow with @pnpm/napi install/resolve/rebuild APIs. Adds authHeaderByUri derivation, proxy/network mapping, read-package hook composition, lockfile bit-block preservation across rewrites, update-all lockfile handling, and compatibility for build-script policies via allowBuilds/dangerouslyAllowAllBuilds.

scopes/dependencies/pnpm/lynx.ts

pnpm-prune-modules.tsLazy-load readCurrentLockfile from ESM @pnpm/lockfile.fs +16/-1

Lazy-load readCurrentLockfile from ESM @pnpm/lockfile.fs

• Introduces a local loader to dynamically import @pnpm/lockfile.fs and then uses readCurrentLockfile for pruning the virtual store directory.

scopes/dependencies/pnpm/pnpm-prune-modules.ts

pnpm.package-manager.tsUpdate pnpm package manager to new module names + lockfile pruning +149/-41

Update pnpm package manager to new module names + lockfile pruning

• Switches to @pnpm/config.reader, @pnpm/installing.modules-yaml, and new deps-inspection packages, plus adds an ESM loader for pnpm helpers. Initializes the lockfile graph converter, resolves hoist-pattern precedence, reads network settings from typed config fields, and prunes unreachable lockfile entries after merging graph-derived lockfile subsets.

scopes/dependencies/pnpm/pnpm.package-manager.ts

read-config.tsRead pnpm config via config.reader with explicit workspaceDir +4/-1

Read pnpm config via config.reader with explicit workspaceDir

• Migrates getConfig import to @pnpm/config.reader and passes workspaceDir so pnpm resolves workspace-level configuration consistently.

scopes/dependencies/pnpm/read-config.ts

packer.tsUse pnpm N-API pack instead of plugin-commands-publishing +6/-7

Use pnpm N-API pack instead of plugin-commands-publishing

• Replaces @pnpm/plugin-commands-publishing pack call with @pnpm/napi pack and correctly resolves tarball paths when returned as absolute or relative.

scopes/pkg/pkg/packer.ts

Bug fix (6) +298 / -31
merge-files.tsAvoid rethrowing after printing merge diagnostics +0/-1

Avoid rethrowing after printing merge diagnostics

• Removes a rethrow in the error handler, likely to prevent duplicated failures after emitting formatted error details.

scopes/component/modules/merge-helper/merge-files.ts

pnpm-error-to-bit-error.tsHandle pnpm N-API errors structurally (not as PnpmError class) +15/-3

Handle pnpm N-API errors structurally (not as PnpmError class)

• Defines a PnpmErrorLike interface and updates conversion logic to rely on optional fields (code/hint/prefix/pkgsStack) rather than @pnpm/error’s class types.

scopes/dependencies/pnpm/pnpm-error-to-bit-error.ts

ci.main.runtime.tsImprove branch detection for CircleCI PR ref checkouts +39/-0

Improve branch detection for CircleCI PR ref checkouts

• Avoids treating pull/* refs as real branch names and, when necessary, resolves the PR head ref via the GitHub API using CIRCLE_PULL_REQUEST(S). This keeps lane/cleanup logic correct in CircleCI workflows and e2e scenarios.

scopes/git/ci/ci.main.runtime.ts

dependencies-graph.tsNormalize merged graphs: peer providers + unreachable pruning +234/-19

Normalize merged graphs: peer providers + unreachable pruning

• Strengthens graph merge logic by merging root-edge neighbours deterministically, normalizing peer provider versions to the highest compatible, and pruning unreachable nodes/packages from the root.

scopes/scope/objects/models/dependencies-graph.ts

schema-extractor-context.tsAdjust unresolved-identifier handling path +0/-1

Adjust unresolved-identifier handling path

• Removes an early return constructing a TypeRefSchema in an unresolved identifier branch, likely allowing subsequent logic to handle the case consistently.

scopes/typescript/typescript/schema-extractor-context.ts

install.main.runtime.tsTreat N-API SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER as unpublished-snap candidate +10/-7

Treat N-API SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER as unpublished-snap candidate

• Expands unpublished-snap dependency error enrichment to recognize pnpm N-API’s SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER code in addition to the legacy NO_MATCHING_VERSION path.

scopes/workspace/install/install.main.runtime.ts

Refactor (1) +0 / -2
workspace-aspects-loader.tsRemove unreachable throw after returning scope aspects +0/-2

Remove unreachable throw after returning scope aspects

• Deletes a dead throw statement after an early return in the error-handling path.

scopes/workspace/workspace/workspace-aspects-loader.ts

Tests (10) +172 / -59
dependency-resolver.e2e.tsUpdate modules manifest + lockfile assertions for new pnpm internals +17/-8

Update modules manifest + lockfile assertions for new pnpm internals

• Switches modules manifest access to @pnpm/installing.modules-yaml via dynamic import and replaces .pnpm folder assertions with pnpm-lock.yaml snapshot/package checks. Also forces minimumReleaseAge=0 to stabilize registry resolution in tests.

e2e/harmony/dependency-resolver.e2e.ts

deps-graph-reimport.e2e.tsStabilize dependency resolver behavior under pnpm v12 +6/-8

Stabilize dependency resolver behavior under pnpm v12

• Sets dependency-resolver minimumReleaseAge=0 in multiple suites and removes an assertion documenting a prior lockfile merge limitation that no longer applies (or is no longer stable).

e2e/harmony/deps-graph-reimport.e2e.ts

deps-graph.e2e.tsStabilize deps-graph e2e with minimumReleaseAge override +3/-0

Stabilize deps-graph e2e with minimumReleaseAge override

• Adds dependency-resolver minimumReleaseAge=0 to reduce flaky behavior when resolving latest versions during tests.

e2e/harmony/deps-graph.e2e.ts

install.e2e.tsAssert updates via pnpm-lock.yaml instead of virtual-store dirs +11/-2

Assert updates via pnpm-lock.yaml instead of virtual-store dirs

• Adds YAML parsing and validates updated subdependencies through lockfile packages/snapshots. Also forces minimumReleaseAge=0 for deterministic dist-tag installs.

e2e/harmony/install.e2e.ts

pkg-manager-config.e2e.tsValidate capsule installs read workspace pnpm config (pnpm-workspace.yaml) +20/-14

Validate capsule installs read workspace pnpm config (pnpm-workspace.yaml)

• Moves modules manifest reading to @pnpm/installing.modules-yaml (dynamic import) and updates the test to assert pnpm-workspace.yaml hoistPattern is applied in capsules (instead of .npmrc). Adjusts workspace flags to keep aspect/env resolution stable.

e2e/harmony/pkg-manager-config.e2e.ts

pnpm-default-hoisting.e2e.tsUse installing.modules-yaml API via dynamic import +6/-2

Use installing.modules-yaml API via dynamic import

• Replaces @pnpm/modules-yaml with @pnpm/installing.modules-yaml and wraps readModulesManifest in an async dynamic import helper for ESM compatibility.

e2e/harmony/pnpm-default-hoisting.e2e.ts

tsconfig-env-mismatch.e2e.tsStabilize tsconfig mismatch test setup and assertions +3/-8

Stabilize tsconfig mismatch test setup and assertions

• Installs required TypeScript/compiler tooling earlier in the suite, removes redundant install during link/build, and simplifies the build assertion to expect no throw.

e2e/harmony/tsconfig-env-mismatch.e2e.ts

lockfile-deps-graph-converter.spec.tsInitialize converter ESM deps and add peer-provider merge coverage +84/-9

Initialize converter ESM deps and add peer-provider merge coverage

• Adds an init() call before tests (to load ESM-only pnpm helpers) and introduces a test ensuring merged graphs pick the highest compatible peer provider version when producing a lockfile.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.spec.ts

pnpm-error-to-bit-error.spec.tsAvoid importing ESM @pnpm/error in tests +15/-5

Avoid importing ESM @pnpm/error in tests

• Replaces PnpmError construction with a structural error factory to keep mocha/Babel from pulling ESM-only @pnpm/error into the test runtime.

scopes/dependencies/pnpm/pnpm-error-to-bit-error.spec.ts

schema.spec.tsStabilize chai-subset usage via typed helper +7/-3

Stabilize chai-subset usage via typed helper

• Introduces a helper wrapper for containSubset to avoid typing/chain issues and updates schema subset assertions to use it.

scopes/semantics/schema/schema.spec.ts

Other (9) +624 / -5265
config.ymlIncrease no-output timeout for split e2e runs +1/-0

Increase no-output timeout for split e2e runs

• Adds a 50-minute no_output_timeout to the e2e split-test command step to prevent CircleCI from killing long silent runs.

.circleci/config.yml

babel.config.jsExclude dynamic-import transform to preserve native import() +1/-0

Exclude dynamic-import transform to preserve native import()

• Configures Babel preset-env to exclude @babel/plugin-transform-dynamic-import so dynamic import remains intact for ESM-only pnpm modules.

babel.config.js

package.jsonBump required Node engine to 22.13+ +1/-1

Bump required Node engine to 22.13+

• Updates the project’s engines.node requirement to >=22.13.0, aligning runtime expectations with pnpm v12 / ESM/N-API usage.

package.json

pnpm-lock.yamlRefresh lockfile for pnpm v12 internal dependency set +588/-5236

Refresh lockfile for pnpm v12 internal dependency set

• Updates the workspace lockfile to reflect the renamed @pnpm/* packages, new versions, and N-API adoption.

pnpm-lock.yaml

package-manager.tsSwitch peer-issues typing to pnpm N-API +1/-1

Switch peer-issues typing to pnpm N-API

• Updates PeerDependencyIssuesByProjects import to come from @pnpm/napi instead of @pnpm/core.

scopes/dependencies/dependency-resolver/package-manager.ts

yarn.package-manager.tsSwitch parseOverrides import to config.parse-overrides +1/-1

Switch parseOverrides import to config.parse-overrides

• Updates the pnpm overrides parser dependency to the new module split used by recent pnpm versions.

scopes/dependencies/yarn/yarn.package-manager.ts

babel-config.tsPreserve native dynamic import in Harmony Babel config +1/-0

Preserve native dynamic import in Harmony Babel config

• Matches root Babel behavior by excluding @babel/plugin-transform-dynamic-import to keep import() available for ESM-only pnpm modules at runtime.

scopes/harmony/aspect/babel/babel-config.ts

e2e-test-timings.jsonUpdate e2e runtime manifest for scheduling/splitting +3/-1

Update e2e runtime manifest for scheduling/splitting

• Bumps expected runtime for deps-graph.e2e.ts and adds timings for newly tracked tests to keep CircleCI splitting accurate.

scripts/e2e-test-timings.json

workspace.jsoncRename and bump @pnpm/* internal deps; add overrides for mirror gaps +27/-25

Rename and bump @pnpm/* internal deps; add overrides for mirror gaps

• Migrates pnpm internal dependencies to the v11+ split naming and introduces @pnpm/napi (v12 alpha). Adds resolution overrides to pin packages to versions available in bit.cloud’s registry mirror and updates related engine settings.

workspace.jsonc

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (17) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. strictSSL overridden by pnpm 🐞 Bug ≡ Correctness
Description
PnpmPackageManager.getNetworkConfig() forwards strictSSL whenever config.strictSsl is non-null,
so pnpm’s resolved default can override Bit/global strictSSL settings during
DependencyResolverMain.getNetworkConfig() merging. This can make BIT_NETWORK_STRICT_SSL / global
config ineffective and cause unexpected registry/proxy TLS behavior.
Code

scopes/dependencies/pnpm/pnpm.package-manager.ts[R346-348]

+    if (config.strictSsl != null) {
+      result.strictSSL = config.strictSsl;
   }
Evidence
The pnpm package manager returns strictSSL without checking explicitSettings, while the
dependency resolver merges package-manager network config over global Http network config, so pnpm
defaults can override Bit/global settings.

scopes/dependencies/pnpm/pnpm.package-manager.ts[340-358]
scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[811-816]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`PnpmPackageManager.getNetworkConfig()` currently sets `result.strictSSL` whenever `config.strictSsl != null`. Because `DependencyResolverMain.getNetworkConfig()` merges configs as `{...global, ...packageManager, ...depResolverConfig}`, this means pnpm’s *resolved default* can override the global Bit network config even when the user never configured `strict-ssl` in pnpm.
### Issue Context
You already implemented `explicitSettings` gating for numeric network settings to avoid forwarding pnpm defaults. `strictSsl` should follow the same rule; otherwise strict SSL behavior can change simply because pnpm supplies a default.
### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[314-358]
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[811-816]
### Suggested fix
- Only set `result.strictSSL` when the user explicitly configured it.
- Prefer: `explicitSettings.has('strictSsl')` (or the correct key used by `@pnpm/napi`’s `explicitSettings`).
- If `explicitSettings` is absent (older engines), do **not** forward `strictSSL` at all (to preserve current “only user-configured settings override global config” behavior), or add an alternative explicitness check if `ResolvedConfig` exposes one.
Example (key name must be verified):

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. npm alias rejected 🐞 Bug ≡ Correctness
Description
DependencyResolverMain.isValidVersionSpecifier() returns false for valid unversioned npm: alias
specs (and can also mis-handle scoped aliases) because it assumes an @ suffix must exist and uses
lastIndexOf('@') to find it. Any validation path that relies on this method (e.g.
validateAspectData() for dependency/policy versions) will reject specs like npm:uri-js-replace
that are present in this repo’s lockfile/config.
Code

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[R1483-1486]

+    if (trimmedSpec.startsWith('npm:')) {
+      const versionStart = trimmedSpec.lastIndexOf('@');
+      return versionStart > 'npm:'.length && this.isValidVersionSpecifier(trimmedSpec.slice(versionStart + 1));
+    }
Evidence
The new npm: handling returns false when no @ version suffix exists (e.g. npm:uri-js-replace
yields lastIndexOf('@') === -1). The repo’s own lockfile/config uses that exact unversioned npm:
alias form, demonstrating it is a valid/expected specifier in this codebase but would be rejected by
the current validator.

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1477-1487]
pnpm-lock.yaml[24-32]
workspace.jsonc[711-718]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`DependencyResolverMain.isValidVersionSpecifier()` currently treats `npm:` specs as valid only if they contain an `@<version>` segment. This incorrectly rejects valid pnpm/npm alias specifiers like `npm:uri-js-replace` (and can also break scoped aliases like `npm:@scope/pkg`), because the code uses `lastIndexOf('@')` without accounting for scoped package names or the absence of an explicit version.
### Issue Context
The repository itself contains `npm:` alias specs without a version (e.g. `uri-js: npm:uri-js-replace`). With the current implementation, `isValidVersionSpecifier('npm:uri-js-replace')` returns `false`.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1477-1487]
### Implementation notes
- For `npm:` specs, parse the portion after `npm:` as a *package name* (possibly scoped) optionally followed by `@<versionOrRange>`.
- Do **not** treat the first `@` of a scoped package as the version separator.
- A robust approach:
- `const alias = trimmedSpec.slice('npm:'.length)`
- Find a version separator `@` **only if** it occurs *after* the last `/` in `alias` (so `npm:@scope/pkg@^1` works, `npm:@scope/pkg` works).
- If no version separator exists, accept the alias as valid (optionally validate the alias package name with an existing package-name validator if available).
- If a version separator exists, validate the suffix via `semver.valid/validRange` (or recursively via `isValidVersionSpecifier`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Heap cap bypass 🐞 Bug ☼ Reliability
Description
CommandHelper.runCmd() spreads envVariables after childNodeOptions(), so any caller-provided
envVariables.NODE_OPTIONS overrides the intended "--max-old-space-size=2048" cap and can reintroduce
child-process OOMs. This makes the new memory protection depend on each call site never setting
NODE_OPTIONS.
Code

components/legacy/e2e-helper/e2e-command-helper.ts[119]

+    const env = { ...process.env, ...childNodeOptions(), ...envVariables };
Evidence
The new env merge order allows NODE_OPTIONS from envVariables to override the capped value produced
by childNodeOptions(), contradicting the documented goal of always capping spawned children.

components/legacy/e2e-helper/e2e-command-helper.ts[106-129]
components/legacy/e2e-helper/e2e-command-helper.ts[1037-1050]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`runCmd()` constructs `env` as `{ ...process.env, ...childNodeOptions(), ...envVariables }`, which allows `envVariables.NODE_OPTIONS` to overwrite the capped NODE_OPTIONS.
### Issue Context
The intention of `childNodeOptions()` is to cap spawned children to `--max-old-space-size=2048` to avoid CI OOM kills.
### Fix Focus Areas
- components/legacy/e2e-helper/e2e-command-helper.ts[106-129]
- components/legacy/e2e-helper/e2e-command-helper.ts[1045-1050]
### Suggested fix
Build `env` so the cap always wins while still preserving other caller env vars. For example:
- Compute `effectiveNodeOptions` from `(envVariables?.NODE_OPTIONS ?? process.env.NODE_OPTIONS ?? '')`, strip any existing `--max-old-space-size*` forms, then append `--max-old-space-size=2048`.
- Set `env = { ...process.env, ...envVariables, NODE_OPTIONS: effectiveNodeOptions }` (note: NODE_OPTIONS assigned last / explicitly).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (7)
4. file: deps deleted 🐞 Bug ≡ Correctness
Description
PnpmPackageManager.calcDependenciesGraph() tries to preserve injected sibling workspace deps (file:
refs) only when the importer entry is a string, but pnpm v12 lockfiles store importer deps as
objects (with a .version field). As a result, real injected direct dependencies can be deleted from
the component importer, producing an incomplete dependency graph.
Code

scopes/dependencies/pnpm/pnpm.package-manager.ts[R512-527]

+          if (importerId === componentImporterId) {
+            const ref =
+              importer.dependencies?.[workspacePkgName] ??
+              importer.devDependencies?.[workspacePkgName] ??
+              importer.optionalDependencies?.[workspacePkgName];
+            if (typeof ref === 'string' && ref.startsWith('file:')) continue;
+          }
+          for (const depType of [
+            'dependencies',
+            'devDependencies',
+            'optionalDependencies',
+            'specifiers',
+            'dependenciesMeta',
+          ]) {
+            delete importer[depType]?.[workspacePkgName];
}
Evidence
The deletion guard only checks typeof ref === 'string', but the repo’s updated e2e tests treat
pnpm v12 lockfile importer deps as objects with a .version property, so file: refs won’t be
preserved and will be deleted by the loop.

scopes/dependencies/pnpm/pnpm.package-manager.ts[501-528]
e2e/harmony/deps-graph.e2e.ts[205-211]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`calcDependenciesGraph()` attempts to keep injected sibling workspace deps for the *component's own importer* when they are `file:` refs. The current check only preserves the dependency when the ref is a string, but pnpm v12 importer entries are typically objects like `{ specifier, version }`, so `file:` refs are not detected and are deleted.
### Issue Context
This breaks the intent described in the comment above the check (keep injected sibling deps in the component importer so the graph converter can rewrite them). It can lead to missing direct edges in the component dependency graph.
### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[501-528]
### Suggested change
When inspecting `ref`, normalize both shapes:
- If `ref` is a string, treat it as the version.
- If `ref` is an object, use `ref.version`.
Then apply the `file:` preservation logic on that normalized string.
Example:

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Nested peer ranges ignored 🐞 Bug ≡ Correctness
Description
DependenciesGraph.normalizePeerProviderVersions() rewrites nested peer-provider IDs without passing
the nested provider’s own peerDependencies, so nested peers fall back to “highest” selection even
when that breaks the provider’s peer ranges. This can yield invalid peer graphs/lockfile IDs and
cause installs/resolution to be incorrect or fail.
Code

scopes/scope/objects/models/dependencies-graph.ts[R148-165]

+  private normalizePeerProviderVersions(): void {
+    const versionsByPackageName = this.collectVersionsByPackageName();
+    const getBestCompatiblePeer = (name: string, range: string) =>
+      versionsByPackageName
+        .get(name)
+        ?.find(({ version }) => semver.satisfies(version, range, { includePrerelease: true }));
+    const getHighestPeer = (name: string) => versionsByPackageName.get(name)?.[0];
+    const rewritePeerId = (peerId: string, peerDependencies?: Record<string, string>): string => {
+      const parsedPeer = parsePkgId(peerId);
+      const peerIds = splitPeerIds(peerId).map((nestedPeerId) => rewritePeerId(nestedPeerId));
+      let rewrittenBase = nodeIdWithoutPeerSuffix(peerId);
+      if (parsedPeer) {
+        const range = peerDependencies?.[parsedPeer.name];
+        const bestPeer = range ? getBestCompatiblePeer(parsedPeer.name, range) : getHighestPeer(parsedPeer.name);
+        if (bestPeer) rewrittenBase = `${parsedPeer.name}@${bestPeer.version}`;
+      }
+      return `${rewrittenBase}${createPeerSuffix(peerIds)}`;
+    };
Evidence
The recursive rewrite drops nested peer constraints: nested peers are rewritten without
peerDependencies, which makes the algorithm choose getHighestPeer() for them even though
compatibility checking only happens when a range is provided.

scopes/scope/objects/models/dependencies-graph.ts[148-165]
scopes/scope/objects/models/dependencies-graph.ts[182-196]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`normalizePeerProviderVersions()` recursively rewrites nested peer IDs via `rewritePeerId(nestedPeerId)` but does not pass any `peerDependencies` for the nested package, so nested peers are rewritten using `getHighestPeer()` instead of the best compatible peer.
### Issue Context
This happens in the new peer-provider normalization logic added to `DependenciesGraph.merge()`.
### Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[148-230]
### Suggested fix
- When rewriting a peerId that itself has nested peers, look up the nested provider package’s peerDependencies from `this.packages` (e.g. by `nodeIdWithoutPeerSuffix(nestedPeerId)` or by parsed name@version) and pass those into the recursive `rewritePeerId()` call.
- Add a regression test where a nested peer provider has a restrictive peer range and the highest available version is incompatible, asserting the rewritten ID keeps the highest *compatible* nested provider, not the absolute highest.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Null refToRelative neighbor id 🐞 Bug ≡ Correctness
Description
importerDepsToNeighbours() uses a non-null assertion on dp.refToRelative(version, name), but the
same module already treats refToRelative() as nullable; when it returns null (e.g., for
local/link-style refs), the graph is built with an invalid neighbour id and later graph processing
can fail.
Code

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[1]

bareSpecifier: pkgToResolve.version,
Evidence
The converter already assumes dp.refToRelative() can return null (it checks before pushing).
Meanwhile, the graph→lockfile path emits importer dependencies with link: versions, and the spec
asserts those exist (e.g. bar: { version: 'link:../bar' ... }). Feeding such a lockfile back into
importerDepsToNeighbours() will call dp.refToRelative('link:../bar', 'bar') and the current !
can yield an invalid neighbour id.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[73-83]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[201-216]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[350-353]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.spec.ts[228-275]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`importerDepsToNeighbours()` currently does `dp.refToRelative(version, name)!` and blindly pushes the resulting `id` into the neighbours list. However, the same file already handles `dp.refToRelative(...)` as nullable elsewhere, so this path can introduce `null/undefined` ids into the dependency graph (or throw later when consumers assume `id` is a string).
This is especially risky because the lockfile importer entries can legitimately contain non-registry refs (e.g. `link:../bar`), which are not guaranteed to be convertible to a pnpm depPath.
### Issue Context
- `extractDependenciesFromSnapshot()` already guards `dp.refToRelative(...)` with a null-check, proving the API is nullable.
- `convertGraphToLockfile()` explicitly writes importer entries with `link:` versions.
- The converter spec asserts that such `link:` entries exist in the generated lockfile importers.
### Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[73-84]
### Suggested fix
1. Replace the non-null assertion with a null-check:
- `const id = dp.refToRelative(version, name);`
- `if (!id) continue;` (or otherwise handle link/file refs explicitly if they must be represented)
2. Add/adjust a unit test that covers converting a lockfile whose importer dependency includes a `link:` version (or any other ref that makes `refToRelative` return null), asserting the converter does not crash and produces a sane graph.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Broken heredoc invocation 🐞 Bug ≡ Correctness
Description
The verify_pnpm_napi_bundle step runs node \<<'NODE', which escapes the heredoc operator so the
JS snippet may not be redirected into Node, breaking or stalling the CI verification command. This
affects every job that invokes the new bundle verification command (linux/macos/windows).
Code

.circleci/config.yml[R160-163]

+          command: |
+            cd <<parameters.directory>>
+            PNPM_NAPI_PACKAGE="<<parameters.package>>" node \<<'NODE'
+            const fs = require('fs');
Evidence
The CircleCI command block shows node \<<'NODE' before the inline JS. Escaping the heredoc
operator prevents the script body from being redirected into Node, so the verification step cannot
execute reliably.

.circleci/config.yml[160-166]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The CircleCI step `verify_pnpm_napi_bundle` uses `node \<<'NODE'`. The backslash escapes the heredoc operator (`<<`), so the shell may not treat it as a heredoc redirection and Node may not receive the embedded JS program.
## Issue Context
This command is used to verify that the platform-specific `@pnpm/napi.*` package includes `pnpm-napi.node` inside the Bit CLI bundle.
## Fix Focus Areas
- .circleci/config.yml[160-163]
## How to Fix
- Change:
- `PNPM_NAPI_PACKAGE="<<parameters.package>>" node \<<'NODE'`
- To:
- `PNPM_NAPI_PACKAGE="<<parameters.package>>" node <<'NODE'`
If CircleCI config processing conflicts with raw `<<`, alternatively avoid heredocs entirely (e.g., move the JS snippet into a checked-in script file and run `node path/to/script.js`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. git+ssh policy rejected 🐞 Bug ≡ Correctness
Description
DependencyResolverMain.validateAspectData() validates policy versions using
isValidVersionSpecifier(), but isValidVersionSpecifier() does not accept the pnpm-supported
git+ssh:// scheme. This will reject valid dependency policy entries (e.g. in
workspace.jsonc/env.jsonc) and fail aspect-data validation for those components/workspaces.
Code

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[R1475-1485]

isValidVersionSpecifier(spec: string): boolean {
-    return (
-      parseBareSpecifier(
-        spec,
-        'pkgname', // This argument is the package but we don't need it
-        'latest',
-        'https://registry.npmjs.org/'
-      ) != null
-    );
+    const trimmedSpec = spec.trim();
+    if (!trimmedSpec) return false;
+    if (semver.valid(trimmedSpec) || semver.validRange(trimmedSpec)) return true;
+    if (/^(?:workspace|file|link|git|git\+https?|ssh):/.test(trimmedSpec)) return true;
+    if (/^https?:\/\/registry\.npmjs\.org\/.+\/-.+\.tgz(?:[#?].*)?$/.test(trimmedSpec)) return true;
+    if (trimmedSpec.startsWith('npm:')) {
+      const versionStart = trimmedSpec.lastIndexOf('@');
+      return versionStart > 'npm:'.length && this.isValidVersionSpecifier(trimmedSpec.slice(versionStart + 1));
+    }
+    return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(trimmedSpec);
Evidence
The policy-validation path calls isValidVersionSpecifier() (no extra prefix allowances), and
isValidVersionSpecifier()’s protocol whitelist omits git+ssh: so git+ssh://... will not match
any accepted branch and will be treated as invalid.

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1432-1459]
scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1475-1485]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`DependencyResolverMain.isValidVersionSpecifier()` is used to validate dependency-policy versions, but its protocol whitelist regex does not include `git+ssh:`. pnpm supports `git+ssh://...` and the same file already treats `git+ssh://` as an allowed dependency prefix elsewhere, so policy validation becomes inconsistent and rejects valid configs.
## Issue Context
- `validateAspectData()` validates `data.policy` versions only through `isValidVersionSpecifier()` (plus `+`/`-`), so missing protocol support becomes a hard validation failure.
## Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1432-1459]
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1475-1485]
## Proposed fix
- Expand the protocol regex to include `git\+ssh:` (and preferably keep parity with pnpm-supported git URL forms).
- Add/extend a unit test (if present for validation) that asserts `git+ssh://...` policy versions are accepted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Allow-all scripts flag lost 🐞 Bug ≡ Correctness
Description
resolveScriptPolicies() never sets dangerouslyAllowAllBuilds, so when callers pass
dangerouslyAllowAllScripts the intended "allow all builds" behavior is not enabled and script
execution is evaluated under the ordinary allowBuilds map instead. This can break installs that
require lifecycle/build scripts (e.g. native modules) while silently ignoring the user’s
configuration.
Code

scopes/dependencies/pnpm/lynx.ts[R549-563]

+  neverBuiltDependencies,
+}: ScriptPolicyConfig): { allowBuilds: Record<string, boolean | string>; dangerouslyAllowAllBuilds?: boolean } {
+  const allowBuilds: Record<string, boolean | string> = {};
if (dangerouslyAllowAllScripts) {
-    if (resolvedNeverBuilt == null) {
-      // If neverBuiltDependencies is not explicitly set, use a default list
-      // we tell pnpm to allow all scripts to be executed, except the packages listed below.
-      resolvedNeverBuilt = ['core-js'];
+    // pnpm v11's createAllowBuildFunction ignores allowBuilds when dangerouslyAllowAllBuilds is
+    // set, so emit allowBuilds with just the deny entries whenever a deny list exists.
+    if (!neverBuiltDependencies?.length) {
+      allowBuilds['core-js'] = false;
+      return { allowBuilds };
}
-  } else {
-    onlyBuiltDependencies = [];
-    ignoredBuiltDependencies = [];
-    for (const [packageDescriptor, allowedScript] of Object.entries(allowScripts ?? {})) {
-      switch (allowedScript) {
-        case true:
-          onlyBuiltDependencies.push(packageDescriptor);
-          break;
-        case false:
-          ignoredBuiltDependencies.push(packageDescriptor);
-          break;
-        default:
-          // Ignore any non-boolean values. String values are placeholders that the user
-          // should replace with booleans.
-          // pnpm will print a warning about these during installation.
-          break;
-      }
+    for (const pkg of neverBuiltDependencies) {
+      allowBuilds[pkg] = false;
}
-    for (const trustedPkgName of TRUSTED_PACKAGE_NAMES) {
-      if (allowScripts?.[trustedPkgName] == null) {
-        onlyBuiltDependencies.push(trustedPkgName);
-      }
+    return { allowBuilds };
+  }
Evidence
The install path explicitly forwards dangerouslyAllowAllBuilds to @pnpm/napi, but the policy
builder never sets it even when dangerouslyAllowAllScripts is provided by the caller, so the
allow-all behavior cannot take effect.

scopes/dependencies/pnpm/lynx.ts[368-399]
scopes/dependencies/pnpm/lynx.ts[540-584]
scopes/dependencies/pnpm/pnpm.package-manager.ts[193-215]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`dangerouslyAllowAllScripts` is accepted by Bit’s pnpm install options, but the pnpm v12/N-API install path never translates it into the new engine flag (`dangerouslyAllowAllBuilds`). As a result, callers expecting “allow all build scripts” don’t get that behavior.
## Issue Context
- `install()` forwards `scriptPolicies.dangerouslyAllowAllBuilds` into `nodeApi.install(...)`, but `resolveScriptPolicies()` always returns only `{ allowBuilds }`.
- `PnpmPackageManager` passes `dangerouslyAllowAllScripts` down to `lynx.install()`, so this is a user-visible regression.
## Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[540-584]
- scopes/dependencies/pnpm/lynx.ts[368-401]
## Suggested fix
- In `resolveScriptPolicies()`, when `dangerouslyAllowAllScripts` is true, return `{ allowBuilds, dangerouslyAllowAllBuilds: true }`.
- Preserve the existing deny behavior for `neverBuiltDependencies` (and the default `core-js` deny) by keeping those entries in `allowBuilds`.
- Add/adjust a unit/e2e test that sets `dangerouslyAllowAllScripts: true` and asserts the install engine receives `dangerouslyAllowAllBuilds: true` (or that a known script-required package successfully builds).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. Over-scrubs workspace lockfile 🐞 Bug ≡ Correctness
Description
convertGraphToLockfile() pre-populates failedWorkspaceComponentPkgs with every workspace
component pkgId, so scrubPkgsFromLockfile() will always delete those packages and remove
snapshot/importer references even when resolutions are valid, producing an incomplete/incorrect
generated lockfile.
Code

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[R369-373]

const pkgsToResolve = getPkgsToResolve(lockfile, manifests);
const failedWorkspaceComponentPkgs = new Set<string>();
+  for (const pkgId of getWorkspaceComponentPkgIds(lockfile, graph, manifests)) {
+    failedWorkspaceComponentPkgs.add(pkgId);
+  }
Evidence
The function seeds failedWorkspaceComponentPkgs from getWorkspaceComponentPkgIds() and later
scrubs when the set is non-empty. scrubPkgsFromLockfile() deletes entries from lockfile.packages
and removes matching dependencies from snapshots and importers, so seeding the set with all
workspace component pkgIds removes valid data regardless of resolution success.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-442]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[640-682]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`convertGraphToLockfile()` currently seeds `failedWorkspaceComponentPkgs` with all workspace component pkgIds before any resolution/validation happens, and then scrubs them from the lockfile. This can remove legitimate component deps and their edges from the generated lockfile.
### Issue Context
The scrub set should only contain pkgIds that are actually invalid/unresolvable (e.g., unpublished snap versions) so pnpm can fall back to resolving from importer specifiers.
### Fix Focus Areas
- Remove unconditional seeding of `failedWorkspaceComponentPkgs` and instead:
- Keep a separate `workspaceComponentPkgIds` set (if needed for later checks), and
- Add to `failedWorkspaceComponentPkgs` only when a workspace component has missing/empty resolution after the resolve pass.
- Ensure `scrubPkgsFromLockfile()` is called only when there are *actual* failures.
#### Code locations
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-442]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

11. Eager N-API import 🐞 Bug ☼ Reliability
Description
Packer imports @pnpm/napi at module scope, so loading PkgAspect triggers pnpm’s native engine
initialization even when packing is never invoked. This adds startup overhead and can make unrelated
Bit commands fail to start when the native binary is unavailable/incompatible.
Code

scopes/pkg/pkg/packer.ts[5]

+import * as nodeApi from '@pnpm/napi';
Evidence
The PR introduces a top-level @pnpm/napi import in Packer, and PkgMain imports/instantiates
Packer during provider initialization. The repo already documents the intended pattern to avoid
eager native loads by lazy-requiring @pnpm/napi.

scopes/pkg/pkg/packer.ts[2-6]
scopes/pkg/pkg/pkg.main.runtime.ts[33-34]
scopes/pkg/pkg/pkg.main.runtime.ts[148-154]
scopes/dependencies/pnpm/read-config.ts[9-18]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`scopes/pkg/pkg/packer.ts` imports `@pnpm/napi` at top-level. Since `PkgMain` imports and constructs `Packer` during aspect provider initialization, this can load the native pnpm engine in many Bit processes that never call pack.
## Issue Context
Elsewhere (e.g. `scopes/dependencies/pnpm/read-config.ts`) the code explicitly lazy-requires `@pnpm/napi` to avoid mapping the native engine into every `bit` process.
## Fix Focus Areas
- scopes/pkg/pkg/packer.ts[2-6]
- scopes/pkg/pkg/packer.ts[125-142]
### Suggested approach
- Remove the top-level `import * as nodeApi from '@pnpm/napi'`.
- Add a small cached loader inside `pnpmPack()` (or a private helper) similar to:
- `let napiPromise; const loadNapi = () => (napiPromise ??= import('@pnpm/napi'));`
- then `const nodeApi = await loadNapi(); await nodeApi.pack({ dir: cwd });`
- Keep the cache to avoid repeated dynamic imports in the same process.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


12. Invalid NODE_OPTIONS possible 🐞 Bug ≡ Correctness
Description
childNodeOptions() tokenizes NODE_OPTIONS by splitting on spaces and only removes tokens that start
with "--max-old-space-size"; if NODE_OPTIONS is provided in a split flag/value form, the value token
is left behind, producing a malformed NODE_OPTIONS string that may prevent Node from starting. This
can break all spawned bit children in e2e runs under such NODE_OPTIONS inputs.
Code

components/legacy/e2e-helper/e2e-command-helper.ts[R1046-1049]

+  const withoutHeapCap = (process.env.NODE_OPTIONS ?? '')
+    .split(' ')
+    .filter((opt) => opt && !opt.startsWith('--max-old-space-size'));
+  return { NODE_OPTIONS: [...withoutHeapCap, '--max-old-space-size=2048'].join(' ') };
Evidence
The implementation explicitly splits on spaces and filters only the flag token, which can leave a
standalone value token behind in the reconstructed NODE_OPTIONS string.

components/legacy/e2e-helper/e2e-command-helper.ts[1045-1050]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`childNodeOptions()` splits `NODE_OPTIONS` by spaces and filters out only tokens starting with `--max-old-space-size`, but it does not consume/remove the following token when the heap size is passed as a separate argument.
### Issue Context
Even if your CI currently uses the `--max-old-space-size=<n>` form, this sanitizer should not create malformed NODE_OPTIONS values for other valid/possible inputs.
### Fix Focus Areas
- components/legacy/e2e-helper/e2e-command-helper.ts[1045-1050]
### Suggested fix
Parse tokens with a small state machine:
- Iterate tokens; when you see `--max-old-space-size`, skip it and also skip the next token (the value).
- Also skip any `--max-old-space-size=<n>` token.
- Preserve all other tokens, then append `--max-old-space-size=2048`.
Additionally consider splitting on whitespace (`/\s+/`) instead of a literal `' '`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


13. Recursive lockfile pruning 🐞 Bug ☼ Reliability
Description
dropUnreachableLockfileEntries() recursively calls visit() per dependency snapshot; sufficiently
deep dependency chains can trigger "Maximum call stack size exceeded" and crash
convertGraphToLockfile() during installs/lockfile writes.
Code

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[R505-528]

+function dropUnreachableLockfileEntries(lockfile: BitLockfileFile): void {
+  const reachablePackages = new Set<string>();
+  const reachableSnapshots = new Set<string>();
+  const visit = (depPath: string) => {
+    if (reachableSnapshots.has(depPath)) return;
+    reachableSnapshots.add(depPath);
+    reachablePackages.add(dp.removeSuffix(depPath));
+    const snapshot = lockfile.snapshots?.[depPath];
+    if (!snapshot) return;
+    for (const depType of ['dependencies', 'optionalDependencies'] as const) {
+      for (const [name, ref] of Object.entries(snapshot[depType] ?? {})) {
+        if (ref.startsWith('link:') || ref.startsWith('file:')) continue;
+        visit(`${name}@${ref}`);
+      }
+    }
+  };
+  for (const importer of Object.values(lockfile.importers ?? {})) {
+    for (const depType of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) {
+      for (const [name, { version }] of Object.entries(importer[depType] ?? {})) {
+        if (version.startsWith('link:') || version.startsWith('file:')) continue;
+        visit(`${name}@${version}`);
+      }
+    }
+  }
Evidence
The converter’s new pruning walk is recursive (unbounded by depth), while the repo already contains
an explicit-stack implementation for the same operation to prevent stack overflow—showing the
intended safe pattern.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[505-528]
scopes/dependencies/pnpm/pnpm.package-manager.ts[650-672]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`dropUnreachableLockfileEntries()` performs a recursive DFS (`visit()` calls itself). Very deep dependency chains can overflow the JS call stack and crash lockfile generation.
## Issue Context
A nearly identical reachability prune in `pnpm.package-manager.ts` was implemented with an explicit stack specifically to avoid this failure mode.
## Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[505-528]
## Suggested fix
Rewrite the recursive `visit()` to use an explicit stack/loop (like `pruneUnreachableLockfileEntries()` in `pnpm.package-manager.ts`). Keep the same filtering rules (`link:`/`file:`) and the same reachable sets; only change traversal mechanics.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (4)
14. Recursive lockfile prune DFS 🐞 Bug ☼ Reliability
Description
pruneUnreachableLockfileEntries() performs a recursive DFS (visit() calls itself per dependency).
Very deep dependency chains can overflow the JS call stack during lockfile merge because
mergeGraphLockfileIntoExisting() calls this pruning unconditionally.
Code

scopes/dependencies/pnpm/pnpm.package-manager.ts[R646-657]

+  const visit = (depPath: string) => {
+    if (reachableSnapshots.has(depPath)) return;
+    reachableSnapshots.add(depPath);
+    reachablePackages.add(removePeerSuffix(depPath));
+    const snapshot = lockfile.snapshots?.[depPath];
+    if (!snapshot) return;
+    for (const depType of ['dependencies', 'optionalDependencies'] as const) {
+      for (const [name, ref] of Object.entries(snapshot[depType] ?? {}) as Array<[string, string]>) {
+        if (ref.startsWith('link:') || ref.startsWith('file:')) continue;
+        visit(`${name}@${ref}`);
+      }
+    }
Evidence
The new lockfile pruning routine is recursive and is invoked unconditionally as part of merging
graph-derived lockfile data into an existing lockfile, so deep chains can crash that path.

scopes/dependencies/pnpm/pnpm.package-manager.ts[584-626]
scopes/dependencies/pnpm/pnpm.package-manager.ts[643-668]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pruneUnreachableLockfileEntries()` uses recursion for graph traversal. While it has cycle protection, unusually deep chains can still exceed the call stack.
## Issue Context
The prune runs on every `mergeGraphLockfileIntoExisting()` call, so a pathological lockfile can crash installs/merges.
## Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[584-626]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[643-668]
### Suggested change
Replace recursive `visit()` with an explicit stack/queue (iterative DFS/BFS), mirroring the iterative approach used elsewhere (e.g., graph pruning in DependenciesGraph).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


15. Registries authConfig assumed 🐞 Bug ☼ Reliability
Description
getRegistries() and getProxyConfig() both pass/use config.authConfig and then index into it at
runtime, so if authConfig is missing, null, or not an object they can throw. This can prevent
registry/credential/proxy setup and potentially abort pnpm dependency resolution/installs.
Code

scopes/dependencies/pnpm/get-registries.ts[R15-24]

+  const defaultRegistryUri = config.registries.default;
Object.keys(config.registries).forEach((regName) => {
const uri = config.registries[regName];
-    let credentials = getCredentialsByURI(config.rawConfig, uri);
-    let originalAuthConfig = getOriginalAuthConfigByUri(config.rawConfig, uri);
+    let credentials = getCredentialsByURI(config.authConfig, uri);
+    let originalAuthConfig = getOriginalAuthConfigByUri(config.authConfig, uri, defaultRegistryUri);
if (isEmpty(credentials)) {
-      credentials = getCredentialsByURI(config.rawConfig, switchTrailingSlash(uri));
-      originalAuthConfig = getOriginalAuthConfigByUri(config.rawConfig, switchTrailingSlash(uri));
+      credentials = getCredentialsByURI(config.authConfig, switchTrailingSlash(uri));
+      originalAuthConfig = getOriginalAuthConfigByUri(config.authConfig, switchTrailingSlash(uri), defaultRegistryUri);
}
Evidence
The updated code path routes registry and credential setup through config.authConfig:
getRegistries() passes it into credential helpers, and the internal getScopedCredentials()
directly indexes into the provided config (e.g., config["..._authToken"]), which will throw if the
argument is undefined/null. Similarly, getProxyConfig() reads noProxy by indexing
authConfig['no-proxy'] / authConfig.noproxy (with only a TS cast), so when config.authConfig
is absent at runtime those property accesses can immediately throw during proxy computation.

scopes/dependencies/pnpm/get-registries.ts[13-33]
scopes/dependencies/pnpm/get-registries.ts[35-51]
scopes/dependencies/pnpm/get-registries.ts[53-85]
scopes/dependencies/pnpm/get-proxy-config.ts[4-15]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`getRegistries()` and `getProxyConfig()` assume `config.authConfig` is present and indexable, but the TypeScript casts provide no runtime safety; if `authConfig` is undefined/null or not a plain object, property indexing in credential extraction (`getScopedCredentials()`) and proxy computation (`noProxy`) can throw and break pnpm registry/credentials/proxy setup.
## Issue Context
This PR migrated pnpm config handling to `@pnpm/config.reader` and switched credential lookup to `config.authConfig`, while also starting to read `noProxy` from multiple sources including `config.authConfig`. As a result, callers that provide a minimal config object (or older shapes where `authConfig` is absent) can hit runtime exceptions.
## Fix Focus Areas
- scopes/dependencies/pnpm/get-registries.ts[13-33]
- scopes/dependencies/pnpm/get-registries.ts[35-61]
- scopes/dependencies/pnpm/get-registries.ts[53-85]
- scopes/dependencies/pnpm/get-proxy-config.ts[4-15]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


16. Recursive graph pruning DFS 🐞 Bug ☼ Reliability
Description
DependenciesGraph.pruneUnreachableFromRoot() traverses neighbours via a recursive DFS (visit() calls
itself per edge), which can exceed the JavaScript call stack on sufficiently deep dependency chains.
Because merge() now calls pruneUnreachableFromRoot() unconditionally, this can crash graph merges on
deep graphs.
Code

scopes/scope/objects/models/dependencies-graph.ts[R126-135]

+    const visit = (nodeId: string) => {
+      const pkgId = nodeIdWithoutPeerSuffix(nodeId);
+      reachablePackages.add(pkgId);
+      const edge = edgesById.get(nodeId);
+      if (!edge || reachableEdges.has(nodeId)) return;
+      reachableEdges.add(nodeId);
+      if (edge.attr?.pkgId) reachablePackages.add(edge.attr.pkgId);
+      for (const neighbour of edge.neighbours) {
+        visit(neighbour.id);
+      }
Evidence
merge() invokes pruneUnreachableFromRoot(), and pruneUnreachableFromRoot() uses a recursive visit()
function that calls itself for each neighbour.

scopes/scope/objects/models/dependencies-graph.ts[78-102]
scopes/scope/objects/models/dependencies-graph.ts[115-139]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pruneUnreachableFromRoot()` uses recursion for graph traversal. Deep dependency chains can overflow the JS call stack, crashing merge/normalization.
### Issue Context
The traversal is invoked from `merge()` after edges/packages are combined, so any merge on a deep graph can hit this path.
### Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[78-102]
- scopes/scope/objects/models/dependencies-graph.ts[115-139]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


17. Peer suffix not traversed 🐞 Bug ☼ Reliability
Description
pruneUnreachableFromRoot() marks reachability only via edge.neighbours and ignores peer-provider
package IDs encoded inside depPath suffix parentheses. If a peer provider is only present in the
suffix context (not as an explicit neighbour edge), it can be deleted from graph.packages and
omitted from generated lockfiles.
Code

scopes/scope/objects/models/dependencies-graph.ts[R115-146]

+  private pruneUnreachableFromRoot(): void {
+    const rootEdge = this.findRootEdge();
+    if (!rootEdge) return;
+    const edgesById = new Map<string, DependencyEdge>();
+    for (const edge of this.edges) {
+      if (edge.id !== DependenciesGraph.ROOT_EDGE_ID) {
+        edgesById.set(edge.id, edge);
+      }
+    }
+    const reachableEdges = new Set<string>();
+    const reachablePackages = new Set<string>();
+    const visit = (nodeId: string) => {
+      const pkgId = nodeIdWithoutPeerSuffix(nodeId);
+      reachablePackages.add(pkgId);
+      const edge = edgesById.get(nodeId);
+      if (!edge || reachableEdges.has(nodeId)) return;
+      reachableEdges.add(nodeId);
+      if (edge.attr?.pkgId) reachablePackages.add(edge.attr.pkgId);
+      for (const neighbour of edge.neighbours) {
+        visit(neighbour.id);
+      }
+    };
+    for (const neighbour of rootEdge.neighbours) {
+      visit(neighbour.id);
+    }
+    this.edges = [rootEdge, ...Array.from(edgesById.values()).filter((edge) => reachableEdges.has(edge.id))];
+    for (const pkgId of this.packages.keys()) {
+      if (!reachablePackages.has(pkgId)) {
+        this.packages.delete(pkgId);
+      }
+    }
+  }
Evidence
The pruning traversal only recurses through neighbour edges and only records the base node ID
(without peer suffix), so peer providers referenced solely in the suffix are not marked reachable.
Since lockfile generation populates output packages from graph.packages, any pruned package
disappears from the generated lockfile; the repo’s lockfile settings indicate peers can be
auto-installed, increasing the chance of peer-context-only references.

scopes/scope/objects/models/dependencies-graph.ts[115-145]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[302-324]
pnpm-lock.yaml[1-7]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pruneUnreachableFromRoot()` does not traverse peer-provider IDs embedded in node IDs (depPath suffix parentheses). This can incorrectly prune packages that are required for lockfile reconstruction if they are referenced only via peer context.
## Issue Context
- Reachability currently adds only the base `pkgId` (`nodeIdWithoutPeerSuffix(nodeId)`) and recurses only via `edge.neighbours`.
- `convertGraphToLockfile()` materializes the lockfile `packages`/`snapshots` from `graph.packages`, so removing a needed package entry changes the resulting lockfile.
## Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[115-146]
- scopes/scope/objects/models/dependencies-graph.ts[295-335]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[302-324]
## Suggested fix
- In `visit(nodeId)`, also traverse peer IDs returned by `splitPeerIds(nodeId)`:
- For each peerId: mark `nodeIdWithoutPeerSuffix(peerId)` reachable and, if there is an edge for that peerId, recurse into it as well.
- Ensure nested/compound peer IDs are handled (you already have `splitPeerIds()` supporting nesting).
- Add a unit test with a graph where a package has an ID like `[email protected]([email protected])` and `[email protected]` exists in `packages` but is not reachable via any `edge.neighbours` chain; assert it is retained after `merge()` pruning.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread scopes/git/ci/ci.main.runtime.ts Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4dc7b80

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit ab13018

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 9068b8c

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

Comment thread .circleci/config.yml Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3d3660f

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit aacaa7f

@zkochan
zkochan requested a review from GiladShoham July 21, 2026 09:01
@zkochan
zkochan enabled auto-merge (squash) July 21, 2026 09:01
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit dda3274

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit ba15aca

Comment thread scopes/dependencies/pnpm/lynx.ts Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit f0d4261

refToRelative returns null for link:-style refs, which importer entries
can legitimately carry (the converter itself emits them); the non-null
assertion produced neighbours with an invalid id.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit d393ee0

PkgMain constructs Packer at aspect init, so the module-scope
@pnpm/napi import mapped the native engine into every process loading
the pkg aspect; only pack needs it.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

The last static value import of ./lynx from the package manager pulled
the engine chain in at aspect init under eager compilation; only
resolveRemoteVersion's path needs it.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

lastIndexOf('@') treated a scoped alias's leading @ as the version
separator and required a version to exist, rejecting specs like
npm:uri-js-replace — which this repo's own overrides carry. The alias
now parses as an optionally scoped package name with an optional
version suffix.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6908795

@pnpm/[email protected] no longer depends on
@pnpm/config.reader, so the config.env-replace chain is gone from the
graph entirely and the mirror override for it is no longer needed.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 0ab9444

…installs

The bundle flow installs @teambit/bit into a fresh directory with its
own hardcoded override list, so the workspace.jsonc overrides never
apply there. bit.cloud's mirror caps @pnpm/config.nerf-dart below the
^2.0.1 the 11xx @pnpm packages need (and advertises an unservable
lex-comparator 4.0.1), which would fail the bundle install once a bit
version carrying those dependencies is published. Verified with pnpm
10.14.0 against the mirror: the bundle-style install fails without
these overrides and succeeds with them.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

strictSsl/ca/cert/key are optional in the engine's projection and set
only when explicitly configured — presence is the explicit gate the
numeric settings get from explicitSettings.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit ae65b53

@zkochan
zkochan merged commit 9aaf25c into teambit:master Jul 31, 2026
13 checks passed
zkochan added a commit that referenced this pull request Aug 1, 2026
…lls (#10551)

## Summary

After the pnpm-v12/napi migration (#10508), every `bit
install` wiped the `bit.depsRequiringBuild` block from `pnpm-lock.yaml`:

```diff
 bit:
-  depsRequiringBuild:
-    - '@apollo/[email protected]'
-    - '@parcel/[email protected]'
-    ...
+  depsRequiringBuild: []
```

Root cause: the migration dropped the `returnListOfDepsRequiringBuild:
true` install option (the napi engine did not implement it), so
`installResult.depsRequiringBuild` only carried *blocked* builds. Bit
allows dependency builds to run, so the list was always empty — and lynx
wrote that empty list over the recorded block on every install.

The fix:

- Preserve the previously recorded list whenever the engine returns no
list (`depsRequiringBuild` undefined): frozen-path repeat installs, and
engines that predate the option. Verified against the currently pinned
`@pnpm/napi` 12.0.0-beta.2 — a repeat install in this repo now leaves
the block byte-identical.
- Pass `returnListOfDepsRequiringBuild: true` again. Engine support was
added in pnpm/pnpm#13532, so the next `@pnpm/napi` release reports the
full list (every package whose files carry install scripts, regardless
of the allow-build policy) on fresh resolves — the same semantics the
pre-migration TypeScript engine had.

---
Written by an agent (Claude Code, claude-fable-5).

---------

Co-authored-by: Claude Fable 5 <[email protected]>
zkochan added a commit that referenced this pull request Aug 2, 2026
## Summary

`bit install` fails on any dependency that shells out to `node-gyp`:

```
.../node_modules/bufferutil install$ node-gyp-build
│ Error: spawn node-gyp ENOENT
[email protected] install: `node-gyp-build` exited with exit status: 1
```

The pnpm engine spawns dependency lifecycle scripts with the PATH of the
bit process plus the relevant `node_modules/.bin` dirs, and ships no
`node-gyp` of its own (`pacquet`'s `node_gyp_bin` / `node_gyp_path`
lifecycle options exist, but every caller passes `None`). Before #10508
Bit inherited a `node-gyp` wrapper from `@pnpm/npm-lifecycle`, which
depends on node-gyp and prepends its wrapper dir to PATH for every
script it spawns — the old lockfile had `[email protected]` through it,
the new one has none.

So anything that falls back to `node-gyp rebuild` — `node-gyp-build`
with no matching prebuild, `node-pre-gyp`, or a plain `"install":
"node-gyp rebuild"` — now dies with `spawn node-gyp ENOENT`. It shows up
on platforms a package has no prebuild for: `[email protected]` ships no
darwin-arm64 prebuild, so every Apple Silicon install of it fails.

## Changes

- **`node-gyp-bin.ts`** (new) — writes an npm-style `node-gyp` wrapper
into `<bit-cache>/node-gyp-bin/<key>` and appends it to
`process.env.PATH`. Appended rather than prepended, so a node-gyp the
user installed themselves still wins. The directory is keyed by a hash
of the `node` and `node-gyp.js` paths baked into the wrapper, so a Bit
or Node upgrade gets a fresh directory instead of rewriting a script a
concurrent install may be executing; wrappers are written
temp-file-then-rename. `process.env` is the only lever available here —
`InstallOptions` exposes no `extraBinPaths` (only `PackOptions` does).
- **`lynx.ts`** — call it once in `install()`, which covers both
`nodeApi.install` and the returned `rebuild`.
- **`workspace.jsonc`** — `node-gyp: 11.5.0` in the root policy and in a
new variant for `scopes/dependencies/pnpm`. The variant entry is
required: nothing imports node-gyp, so dependency detection would never
add it to `@teambit/pnpm`'s package.json. 11.x rather than 13.x because
node-gyp 13 requires Node `^22.22.2` and bvm ships 22.22.0.

The complete fix belongs upstream — `pacquet` already has the
`node_gyp_bin` plumbing, it just has nothing to point it at — but Bit
needs to ship a `node-gyp` either way.

## Test plan

- [x] `npm run lint`
- [x] `bit test scopes/dependencies/pnpm/node-gyp-bin.spec.ts` — 3/3
passing
- [x] Scratch workspace with `[email protected]` (`"install": "node-gyp
rebuild"`): released `bit` → `sh: line 1: node-gyp: command not found`,
exit 127. Local build → node-gyp runs (`node-gyp -v v11.5.0`, invoked as
`<node> <…>/node-gyp.js`); the compile then fails on its own merits,
since that 2016 nan addon does not build against Node 22.
- [x] Same workspace with `[email protected]` and
`npm_config_build_from_source=true` to force the gyp path: `bit install`
completes green and produces a real `build/Release/bufferutil.node`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Jinjiang added a commit to Jinjiang/bit-lite that referenced this pull request Aug 5, 2026
bit-lite-deps drove installs through @pnpm/core and friends. Those packages
are frozen on the v10 line and have no v11 or v12 release: pnpm moved its
install engine to Rust and now exposes it through @pnpm/napi instead. Latest
Bit made the same move (teambit/bit#10508, 2026-07-31), so this follows a
proven path rather than inventing one.

Replace the programmatic v10 API with @pnpm/napi:

- `nodeApi.install` receives a typed InstallOptions built from the same
  settings the old InstallOptions carried.
- Progress comes from the engine's log callback. The engine emits
  wire-compatible pnpm log records, so the parsing in progress.ts is
  unchanged and only the transport is new.
- The addon is loaded through createRequire: it is CommonJS, and Node's
  named-export detection only finds `install` on it.
- Local packages from an enclosing repository become `link:` overrides
  rather than projects. The engine has no equivalent of the old
  allProjects / mutations split, so a project is always an install target;
  overriding by name links without installing. Paths are relative so the
  generated lockfile stays portable.
- A `pnpm-workspace.yaml` is written to the install root. InstallOptions.dir
  is not authoritative: without the marker the engine walks up, adopts an
  enclosing pnpm workspace as its lockfile root, and prunes that
  repository's node_modules.

Behaviour differences worth noting: `excludeLinksFromLockfile` is dropped
because setting it stops the engine from linking workspace packages at all,
and `resolutionMode`, `preferWorkspacePackages`, `strictPeerDependencies`
and `modulesCacheMaxAge` have no counterpart in the binding.

Co-Authored-By: Claude Opus 5 <[email protected]>
Jinjiang added a commit to Jinjiang/bit-lite that referenced this pull request Aug 6, 2026
bit-lite-deps drove installs through @pnpm/core and friends. Those packages
are frozen on the v10 line and have no v11 or v12 release: pnpm moved its
install engine to Rust and now exposes it through @pnpm/napi instead. Latest
Bit made the same move (teambit/bit#10508, 2026-07-31), so this follows a
proven path rather than inventing one.

Replace the programmatic v10 API with @pnpm/napi:

- `nodeApi.install` receives a typed InstallOptions built from the same
  settings the old InstallOptions carried.
- Progress comes from the engine's log callback. The engine emits
  wire-compatible pnpm log records, so the parsing in progress.ts is
  unchanged and only the transport is new.
- The addon is loaded through createRequire: it is CommonJS, and Node's
  named-export detection only finds `install` on it.
- Local packages from an enclosing repository become `link:` overrides
  rather than projects. The engine has no equivalent of the old
  allProjects / mutations split, so a project is always an install target;
  overriding by name links without installing. Paths are relative so the
  generated lockfile stays portable.
- A `pnpm-workspace.yaml` is written to the install root. InstallOptions.dir
  is not authoritative: without the marker the engine walks up, adopts an
  enclosing pnpm workspace as its lockfile root, and prunes that
  repository's node_modules.

Behaviour differences worth noting: `excludeLinksFromLockfile` is dropped
because setting it stops the engine from linking workspace packages at all,
and `resolutionMode`, `preferWorkspacePackages`, `strictPeerDependencies`
and `modulesCacheMaxAge` have no counterpart in the binding.

Co-Authored-By: Claude Opus 5 <[email protected]>
Jinjiang added a commit to Jinjiang/bit-lite that referenced this pull request Aug 6, 2026
bit-lite-deps drove installs through @pnpm/core and friends. Those packages
are frozen on the v10 line and have no v11 or v12 release: pnpm moved its
install engine to Rust and now exposes it through @pnpm/napi instead. Latest
Bit made the same move (teambit/bit#10508, 2026-07-31), so this follows a
proven path rather than inventing one.

Replace the programmatic v10 API with @pnpm/napi:

- `nodeApi.install` receives a typed InstallOptions built from the same
  settings the old InstallOptions carried.
- Progress comes from the engine's log callback. The engine emits
  wire-compatible pnpm log records, so the parsing in progress.ts is
  unchanged and only the transport is new.
- The addon is loaded through createRequire: it is CommonJS, and Node's
  named-export detection only finds `install` on it.
- Local packages from an enclosing repository become `link:` overrides
  rather than projects. The engine has no equivalent of the old
  allProjects / mutations split, so a project is always an install target;
  overriding by name links without installing. Paths are relative so the
  generated lockfile stays portable.
- A `pnpm-workspace.yaml` is written to the install root. InstallOptions.dir
  is not authoritative: without the marker the engine walks up, adopts an
  enclosing pnpm workspace as its lockfile root, and prunes that
  repository's node_modules.

Behaviour differences worth noting: `excludeLinksFromLockfile` is dropped
because setting it stops the engine from linking workspace packages at all,
and `resolutionMode`, `preferWorkspacePackages`, `strictPeerDependencies`
and `modulesCacheMaxAge` have no counterpart in the binding.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants