Skip to content

fix: keep bundled dependency fields out of the published pnpm manifest - #12964

Merged
zkochan merged 4 commits into
mainfrom
fix-12955
Jul 13, 2026
Merged

zkochan merged 4 commits into
mainfrom
fix-12955

Conversation

@zkochan

@zkochan zkochan commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Summary

The published [email protected] broke npm install --omit=dev --omit=optional on its own tarball: the manifest declared dependencies and a large devDependencies list of internal-only packages (e.g. @pnpm/[email protected]) that aren't on the public registry, so the install 404s. 11.11.0 published with neither field.

Root cause: the pnpm package bundles its runtime deps into dist/node_modules, so its manifest is meant to be dep-less — the workspace .pnpmfile.cjs beforePacking hook strips dependencies/devDependencies when packing. The 11.12.0 release ran a pnpm 12 alpha (pacquet) that does not yet honor beforePacking, so the fields leaked into the published manifest.

This fixes the pnpm 12 gap and adds a stopgap for it:

  1. Rust (pacquet) — pacquet now honors beforePacking pnpmfile hooks during pack/publish. Once the release runs a pnpm that includes this, the hook drops the fields as intended.
  2. TypeScript (temporary workaround) — until the release runs such a pnpm, bundle-deps.ts (the CLI's prepublishOnly) strips dependencies/devDependencies from the on-disk manifest after building the bundle. pack re-reads the manifest after prepublishOnly, so the fields never reach the tarball. This on-disk strip can be removed once the release publishes with a beforePacking-aware pnpm.

Closes #12955.

A sibling symptom in the issue comments — empty @pnpm/macos-arm64 tarballs missing the native binary — is a separate pacquet pack/build bug from the same bad release and is not addressed here.

Squash Commit Body

The published pnpm package bundles its runtime dependencies into
dist/node_modules, so its manifest must not declare dependencies or
devDependencies — otherwise pnpm installs them a second time, and the
internal-only devDependencies (e.g. @pnpm/test-ipc-server) aren't
published, so the install 404s. pnpm 11.11.0 published with neither field.

The workspace .pnpmfile.cjs beforePacking hook drops these fields when
packing, but the release for 11.12.0 ran a pnpm 12 alpha (pacquet) that
does not yet honor beforePacking, so the fields leaked into the published
manifest and broke installs.

This fixes the pnpm 12 gap and adds a stopgap for it:

1. pacquet now honors beforePacking pnpmfile hooks during pack/publish,
   so once the release runs a pnpm that includes this, the hook drops the
   fields as intended:
   - PnpmfileHooks::before_packing (trait default no-op) plus a worker JS
     branch and NodeJsHooks impl, called as beforePacking(pkg, dir, ctx)
     with pnpm's `?? manifest` fallback.
   - pack::api is now async; it loads the workspace-root and
     config-dependency pnpmfiles (via a resolve_pnpmfile_paths helper
     shared with the updateConfig hook) and applies beforePacking to the
     published manifest before the file list is computed. The async change
     ripples through pack::run, dispatch_query::pack, publish, and napi.

2. As a temporary workaround until the release runs such a pnpm,
   bundle-deps.ts (the CLI's prepublishOnly) strips dependencies and
   devDependencies from the on-disk manifest after building the bundle.
   pack re-reads the manifest after prepublishOnly, so the fields never
   reach the tarball regardless of the beforePacking gap.

Integration tests drive the real binary through pnpm pack with a
.pnpmfile.cjs beforePacking hook, including the release shape a
workspace-root pnpmfile applied to a --filter-selected sub-package.

Closes pnpm/pnpm#12955.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port. (Rust: beforePacking bridge — the actual fix; TS: bundle-deps.ts stopgap until the release runs a beforePacking-aware pnpm.)
  • Added changesets. This is a parity change, so the two stacks get separate changesets (different release notes): "pnpm": patch for the published-manifest dependency strip, and "pacquet": patch for pacquet applying the beforePacking hook (@pnpm/napi bumps with pacquet via its fixed group).
  • Added or updated tests. (Rust pnpm/crates/cli/tests/pack.rs end-to-end beforePacking tests; updated pack/publish unit tests for the async pack::api.)
  • Updated the documentation if needed.

Written by an agent (Claude Code, claude-opus-4-8[1m]).

Summary by CodeRabbit

  • New Features
    • pnpm pack and pnpm publish now apply beforePacking hooks to package manifests before creating archives, including workspace-level hooks.
  • Bug Fixes
    • Pack and publish output now correctly reflects manifest changes made by beforePacking hooks.
    • Published tarballs no longer include dependencies/devDependencies that could cause installs to pull internal-only packages.
  • Error Handling
    • Packing now reports clear failures when a beforePacking hook fails.

Copilot AI review requested due to automatic review settings July 13, 2026 09:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds asynchronous beforePacking hook execution to Rust-based pack and publish flows, resolves pnpmfiles for packing, updates tests and N-API handling, and removes dependency fields from the pnpm 11 bundled manifest.

Changes

Packing hooks and published manifests

Layer / File(s) Summary
beforePacking hook runtime
pnpm/crates/hooks/src/*
Adds the async before_packing trait method and forwards hook calls through the Node runtime and worker IPC protocol.
Async pack orchestration
pnpm/crates/pack/*, pnpm/crates/napi/src/pack.rs, .changeset/pacquet-before-packing-hook.md
Adds ordered hooks to PackOptions, applies them before packlist computation, reports failures, and adapts callers and tests to the async API.
CLI integration and pnpmfile resolution
pnpm/crates/cli/src/cli_args/*, pnpm/crates/cli/src/config_deps.rs, pnpm/crates/cli/tests/pack.rs
Resolves pnpmfiles for pack and publish commands, awaits packing operations, and verifies hook-modified manifests in generated tarballs.
Bundled pnpm manifest stripping
pnpm11/pnpm/bundle-deps.ts, .changeset/pnpm-publish-strip-bundled-deps.md
Removes dependencies and devDependencies from the bundled pnpm manifest after generating dist/node_modules.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant PackApi
  participant NodeHooks
  participant Pnpmfile
  participant Tarball
  CLI->>PackApi: api(PackOptions with hooks)
  PackApi->>NodeHooks: apply beforePacking
  NodeHooks->>Pnpmfile: beforePacking(manifest, dir, context)
  Pnpmfile-->>NodeHooks: updated manifest
  NodeHooks-->>PackApi: transformed manifest
  PackApi->>Tarball: compute packlist and write tarball
Loading

Assessment against linked issues

Objective Addressed Explanation
Fix the pnpm 11.12.0 tarball so installation succeeds after extraction [#12955] ✅
Remove the install-time dependency on @pnpm/[email protected] [#12955] ✅
Preserve successful pnpm 11.11.0 tarball installation behavior [#12955] ❓ The manifest fields are removed, but the diff does not demonstrate a complete npm install verification.

Out-of-scope changes

Code Change Explanation
Add beforePacking hook runtime dispatch (pnpm/crates/hooks/src/lib.rs:102-122, pnpm/crates/hooks/src/node_runtime.rs:290-298, pnpm/crates/hooks/src/worker.rs:157-174,392-395) Implements hook execution beyond the linked tarball-install objective.
Apply pnpmfile hooks during pacquet packing (pnpm/crates/pack/src/lib.rs:91-402) Changes packed manifests through a separate hook feature, not specifically the pnpm 11 dependency metadata fix.
Add CLI pack/publish hook integration and async plumbing (pnpm/crates/cli/src/cli_args/*, pnpm/crates/cli/tests/pack.rs) Supports the broader beforePacking feature rather than the linked installation objective.

Possibly related PRs

  • pnpm/pnpm#12044 — Provides related pnpmfile hook execution infrastructure.
  • pnpm/pnpm#12805 — Also changes beforePacking behavior and dependency-field stripping.
  • pnpm/pnpm#12822 — Adds the N-API pack binding updated for the async pack API.

Suggested labels: product: pacquet, product: pnpm@11

Suggested reviewers: ksxgithub, qodo-free-for-open-source-projects

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-12955

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

pnpm11/pnpm/bundle-deps.ts

Parsing error: "parserOptions.project" has been provided for @typescript-eslint/parser.
The file was not found in any of the provided project(s): pnpm11/pnpm/bundle-deps.ts


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix published pnpm manifest to omit bundled dependency fields across pnpm & pacquet

🐞 Bug fix 🧪 Tests ✨ Enhancement 🕐 40+ Minutes

Grey Divider

AI Description

• Strip dependencies/devDependencies from pnpm’s on-disk manifest during prepublish bundling
• Make pacquet honor .pnpmfile.cjs beforePacking hooks during pack/publish
• Add end-to-end pack tests proving hook-applied manifest rewrites reach the tarball
Diagram

graph TD
  tsPrepublish["bundle-deps.ts (prepublishOnly)"] --> pkgJson["package.json (stripped)"]
  pkgJson --> packApi["pacquet_pack::api"]
  pacquetCli["pacquet CLI (pack/publish)"] --> packApi --> tarball[".tgz tarball"]
  packApi --> worker["Hooks worker (Node)"] --> pnpmfile(("beforePacking hook"))

  subgraph Legend
    direction LR
    _cli["CLI/component"] ~~~ _file["File"] ~~~ _hook(("Hook"))
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Fix only pacquet hook parity (rely on beforePacking)
  • ➕ Single source of truth: .pnpmfile.cjs controls manifest rewriting
  • ➕ Avoids mutating package.json on disk during prepublishOnly
  • ➖ Still fragile if publishing is done by a tool that doesn’t load hooks correctly
  • ➖ Harder to reason about because correctness depends on external tool behavior
2. Hard-code pnpm-package-specific sanitization in pack/publish
  • ➕ Very robust for the pnpm package regardless of hooks
  • ➕ Potentially simpler than general hook execution
  • ➖ Special-cases one package in shared tooling
  • ➖ Doesn’t help other workspaces relying on beforePacking semantics
3. Move bundled dependency stripping into exportable-manifest generation
  • ➕ Keeps all publish-manifest shaping in one place
  • ➕ Reduces API async ripple in pack layer
  • ➖ Requires threading hook execution into a currently pure/sync transform
  • ➖ Broader refactor risk across manifest/export consumers

Recommendation: The PR’s dual-layer defense is the best tradeoff: strip dependency fields directly during pnpm’s prepublish (so any publisher produces a correct tarball), and also close the pacquet parity gap by honoring beforePacking (so workspace hook semantics match pnpm). The alternatives either reintroduce publisher fragility or require undesirable special-casing/refactoring.

Files changed (16) +358 / -35

Enhancement (4) +60 / -3
pack.rsMake PackArgs::run async and pass pnpmfile paths into pack options +8/-3

Make PackArgs::run async and pass pnpmfile paths into pack options

• Converts pack execution (single and recursive) to async and threads resolved pnpmfile paths into PackOptions so beforePacking hooks can run during packing.

pnpm/crates/cli/src/cli_args/pack.rs

lib.rsAdd before_packing hook to PnpmfileHooks trait +21/-0

Add before_packing hook to PnpmfileHooks trait

• Introduces an async before_packing hook with a default no-op implementation, defining when it runs and how manifest return values are interpreted.

pnpm/crates/hooks/src/lib.rs

node_runtime.rsBridge NodeJsHooks to call beforePacking via worker +9/-0

Bridge NodeJsHooks to call beforePacking via worker

• Implements before_packing for the NodeJsHooks runtime by forwarding the call to the JS worker IPC layer.

pnpm/crates/hooks/src/node_runtime.rs

worker.rsImplement worker support for beforePacking IPC and null fallback +22/-0

Implement worker support for beforePacking IPC and null fallback

• Adds a new worker request path for beforePacking that returns the original manifest when the hook is missing or returns null/undefined, matching pnpm semantics.

pnpm/crates/hooks/src/worker.rs

Bug fix (4) +90 / -5
dispatch.rsFix pack dispatch to pass owned PackArgs +1/-1

Fix pack dispatch to pass owned PackArgs

• Adjusts dispatch wiring for the pack command to pass PackArgs by value, aligning with the new async execution flow.

pnpm/crates/cli/src/cli_args/dispatch.rs

publish.rsMake publish packing async and include pnpmfile hook sources +6/-2

Make publish packing async and include pnpmfile hook sources

• Updates publish’s internal pack step to await the async pack API and to supply the same pnpmfile set used by install/config hooks.

pnpm/crates/cli/src/cli_args/publish.rs

lib.rsRun beforePacking hook chain before computing packlist; make api async +64/-2

Run beforePacking hook chain before computing packlist; make api async

• Makes the pack API async and applies configured pnpmfile beforePacking hooks to the exportable manifest before packlist computation, with structured hook logging and error reporting.

pnpm/crates/pack/src/lib.rs

bundle-deps.tsStrip dependencies and devDependencies from pnpm manifest after bundling +19/-0

Strip dependencies and devDependencies from pnpm manifest after bundling

• After creating dist/node_modules, removes dependencies and devDependencies from the on-disk package.json so the published tarball is dependency-less regardless of publisher hook support.

pnpm11/pnpm/bundle-deps.ts

Refactor (3) +42 / -22
dispatch_query.rsMake pack command execution async to support beforePacking hooks +19/-17

Make pack command execution async to support beforePacking hooks

• Refactors pack dispatch to return an async future and await pack execution, since packing may now invoke pnpmfile hooks.

pnpm/crates/cli/src/cli_args/dispatch_query.rs

config_deps.rsFactor pnpmfile path resolution into shared helper +16/-4

Factor pnpmfile path resolution into shared helper

• Extracts resolve_pnpmfile_paths() so both updateConfig and beforePacking flows apply the same pnpmfile list and ordering.

pnpm/crates/cli/src/config_deps.rs

pack.rsAdapt N-API pack bridge to async pack API +7/-1

Adapt N-API pack bridge to async pack API

• Updates the Node N-API bridge to drive the now-async pack API to completion on a blocking thread, and sets pnpmfiles to empty for the Bit use-case.

pnpm/crates/napi/src/pack.rs

Tests (3) +159 / -5
tests.rsConvert publish pack-for-publish test to tokio async +3/-2

Convert publish pack-for-publish test to tokio async

• Updates the unit test to use an async runtime and await the new async packing helper.

pnpm/crates/cli/src/cli_args/publish/tests.rs

pack.rsAdd integration tests for beforePacking manifest rewrites +136/-0

Add integration tests for beforePacking manifest rewrites

• Adds end-to-end tests that run the real pack binary and assert beforePacking can delete dependency fields and that workspace-root pnpmfile hooks apply to filtered subpackages.

pnpm/crates/cli/tests/pack.rs

tests.rsWrap async pack API for sync tests and extend fixtures with pnpmfiles +20/-3

Wrap async pack API for sync tests and extend fixtures with pnpmfiles

• Adds a small tokio runtime wrapper so existing synchronous tests can call the async API, and updates PackOptions fixtures to include the new pnpmfiles field.

pnpm/crates/pack/src/tests.rs

Other (2) +7 / -0
pnpm-publish-strip-bundled-deps.mdAdd patch changeset for published pnpm manifest fix +5/-0

Add patch changeset for published pnpm manifest fix

• Introduces a patch changeset documenting that the published pnpm package no longer exposes dependencies/devDependencies that should not be installed by consumers.

.changeset/pnpm-publish-strip-bundled-deps.md

Cargo.tomlAdd pacquet-hooks dependency and tokio for tests +2/-0

Add pacquet-hooks dependency and tokio for tests

• Pulls in pacquet-hooks for pnpmfile loading/execution and adds tokio as a dev dependency to support async tests/helpers.

pnpm/crates/pack/Cargo.toml

Copilot AI review requested due to automatic review settings July 13, 2026 09:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

qodo-code-review Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 8bdec82

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
Possible issue
Avoid permanently corrupting source manifests

Restore the original package.json after stripping dependencies to prevent
permanent modifications to the source tree. Consider moving this logic to a
context where it can be safely restored without disrupting the build pipeline.

pnpm11/pnpm/bundle-deps.ts [124-132]

-function stripBundledDependenciesFromManifest () {
-  const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
+function packWithStrippedBundledDependencies () {
+  const originalManifest = fs.readFileSync(MANIFEST_PATH, 'utf8')
+  const manifest = JSON.parse(originalManifest)
   delete manifest.dependencies
   delete manifest.devDependencies
-  fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
+
+  try {
+    fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
+    execSync('pnpm pack', { cwd: import.meta.dirname, stdio: 'inherit' })
+  } finally {
+    fs.writeFileSync(MANIFEST_PATH, originalManifest)
+  }
 }
 
 createDistNodeModules()
-stripBundledDependenciesFromManifest()
+packWithStrippedBundledDependencies()
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out that permanently rewriting the source package.json can corrupt local workflows, although the proposed solution to run pnpm pack directly inside this script could disrupt the build pipeline or cause loops if it is invoked via a prepack hook.

Low
  • More

Previous suggestions

Suggestions up to commit 77812a5
CategorySuggestion                                                                                                                                    Impact
High-level
Spawning a Node worker per packed package

Calling finder::load_pnpmfile_at inside apply_before_packing creates a new
NodeJsHooks instance for every package during a recursive pack, severely
impacting performance. The suggestion recommends loading the hooks once and
sharing an Arc across all packages via PackOptions.

Examples:

pnpm/crates/pack/src/lib.rs [358-377]
async fn apply_before_packing<Reporter: self::Reporter>(
    project_dir: &Path,
    publish_dir: &Path,
    mut manifest: Value,
    pnpmfiles: &[PathBuf],
) -> Result<Value, PackError> {
    let prefix = project_dir.to_string_lossy();
    for pnpmfile in pnpmfiles {
        let hooks = finder::load_pnpmfile_at(pnpmfile.clone());
        let ctx =

 ... (clipped 10 lines)

Solution Walkthrough:

Before:

async fn apply_before_packing<Reporter: self::Reporter>(
    project_dir: &Path,
    publish_dir: &Path,
    mut manifest: Value,
    pnpmfiles: &[PathBuf],
) -> Result<Value, PackError> {
    let prefix = project_dir.to_string_lossy();
    for pnpmfile in pnpmfiles {
        let hooks = finder::load_pnpmfile_at(pnpmfile.clone()); // Creates NodeJsHooks, spawning a new Node process
        let ctx = HookContext { log: before_packing_logger::<Reporter>(pnpmfile, &prefix), dir: None };
        manifest = hooks.before_packing(manifest, publish_dir, ctx).await?;
    }
    Ok(manifest)
}

After:

async fn apply_before_packing<Reporter: self::Reporter>(
    project_dir: &Path,
    publish_dir: &Path,
    mut manifest: Value,
    pnpmfile_hooks: &[(PathBuf, Arc<dyn PnpmfileHooks>)],
) -> Result<Value, PackError> {
    let prefix = project_dir.to_string_lossy();
    for (pnpmfile, hooks) in pnpmfile_hooks {
        let ctx = HookContext { log: before_packing_logger::<Reporter>(pnpmfile, &prefix), dir: None };
        manifest = hooks.before_packing(manifest, publish_dir, ctx).await?;
    }
    Ok(manifest)
}
Suggestion importance[1-10]: 9

__

Why: Identifies a major performance flaw that defeats the purpose of the long-lived Node worker design by inadvertently spawning a new Node process for each workspace package.

High
In-place package.json modification leaves git dirty

The PR modifies package.json in-place within bundle-deps.ts which permanently
removes dependencies and devDependencies locally, leaving git dirty and breaking
subsequent local development. The suggestion recommends restoring the manifest
in a postpack script or relying entirely on beforePacking.

Examples:

pnpm11/pnpm/bundle-deps.ts [123-128]
function stripBundledDependenciesFromManifest () {
  const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
  delete manifest.dependencies
  delete manifest.devDependencies
  fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
}

Solution Walkthrough:

Before:

function stripBundledDependenciesFromManifest () {
  const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
  delete manifest.dependencies
  delete manifest.devDependencies
  fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
}

After:

function stripBundledDependenciesFromManifest () {
  const manifestContent = fs.readFileSync(MANIFEST_PATH, 'utf8')
  fs.writeFileSync(`${MANIFEST_PATH}.backup`, manifestContent) // Add backup for a postpack script to restore
  
  const manifest = JSON.parse(manifestContent)
  delete manifest.dependencies
  delete manifest.devDependencies
  fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
}
Suggestion importance[1-10]: 7

__

Why: Highlights a valid local developer experience issue caused by permanently modifying package.json, which could disrupt the workflow for contributors.

Medium
General
Drop bundleDependencies fields

Remove bundleDependencies and bundledDependencies fields from the manifest to
prevent potential metadata issues.

pnpm11/pnpm/bundle-deps.ts [123-128]

 function stripBundledDependenciesFromManifest () {
   const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
   delete manifest.dependencies
   delete manifest.devDependencies
+  delete manifest.bundleDependencies
+  delete manifest.bundledDependencies
   fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
 }
Suggestion importance[1-10]: 3

__

Why: While pnpm's source manifest may not declare bundleDependencies, removing these fields serves as a harmless defensive measure to prevent unintended resolution metadata.

Low

The published `pnpm` package bundles its runtime dependencies into
`dist/node_modules`, so its manifest must not declare `dependencies` or
`devDependencies` — otherwise pnpm installs them a second time, and the
internal-only devDependencies (e.g. `@pnpm/test-ipc-server`) aren't
published, so the install 404s. pnpm 11.11.0 published with neither field.

The workspace `.pnpmfile.cjs` `beforePacking` hook drops these fields when
packing, but the release for 11.12.0 ran a pnpm 12 alpha (pacquet) that
does not yet honor `beforePacking`, so the fields leaked into the published
manifest and broke installs.

This fixes the pnpm 12 gap and adds a stopgap for it:

1. pacquet now honors `beforePacking` pnpmfile hooks during pack/publish,
   so once the release runs a pnpm that includes this, the hook drops the
   fields as intended:
   - PnpmfileHooks::before_packing (trait default no-op) plus a worker JS
     branch and NodeJsHooks impl, called as `beforePacking(pkg, dir, ctx)`
     with pnpm's `?? manifest` fallback.
   - pack::api is now async; it loads the workspace-root and
     config-dependency pnpmfiles (via a resolve_pnpmfile_paths helper
     shared with the updateConfig hook) and applies beforePacking to the
     published manifest before the file list is computed, so a hook may
     still change files/bin/dependency fields. The async change ripples
     through pack::run, dispatch_query::pack, publish, and the napi bridge.

2. As a temporary workaround until the release runs such a pnpm,
   bundle-deps.ts (the CLI's prepublishOnly) strips dependencies and
   devDependencies from the on-disk manifest after building the bundle.
   pack re-reads the manifest after prepublishOnly, so the fields never
   reach the tarball regardless of the beforePacking gap.

Integration tests drive the real binary through `pnpm pack` with a
`.pnpmfile.cjs` beforePacking hook, including the release shape a
workspace-root pnpmfile applied to a `--filter`-selected sub-package.

Closes #12955.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     24.7±0.26ms    15.2 MB/sec    1.00     24.8±0.29ms    15.1 MB/sec
packument/parse                1.00     79.1±1.24µs   838.4 MB/sec    1.00     79.2±3.33µs   837.7 MB/sec
tarball/download_dependency    1.03      7.1±0.37ms   611.5 KB/sec    1.00      6.9±0.30ms   632.6 KB/sec

@qodo-code-review

qodo-code-review Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (1) 📎 Requirement gaps (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. stripBundledDependenciesFromManifest declared too early ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
In bundle-deps.ts, stripBundledDependenciesFromManifest() is declared before its first usage in
the same file. This violates the rule requiring TypeScript function declarations to appear only
after their first usage.
Code

pnpm11/pnpm/bundle-deps.ts[R124-132]

+function stripBundledDependenciesFromManifest () {
+  const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
+  delete manifest.dependencies
+  delete manifest.devDependencies
+  fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
+}
+
createDistNodeModules()
+stripBundledDependenciesFromManifest()
Evidence
The function declaration at lines 124-129 precedes its first usage at line 132, which matches the
rule’s failure condition (declaration before any call site in-file).

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/pnpm/bundle-deps.ts[124-132]

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

## Issue description
A top-level TypeScript function declaration appears before its first call site, which violates the repo’s ordering rule for function declarations.

## Issue Context
The rule applies to `function foo(...) {}` declarations in `.ts` files. The function is called later in the same file, but no call appears before the declaration.

## Fix Focus Areas
- pnpm11/pnpm/bundle-deps.ts[124-132]

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



Remediation recommended

2. Unvalidated beforePacking result 🐞 Bug ⛨ Security ⭐ New
Description
beforePacking hook results are accepted even when they are not JSON objects, and pacquet then uses
that value as the publish manifest. A hook returning a string/array can silently disable
manifest-driven packing behavior (e.g. files/bin handling) and produce incorrect tarball
contents or malformed output instead of failing fast.
Code

pnpm/crates/hooks/src/worker.rs[R392-395]

+    }} else if (req.hook === 'beforePacking') {{
+      if (typeof fn !== 'function') {{ send({{ ok: req.payload }}); return; }}
+      const newPkg = await fn(req.payload, req.dir, context);
+      send({{ ok: newPkg == null ? req.payload : newPkg }});
Evidence
The worker’s beforePacking path forwards arbitrary non-nullish return values without validation,
and the pack pipeline then uses that value as the manifest. Downstream, fs-packlist relies on
manifest.get("files")/get("bin"); for non-object manifests these lookups return None, changing
what gets packed rather than producing a clear hook error.

pnpm/crates/hooks/src/worker.rs[381-402]
pnpm/crates/pack/src/lib.rs[353-376]
pnpm/crates/fs-packlist/src/lib.rs[114-117]
pnpm/crates/fs-packlist/src/lib.rs[273-285]

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 `beforePacking` hook bridge forwards any non-nullish return value from JS back into Rust, and `pacquet_pack` then treats it as the manifest without validation. If a pnpmfile/plugin accidentally returns a non-object (string/number/array), subsequent packing logic will read manifest fields via `manifest.get(...)` (which returns `None` for non-objects), causing manifest-driven packing behavior (like `files` allowlists and `bin` detection) to be skipped/altered instead of producing a clear error.

### Issue Context
- The worker’s `readPackage` hook includes shape validation, but `beforePacking` currently does not.
- `fs-packlist` uses `manifest.get("files")`/`get("bin")` to decide what to include; with a non-object manifest these become absent and packing behavior changes.

### Fix Focus Areas
- pnpm/crates/hooks/src/worker.rs[392-395]
- pnpm/crates/pack/src/lib.rs[358-375]
- pnpm/crates/fs-packlist/src/lib.rs[114-116]
- pnpm/crates/fs-packlist/src/lib.rs[273-285]

### Suggested fix
1. In the Node worker `beforePacking` branch, validate the hook’s return value:
  - Keep the existing `null`/`undefined` fallback (`newPkg == null ? req.payload : newPkg`).
  - If `newPkg` is non-nullish but not a plain object (`typeof newPkg !== 'object' || Array.isArray(newPkg)`), throw an error (similar to `readPackage` validation) so packing fails loudly.
2. Add a Rust-side defense-in-depth check in `apply_before_packing` to ensure `manifest.is_object()` after each hook application; if not, return a `PackError::BeforePacking` with a clear message.
3. Add a regression test covering a `beforePacking` hook that returns an invalid type (e.g. string/array) and assert that `pack` fails with the expected error.

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


3. Pnpmfile workers not reused ✓ Resolved 🐞 Bug ➹ Performance
Description
apply_before_packing constructs a fresh hooks instance for each pnpmfile path on every packed
project, so recursive workspace packs can repeatedly spawn new Node hook workers per project. This
can add significant latency and resource usage for large workspaces packing many projects with the
same pnpmfiles.
Code

pnpm/crates/pack/src/lib.rs[R358-376]

+async fn apply_before_packing<Reporter: self::Reporter>(
+    project_dir: &Path,
+    publish_dir: &Path,
+    mut manifest: Value,
+    pnpmfiles: &[PathBuf],
+) -> Result<Value, PackError> {
+    let prefix = project_dir.to_string_lossy();
+    for pnpmfile in pnpmfiles {
+        let hooks = finder::load_pnpmfile_at(pnpmfile.clone());
+        let ctx =
+            HookContext { log: before_packing_logger::<Reporter>(pnpmfile, &prefix), dir: None };
+        manifest = hooks.before_packing(manifest, publish_dir, ctx).await.map_err(|err| {
+            PackError::BeforePacking {
+                pnpmfile: pnpmfile.display().to_string(),
+                message: err.to_string(),
+            }
+        })?;
+    }
+    Ok(manifest)
Evidence
The pack path loads pnpmfiles anew per project; load_pnpmfile_at always constructs a new
NodeJsHooks, and NodeJsHooks only caches its worker per instance, so repeated construction
prevents worker reuse.

pnpm/crates/pack/src/lib.rs[358-376]
pnpm/crates/hooks/src/finder.rs[27-33]
pnpm/crates/hooks/src/node_runtime.rs[12-37]
pnpm/crates/cli/src/cli_args/pack.rs[216-235]

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

### Issue description
Recursive pack calls `pacquet_pack::api` once per project. The new `beforePacking` support reloads pnpmfiles into new `NodeJsHooks` instances per project, defeating the per-instance worker reuse and potentially spawning many `node` workers.

### Issue Context
- `apply_before_packing` calls `finder::load_pnpmfile_at(...)` inside the per-pack loop.
- `load_pnpmfile_at` creates a new `NodeJsHooks`, whose worker cache is per instance.

### Fix Focus Areas
- pnpm/crates/pack/src/lib.rs[358-376]
- pnpm/crates/hooks/src/finder.rs[27-33]
- pnpm/crates/hooks/src/node_runtime.rs[12-37]
- pnpm/crates/cli/src/cli_args/pack.rs[216-235]

### Suggested fix
Introduce reuse across projects, e.g.:
- Build a cache of `Arc<dyn PnpmfileHooks>` keyed by pnpmfile path (per-command or process-global), and have `apply_before_packing` reuse cached hook instances.
- In recursive pack, compute `pnpmfiles` once and thread it through `pack_options` instead of resolving per project (reduces filesystem churn even if hooks are cached elsewhere).

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


4. Historical comment in bundle-deps.ts 📘 Rule violation ⚙ Maintainability
Description
New comments describe past release behavior and future cleanup (e.g., “temporary workaround”,
“published 11.12.0…”, “Remove this once…”), rather than only the current contract. This violates the
requirement to keep inline comments focused on current behavior and can quickly become misleading.
Code

pnpm11/pnpm/bundle-deps.ts[R119-123]

+// The workspace .pnpmfile.cjs beforePacking hook already drops these fields when
+// packing. This on-disk strip is a temporary workaround for pnpm/pnpm#12955: the
+// pnpm v12 alpha that currently runs the release does not yet honor beforePacking,
+// so it published 11.12.0 with the fields intact. Remove this once the release
+// runs a pnpm that applies the hook.
Evidence
The added comment explicitly references past release behavior and a future removal plan (“temporary
workaround”, “published 11.12.0…”, “Remove this once…”), which is exactly the historical/temporal
commentary the checklist rule prohibits.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/pnpm/bundle-deps.ts[119-123]

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

## Issue description
A newly added comment block uses historical/temporal phrasing (e.g., “temporary workaround”, “published 11.12.0…”, “Remove this once…”) instead of documenting the current behavior/contract.

## Issue Context
Per the rule, inline comments should describe current behavior and rationale, not past implementations or future migration/removal notes.

## Fix Focus Areas
- pnpm11/pnpm/bundle-deps.ts[113-123]

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


View more (2)
5. Hook version path bypass 🐞 Bug ⛨ Security
Description
pacquet_pack::api validates the on-disk package.json version for path separators, but after
beforePacking it derives published_version from the hook-mutated manifest and passes it into
resolve_output. A beforePacking hook can inject / or \ so --out templates derive a parent
pack_destination (e.g. ..) and write the tarball outside the caller’s expected directory.
Code

pnpm/crates/pack/src/lib.rs[R282-293]

+    // Run `beforePacking` hooks against the built manifest, before the
+    // file list is computed, so a hook that rewrites `files` / `bin` /
+    // dependency fields is honored. pnpm runs it inside
+    // `createExportableManifest`; pacquet applies it here because
+    // `create_exportable_manifest` is a pure, synchronous transform.
+    publish_manifest =
+        apply_before_packing::<Reporter>(&opts.dir, &dir, publish_manifest, &opts.pnpmfiles)
+            .await?;
+
    // Strip semver build metadata (the `+<build>` segment) so the
    // tarball name, the packed manifest, and any registry metadata all
    // agree on the version. See pnpm/pnpm#11518.
Evidence
The code only validates the pre-hook version for path separators, then runs beforePacking and
recomputes published_version from the hook-mutated manifest; resolve_output derives a
destination directory from the parent of the --out template expansion.

pnpm/crates/pack/src/lib.rs[255-303]
pnpm/crates/pack/src/lib.rs[585-610]
pnpm/crates/pack/src/lib.rs[282-289]

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

### Issue description
`beforePacking` can mutate the published manifest's `version`, but the post-hook `published_version` is used for output path/template expansion without re-applying the path-separator validation that exists for the pre-hook version.

### Issue Context
- Pre-hook validation rejects `/` and `\\` in the original `version`.
- After `beforePacking`, `published_version` is recomputed from the (possibly modified) manifest and fed into `resolve_output`, which can turn path separators into a parent `pack_destination` when `--out` is used.

### Fix Focus Areas
- pnpm/crates/pack/src/lib.rs[255-303]
- pnpm/crates/pack/src/lib.rs[585-610]

### Suggested fix
After `apply_before_packing` and `strip_build_metadata`, re-run the same separator validation on `published_version` (and return `PackError::InvalidPackageVersion` on failure) before calling `resolve_output`.

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


6. Hook log escape injection 🐞 Bug ⛨ Security
Description
before_packing_logger forwards context.log(...) output into HookLog.message without stripping
control characters, and the default terminal reporter prints the message directly. A malicious
beforePacking hook can emit ANSI escape sequences to spoof or hide CLI output during
pack/publish.
Code

pnpm/crates/pack/src/lib.rs[R379-392]

+/// A `context.log(...)` sink forwarding each `beforePacking` log line to
+/// the `pnpm:hook` channel, tagged with the pnpmfile it came from.
+fn before_packing_logger<Reporter: self::Reporter>(pnpmfile: &Path, prefix: &str) -> LogFn {
+    let from = pnpmfile.to_string_lossy().into_owned();
+    let prefix = prefix.to_owned();
+    Arc::new(move |message| {
+        Reporter::emit(&LogEvent::Hook(HookLog {
+            level: LogLevel::Debug,
+            from: from.clone(),
+            hook: "beforePacking".to_string(),
+            prefix: prefix.clone(),
+            message,
+        }));
+    })
Evidence
before_packing_logger emits the raw hook message, and the default reporter concatenates
log.message into terminal output without escaping/sanitizing.

pnpm/crates/pack/src/lib.rs[379-392]
pnpm/crates/default-reporter/src/state.rs[1056-1063]

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

### Issue description
Hook-provided log strings are rendered to the terminal without sanitization, allowing control/escape sequences to alter terminal output.

### Issue Context
- `before_packing_logger` emits `LogEvent::Hook` with the hook-controlled `message`.
- `DefaultReporter` formats `HookLog` as `<hook>: <message>` and pushes it to terminal output.

### Fix Focus Areas
- pnpm/crates/pack/src/lib.rs[379-392]
- pnpm/crates/default-reporter/src/state.rs[1056-1063]

### Suggested fix
Sanitize `message` for terminal output (e.g., strip control chars like the pack output sanitizer does) either:
1) at emission time in `before_packing_logger`, or
2) in the terminal renderer path for `HookLog` (recommended for consistency across hook types).

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


Grey Divider

Previous review results

Review updated until commit 077f748

Results up to commit 77812a5


🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required
1. stripBundledDependenciesFromManifest declared too early ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
In bundle-deps.ts, stripBundledDependenciesFromManifest() is declared before its first usage in
the same file. This violates the rule requiring TypeScript function declarations to appear only
after their first usage.
Code

pnpm11/pnpm/bundle-deps.ts[R124-132]

+function stripBundledDependenciesFromManifest () {
+  const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
+  delete manifest.dependencies
+  delete manifest.devDependencies
+  fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
+}
+
createDistNodeModules()
+stripBundledDependenciesFromManifest()
Evidence
The function declaration at lines 124-129 precedes its first usage at line 132, which matches the
rule’s failure condition (declaration before any call site in-file).

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/pnpm/bundle-deps.ts[124-132]

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

## Issue description
A top-level TypeScript function declaration appears before its first call site, which violates the repo’s ordering rule for function declarations.

## Issue Context
The rule applies to `function foo(...) {}` declarations in `.ts` files. The function is called later in the same file, but no call appears before the declaration.

## Fix Focus Areas
- pnpm11/pnpm/bundle-deps.ts[124-132]

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



Remediation recommended
2. Historical comment in bundle-deps.ts 📘 Rule violation ⚙ Maintainability
Description
New comments describe past release behavior and future cleanup (e.g., “temporary workaround”,
“published 11.12.0…”, “Remove this once…”), rather than only the current contract. This violates the
requirement to keep inline comments focused on current behavior and can quickly become misleading.
Code

pnpm11/pnpm/bundle-deps.ts[R119-123]

+// The workspace .pnpmfile.cjs beforePacking hook already drops these fields when
+// packing. This on-disk strip is a temporary workaround for pnpm/pnpm#12955: the
+// pnpm v12 alpha that currently runs the release does not yet honor beforePacking,
+// so it published 11.12.0 with the fields intact. Remove this once the release
+// runs a pnpm that applies the hook.
Evidence
The added comment explicitly references past release behavior and a future removal plan (“temporary
workaround”, “published 11.12.0…”, “Remove this once…”), which is exactly the historical/temporal
commentary the checklist rule prohibits.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/pnpm/bundle-deps.ts[119-123]

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

## Issue description
A newly added comment block uses historical/temporal phrasing (e.g., “temporary workaround”, “published 11.12.0…”, “Remove this once…”) instead of documenting the current behavior/contract.

## Issue Context
Per the rule, inline comments should describe current behavior and rationale, not past implementations or future migration/removal notes.

## Fix Focus Areas
- pnpm11/pnpm/bundle-deps.ts[113-123]

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


3. Hook version path bypass 🐞 Bug ⛨ Security
Description
pacquet_pack::api validates the on-disk package.json version for path separators, but after
beforePacking it derives published_version from the hook-mutated manifest and passes it into
resolve_output. A beforePacking hook can inject / or \ so --out templates derive a parent
pack_destination (e.g. ..) and write the tarball outside the caller’s expected directory.
Code

pnpm/crates/pack/src/lib.rs[R282-293]

+    // Run `beforePacking` hooks against the built manifest, before the
+    // file list is computed, so a hook that rewrites `files` / `bin` /
+    // dependency fields is honored. pnpm runs it inside
+    // `createExportableManifest`; pacquet applies it here because
+    // `create_exportable_manifest` is a pure, synchronous transform.
+    publish_manifest =
+        apply_before_packing::<Reporter>(&opts.dir, &dir, publish_manifest, &opts.pnpmfiles)
+            .await?;
+
    // Strip semver build metadata (the `+<build>` segment) so the
    // tarball name, the packed manifest, and any registry metadata all
    // agree on the version. See pnpm/pnpm#11518.
Evidence
The code only validates the pre-hook version for path separators, then runs beforePacking and
recomputes published_version from the hook-mutated manifest; resolve_output derives a
destination directory from the parent of the --out template expansion.

pnpm/crates/pack/src/lib.rs[255-303]
pnpm/crates/pack/src/lib.rs[585-610]
pnpm/crates/pack/src/lib.rs[282-289]

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

### Issue description
`beforePacking` can mutate the published manifest's `version`, but the post-hook `published_version` is used for output path/template expansion without re-applying the path-separator validation that exists for the pre-hook version.

### Issue Context
- Pre-hook validation rejects `/` and `\\` in the original `version`.
- After `beforePacking`, `published_version` is recomputed from the (possibly modified) manifest and fed into `resolve_output`, which can turn path separators into a parent `pack_destination` when `--out` is used.

### Fix Focus Areas
- pnpm/crates/pack/src/lib.rs[255-303]
- pnpm/crates/pack/src/lib.rs[585-610]

### Suggested fix
After `apply_before_packing` and `strip_build_metadata`, re-run the same separator validation on `published_version` (and return `PackError::InvalidPackageVersion` on failure) before calling `resolve_output`.

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


4. Hook log escape injection 🐞 Bug ⛨ Security
Description
before_packing_logger forwards context.log(...) output into HookLog.message without stripping
control characters, and the default terminal reporter prints the message directly. A malicious
beforePacking hook can emit ANSI escape sequences to spoof or hide CLI output during
pack/publish.
Code

pnpm/crates/pack/src/lib.rs[R379-392]

+/// A `context.log(...)` sink forwarding each `beforePacking` log line to
+/// the `pnpm:hook` channel, tagged with the pnpmfile it came from.
+fn before_packing_logger<Reporter: self::Reporter>(pnpmfile: &Path, prefix: &str) -> LogFn {
+    let from = pnpmfile.to_string_lossy().into_owned();
+    let prefix = prefix.to_owned();
+    Arc::new(move |message| {
+        Reporter::emit(&LogEvent::Hook(HookLog {
+            level: LogLevel::Debug,
+            from: from.clone(),
+            hook: "beforePacking".to_string(),
+            prefix: prefix.clone(),
+            message,
+        }));
+    })
Evidence
before_packing_logger emits the raw hook message, and the default reporter concatenates
log.message into terminal output without escaping/sanitizing.

pnpm/crates/pack/src/lib.rs[379-392]
pnpm/crates/default-reporter/src/state.rs[1056-1063]

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

### Issue description
Hook-provided log strings are rendered to the terminal without sanitization, allowing control/escape sequences to alter terminal output.

### Issue Context
- `before_packing_logger` emits `LogEvent::Hook` with the hook-controlled `message`.
- `DefaultReporter` formats `HookLog` as `<hook>: <message>` and pushes it to terminal output.

### Fix Focus Areas
- pnpm/crates/pack/src/lib.rs[379-392]
- pnpm/crates/default-reporter/src/state.rs[1056-1063]

### Suggested fix
Sanitize `message` for terminal output (e.g., strip control chars like the pack output sanitizer does) either:
1) at emission time in `before_packing_logger`, or
2) in the terminal renderer path for `HookLog` (recommended for consistency across hook types).

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


View more (1)
5. Pnpmfile workers not reused ✓ Resolved 🐞 Bug ➹ Performance
Description
apply_before_packing constructs a fresh hooks instance for each pnpmfile path on every packed
project, so recursive workspace packs can repeatedly spawn new Node hook workers per project. This
can add significant latency and resource usage for large workspaces packing many projects with the
same pnpmfiles.
Code

pnpm/crates/pack/src/lib.rs[R358-376]

+async fn apply_before_packing<Reporter: self::Reporter>(
+    project_dir: &Path,
+    publish_dir: &Path,
+    mut manifest: Value,
+    pnpmfiles: &[PathBuf],
+) -> Result<Value, PackError> {
+    let prefix = project_dir.to_string_lossy();
+    for pnpmfile in pnpmfiles {
+        let hooks = finder::load_pnpmfile_at(pnpmfile.clone());
+        let ctx =
+            HookContext { log: before_packing_logger::<Reporter>(pnpmfile, &prefix), dir: None };
+        manifest = hooks.before_packing(manifest, publish_dir, ctx).await.map_err(|err| {
+            PackError::BeforePacking {
+                pnpmfile: pnpmfile.display().to_string(),
+                message: err.to_string(),
+            }
+        })?;
+    }
+    Ok(manifest)
Evidence
The pack path loads pnpmfiles anew per project; load_pnpmfile_at always constructs a new
NodeJsHooks, and NodeJsHooks only caches its worker per instance, so repeated construction
prevents worker reuse.

pnpm/crates/pack/src/lib.rs[358-376]
pnpm/crates/hooks/src/finder.rs[27-33]
pnpm/crates/hooks/src/node_runtime.rs[12-37]
pnpm/crates/cli/src/cli_args/pack.rs[216-235]

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

### Issue description
Recursive pack calls `pacquet_pack::api` once per project. The new `beforePacking` support reloads pnpmfiles into new `NodeJsHooks` instances per project, defeating the per-instance worker reuse and potentially spawning many `node` workers.

### Issue Context
- `apply_before_packing` calls `finder::load_pnpmfile_at(...)` inside the per-pack loop.
- `load_pnpmfile_at` creates a new `NodeJsHooks`, whose worker cache is per instance.

### Fix Focus Areas
- pnpm/crates/pack/src/lib.rs[358-376]
- pnpm/crates/hooks/src/finder.rs[27-33]
- pnpm/crates/hooks/src/node_runtime.rs[12-37]
- pnpm/crates/cli/src/cli_args/pack.rs[216-235]

### Suggested fix
Introduce reuse across projects, e.g.:
- Build a cache of `Arc<dyn PnpmfileHooks>` keyed by pnpmfile path (per-command or process-global), and have `apply_before_packing` reuse cached hook instances.
- In recursive pack, compute `pnpmfiles` once and thread it through `pack_options` instead of resolving per project (reduces filesystem churn even if hooks are cached elsewhere).

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


Qodo Logo

Comment thread pnpm11/pnpm/bundle-deps.ts Resolved
@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

The unified release flow (#12949) requires a changeset for Rust
changes. The TypeScript and pacquet sides fix different things and get
different release notes, so they are separate changeset files: "pnpm" for
the published-manifest dependency strip, and "pacquet" for applying the
beforePacking hook during pack/publish (the napi bindings bump with
pacquet through its fixed group).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@codecov-commenter

codecov-commenter commented Jul 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.43925% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.25%. Comparing base (d3e1383) to head (077f748).

Files with missing lines Patch % Lines
pnpm/crates/pack/src/lib.rs 67.50% 13 Missing ⚠️
pnpm/crates/napi/src/pack.rs 0.00% 5 Missing ⚠️
pnpm/crates/cli/src/cli_args/dispatch_query.rs 85.71% 2 Missing ⚠️
pnpm/crates/hooks/src/lib.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12964      +/-   ##
==========================================
- Coverage   85.26%   85.25%   -0.01%     
==========================================
  Files         486      486              
  Lines       77280    77368      +88     
==========================================
+ Hits        65890    65962      +72     
- Misses      11390    11406      +16     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI review requested due to automatic review settings July 13, 2026 09:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Addresses a review note: the extracted stripBundledDependenciesFromManifest
helper was declared before its only call site, against the repo's
declare-after-use rule. It's a trivial final step in the script, so inline
it after createDistNodeModules() instead of adding an out-of-order helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@greptile-apps

greptile-apps Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge; the async propagation through pack/publish is consistent, the napi shim correctly guards with an empty hook list, and integration tests exercise the hook path end-to-end.

The change is a targeted bug fix with a clear root cause and two complementary remediation layers. The beforePacking hook wiring follows the exact same pattern as the existing readPackage and filterLog hooks. The block_on usage in napi is safe because before_packing_hooks is hard-coded to empty there. Integration tests verify the packed manifest reflects hook modifications in all three relevant configurations.

No files require special attention. The pnpm11/pnpm/bundle-deps.ts stopgap has a clear removal marker in its inline comment; the Rust changes are well-tested.

Reviews (2): Last reviewed commit: "perf(pack): load beforePacking pnpmfiles..." | Re-trigger Greptile

Comment thread pnpm/crates/napi/src/pack.rs Resolved
Comment thread pnpm/crates/pack/src/lib.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8bdec82

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pnpm/crates/cli/src/cli_args/pack.rs (1)

153-182: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Recursive pnpm pack -r reloads pnpmfile hooks per project — see consolidated comment.

Each iteration of this loop calls pack_options (which re-resolves pnpmfiles via filesystem lookups) and then api(...), which reinitializes the hook worker for the same pnpmfile(s) from scratch every time. In a large monorepo with many selected packages, this repeats fs stats and Node-worker spin-up per package. Detailed in the consolidated comment below.

Also applies to: 216-217

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/cli/src/cli_args/pack.rs` around lines 153 - 182, The recursive
packing loop should reuse shared pnpmfile hook resolution and worker state
instead of rebuilding them for every project. Update the `pack_options`/`api`
flow used inside the `for root in chunk` loop to initialize the hooks once for
the recursive operation and pass or reuse that state for each package while
preserving each project’s existing pack options and results.
pnpm/crates/pack/src/lib.rs (1)

265-267: 🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Re-run the version separator guard after beforePacking. resolve_output() only validates --out; it does not reject / or \\ in version. Since published_version comes from the hook-mutated manifest, a hook can inject path components into the default <name>-<version>.tgz path and escape dest_dir.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/pack/src/lib.rs` around lines 265 - 267, Reapply the slash and
backslash validation to the hook-mutated published version after beforePacking
and before resolve_output constructs the default package path. Ensure the guard
covers published_version, rejecting path components before the archive
destination is derived, while preserving the existing InvalidPackageVersion
error behavior.
🧹 Nitpick comments (1)
pnpm/crates/pack/src/tests.rs (1)

41-44: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

No unit coverage of the beforePacking hook path in this crate.

Every fixture here sets pnpmfiles: Vec::new(), so apply_before_packing's hook-loading/chaining/error-mapping logic in lib.rs is only exercised by the Node-process-backed CLI integration test (pnpm/crates/cli/tests/pack.rs), not by this crate's fast unit tests. This lines up with Codecov's reported missing coverage in pnpm/crates/pack/src/lib.rs.

Consider adding a test double for PnpmfileHooks (the PnpmfileHooks trait is already mocked elsewhere, e.g. RecordingHooks in resolving-deps-resolver/src/tests.rs) so apply_before_packing's ordering and PackError::BeforePacking mapping can be unit-tested without spinning a Node process — this likely requires apply_before_packing/api to accept pre-loaded hooks rather than hardcoding finder::load_pnpmfile_at. Per pnpm/AGENTS.md, dependency injection is justified here since the Node worker is an external-service branch that a real fixture can't exercise cheaply.

Based on learnings/path instructions: "Prefer real fixtures... use dependency injection only for unreachable filesystem, time, process-global-state, or external-service branches."

Also applies to: 46-60

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/pack/src/tests.rs` around lines 41 - 44, Add fast unit coverage
in the pack crate for apply_before_packing using a PnpmfileHooks test double,
following the existing RecordingHooks pattern. Adjust api/apply_before_packing
to accept pre-loaded hooks through dependency injection instead of always
calling finder::load_pnpmfile_at, then test hook ordering and failures mapping
to PackError::BeforePacking without starting Node. Keep real fixtures for paths
that do not require the external-service seam.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm/crates/pack/src/lib.rs`:
- Around line 353-393: Cache the hooks loaded by finder::load_pnpmfile_at so
repeated apply_before_packing calls reuse the same loaded pnpmfile worker
instead of reinitializing it per package. Introduce or use a shared cache keyed
by pnpmfile path across the recursive packing flow, while preserving hook
execution order and per-invocation logging context in apply_before_packing.

---

Outside diff comments:
In `@pnpm/crates/cli/src/cli_args/pack.rs`:
- Around line 153-182: The recursive packing loop should reuse shared pnpmfile
hook resolution and worker state instead of rebuilding them for every project.
Update the `pack_options`/`api` flow used inside the `for root in chunk` loop to
initialize the hooks once for the recursive operation and pass or reuse that
state for each package while preserving each project’s existing pack options and
results.

In `@pnpm/crates/pack/src/lib.rs`:
- Around line 265-267: Reapply the slash and backslash validation to the
hook-mutated published version after beforePacking and before resolve_output
constructs the default package path. Ensure the guard covers published_version,
rejecting path components before the archive destination is derived, while
preserving the existing InvalidPackageVersion error behavior.

---

Nitpick comments:
In `@pnpm/crates/pack/src/tests.rs`:
- Around line 41-44: Add fast unit coverage in the pack crate for
apply_before_packing using a PnpmfileHooks test double, following the existing
RecordingHooks pattern. Adjust api/apply_before_packing to accept pre-loaded
hooks through dependency injection instead of always calling
finder::load_pnpmfile_at, then test hook ordering and failures mapping to
PackError::BeforePacking without starting Node. Keep real fixtures for paths
that do not require the external-service seam.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d4f92b95-5622-4e59-943e-15fb5601f209

📥 Commits

Reviewing files that changed from the base of the PR and between d3e1383 and 8bdec82.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (17)
  • .changeset/pacquet-before-packing-hook.md
  • .changeset/pnpm-publish-strip-bundled-deps.md
  • pnpm/crates/cli/src/cli_args/dispatch.rs
  • pnpm/crates/cli/src/cli_args/dispatch_query.rs
  • pnpm/crates/cli/src/cli_args/pack.rs
  • pnpm/crates/cli/src/cli_args/publish.rs
  • pnpm/crates/cli/src/cli_args/publish/tests.rs
  • pnpm/crates/cli/src/config_deps.rs
  • pnpm/crates/cli/tests/pack.rs
  • pnpm/crates/hooks/src/lib.rs
  • pnpm/crates/hooks/src/node_runtime.rs
  • pnpm/crates/hooks/src/worker.rs
  • pnpm/crates/napi/src/pack.rs
  • pnpm/crates/pack/Cargo.toml
  • pnpm/crates/pack/src/lib.rs
  • pnpm/crates/pack/src/tests.rs
  • pnpm11/pnpm/bundle-deps.ts

Comment thread pnpm/crates/pack/src/lib.rs Resolved
Review feedback (greptile, CodeRabbit): apply_before_packing loaded each
pnpmfile via finder::load_pnpmfile_at on every api() call, so a recursive
pack (pnpm pack -r / publish -r) in a workspace with a .pnpmfile.cjs
re-spawned that pnpmfile's Node worker once per packed project.

PackOptions now carries the loaded hooks (Vec<Arc<dyn PnpmfileHooks>>)
instead of paths. The CLI loads them once — the recursive path before the
per-project loop, like catalogs — and clones the Arcs into each project,
so the worker (a lazily-spawned OnceCell inside NodeJsHooks) is spawned
once and reused. apply_before_packing derives the pnpmfile path for logging
and error context from PnpmfileHooks::source_path.

Also reword the napi block_on comment to say the blocking tarball write
does not tie up an async worker thread, and add a recursive-pack test
asserting the workspace-root beforePacking hook runs for every project.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo is busy working

Check back in a few minutes. Qodo's code review agents are on it.

Grey Divider

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
pnpm11/pnpm/bundle-deps.ts (1)

126-129: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the temporary nature and rationale of the manifest stripping.

The manifest field removal has no comment explaining why it's needed or that it's a temporary workaround. Per the REVIEW_GUIDE, the fix should live at the pack/publish flow layer (the beforePacking hook), not in an ad-hoc call site. A brief comment would help future maintainers understand when this can be removed (i.e., when the TypeScript pnpm CLI gains beforePacking hook support).

As per path instructions, REVIEW_GUIDE.md states: "this PR must solve the tarball/install regression by removing bundled dependencies/devDependencies from published manifests at the correct layer (pack/publish flow), not via ad-hoc call sites."

💬 Suggested comment
 createDistNodeModules()

+// Temporary workaround: strip bundled dependencies/devDependencies from the
+// published manifest so `npm install --omit=dev --omit=optional` succeeds on
+// the extracted tarball. This should eventually be replaced by beforePacking
+// hook support in the TypeScript pack/publish flow.
 const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'))
 delete manifest.dependencies
 delete manifest.devDependencies
 fs.writeFileSync(MANIFEST_PATH, `${JSON.stringify(manifest, undefined, 2)}\n`)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm11/pnpm/bundle-deps.ts` around lines 126 - 129, Move the manifest
dependency stripping from this ad-hoc call site into the pack/publish flow’s
beforePacking hook, using the hook implementation as the change point. Add a
brief comment documenting that removing dependencies and devDependencies is a
temporary workaround for the tarball/install regression and can be removed once
the TypeScript pnpm CLI supports beforePacking.

Source: Path instructions

pnpm/crates/cli/tests/pack.rs (1)

120-171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a regression test for the beforePacking hook failure path.

The three integration tests cover happy paths (hook rewrites manifest), but none exercise PackError::BeforePacking when a hook throws. A .pnpmfile.cjs that throws in beforePacking should fail the CLI with the pnpmfile path attributed; asserting that covers the error-mapping branch currently flagged as uncovered in pnpm/crates/pack/src/lib.rs.

🧪 Suggested hook-failure test
+/// A `beforePacking` hook that throws surfaces a pack failure attributing
+/// the offending pnpmfile.
+#[test]
+fn before_packing_hook_failure_fails_the_pack() {
+    let CommandTempCwd { pacquet, root, workspace, .. } = CommandTempCwd::init();
+    fs::write(
+        workspace.join("package.json"),
+        json!({ "name": "pkg", "version": "1.0.0" }).to_string(),
+    )
+    .expect("write package.json");
+    fs::write(
+        workspace.join(".pnpmfile.cjs"),
+        r"module.exports = {
+  hooks: {
+    beforePacking () {
+      throw new Error('hook boom')
+    },
+  },
+}
+",
+    )
+    .expect("write .pnpmfile.cjs");
+    let out = workspace.join("tarballs");
+    fs::create_dir_all(&out).expect("create out dir");
+
+    pacquet
+        .with_arg("pack")
+        .with_arg("--pack-destination")
+        .with_arg(out.to_str().expect("utf8 out dir"))
+        .assert()
+        .failure()
+        .stderr(predicates::str::contains("hook boom"));
+
+    drop(root);
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/cli/tests/pack.rs` around lines 120 - 171, Add a regression test
alongside recursive_pack_applies_before_packing_hook_to_every_project that
writes a .pnpmfile.cjs whose beforePacking hook throws, runs the pack CLI, and
asserts failure with PackError::BeforePacking behavior, including attribution of
the error to the pnpmfile path. Cover the CLI error output or structured failure
details without changing the existing happy-path tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pnpm/crates/cli/tests/pack.rs`:
- Around line 120-171: Add a regression test alongside
recursive_pack_applies_before_packing_hook_to_every_project that writes a
.pnpmfile.cjs whose beforePacking hook throws, runs the pack CLI, and asserts
failure with PackError::BeforePacking behavior, including attribution of the
error to the pnpmfile path. Cover the CLI error output or structured failure
details without changing the existing happy-path tests.

In `@pnpm11/pnpm/bundle-deps.ts`:
- Around line 126-129: Move the manifest dependency stripping from this ad-hoc
call site into the pack/publish flow’s beforePacking hook, using the hook
implementation as the change point. Add a brief comment documenting that
removing dependencies and devDependencies is a temporary workaround for the
tarball/install regression and can be removed once the TypeScript pnpm CLI
supports beforePacking.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ca59e54a-2057-4896-bfc1-ab8d24940aae

📥 Commits

Reviewing files that changed from the base of the PR and between 8bdec82 and 077f748.

📒 Files selected for processing (8)
  • pnpm/crates/cli/src/cli_args/pack.rs
  • pnpm/crates/cli/src/cli_args/publish.rs
  • pnpm/crates/cli/src/config_deps.rs
  • pnpm/crates/cli/tests/pack.rs
  • pnpm/crates/napi/src/pack.rs
  • pnpm/crates/pack/src/lib.rs
  • pnpm/crates/pack/src/tests.rs
  • pnpm11/pnpm/bundle-deps.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/crates/cli/src/cli_args/publish.rs
  • pnpm/crates/cli/src/config_deps.rs

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 13, 2026
@zkochan
zkochan merged commit 0dd21df into main Jul 13, 2026
38 checks passed
@zkochan
zkochan deleted the fix-12955 branch July 13, 2026 10:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

11.12.0 release fails to install from tarball

3 participants