Skip to content

feat: add custom resolver hooks - #10153

Closed
TrevorBurnham wants to merge 3 commits into
pnpm:mainfrom
TrevorBurnham:custom-resolver-hook
Closed

TrevorBurnham wants to merge 3 commits into
pnpm:mainfrom
TrevorBurnham:custom-resolver-hook

Conversation

@TrevorBurnham

Copy link
Copy Markdown
Contributor

This PR is an effort to add more flexibility to pnpm's hook system, bringing it closer to Yarn's plugin functionality. The changes are:

  1. A new resolvers hook, an array of objects that support a variety of methods for controlling how packages are resolved and how their entries are written to/read from the lockfile.
  2. An optional return value in preResolution to force full resolution (fixes Force package reinstall via preResolution hook #9516). This is essential for our use case, where we need to force certain packages to reinstall from our registry even if the lockfile is satisfied.

Why?

I've been working for a while to try to integrate pnpm with my company's internal registry system, which has some unusual properties. I've tried to do so using the existing hooks, but I keep running into issues (see e.g. #9485, #9516, and #9752).

No matter what combination of readPackage, preResolution, and afterAllResolved I use, I can't quite get the behavior I want. But with the changes on this branch, I can.

How?

Here's an example:

module.exports = {
  hooks: {
    resolvers: [
      {
        // Match packages by name, scope, or other criteria
        supportsDescriptor: (descriptor) => descriptor.name === 'my-package',

        // Provide custom resolution
        resolve: (descriptor, opts) => ({
          id: '[email protected]',
          resolution: { tarball: 'file://local/path.tgz', integrity: 'sha512-...' },
          resolvedVia: 'my-resolver'
        }),
      }
    ]
  }
}

I've taken inspiration from Yarn here: The supportsDescriptor method tells pnpm "I know how to resolve this package"; pnpm calls the resolve method only if that method returned true. The resolve method then returns an id and resolution that tell pnpm how to resolve the package.

A custom resolver can also control how packages are serialized to and from the lockfile. So for instance, if you want to resolve packages from a custom cache but the location of that cache differs across systems, you can avoid the diff noise that would occur if the cache were included in the lockfile.

All of these custom resolver methods can be either synchronous or asynchronous, allowing hook users to perform any kinds of lookups they need.

More details

I've drafted documentation changes for pnpm.io to cover the new custom resolver methods: TrevorBurnham/pnpm.io@bb3410d


Note to reviewers: I was able to replicate the CI test failures on main. They're not caused by the changes on this branch, which should be fully backward-compatible.

@welcome

welcome Bot commented Nov 3, 2025

Copy link
Copy Markdown

💖 Thanks for opening this pull request! 💖
Please be patient and we will get back to you as soon as we can.

@zkochan
zkochan requested a review from Copilot November 4, 2025 23:49

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.

Pull Request Overview

This PR adds support for custom resolver plugins to pnpm, enabling users to extend package resolution logic through pnpmfile hooks. The changes introduce a plugin architecture for resolving non-standard package sources and handling custom lockfile resolution types.

  • Adds ResolverPlugin interface with support for both descriptor resolution and lockfile resolution phases
  • Introduces CustomResolution type to support arbitrary resolution types beyond the standard directory/git/tarball formats
  • Updates hooks system to support custom resolvers and allows preResolution hook to force full resolution
  • Implements comprehensive test coverage for custom resolver functionality

Reviewed Changes

Copilot reviewed 36 out of 37 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
packages/types/src/resolver.ts Defines new ResolverPlugin interface and related types for custom resolution
resolving/resolver-base/src/index.ts Adds CustomResolution type and updates type unions
resolving/default-resolver/src/index.ts Integrates custom resolver logic into the resolution pipeline
resolving/default-resolver/test/customResolver.ts Comprehensive test suite for custom resolver functionality
lockfile/types/src/index.ts Adds CustomResolution to lockfile resolution types
lockfile/utils/src/pkgSnapshotToResolution.ts Implements resolver plugin support for lockfile-to-resolution conversion
lockfile/utils/test/pkgSnapshotToResolution.ts Tests for custom resolver lockfile handling
hooks/types/src/index.ts Exports resolver types and updates hook signatures
hooks/pnpmfile/src/Hooks.ts Adds resolvers to pnpmfile hooks interface
releasing/plugin-commands-deploy/src/createDeployFiles.ts Adds type guards and support for custom resolution types
pkg-manager/core/README.md Documents new hook features and API changes
Various package.json files Adds dependencies for new type packages
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +47 to +48
"@pnpm/types": "workspace:*",
"@types/normalize-path": "catalog:", "@zkochan/rimraf": "catalog:",

Copilot AI Nov 4, 2025

Copy link

Choose a reason for hiding this comment

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

Inconsistent indentation in the dependencies object. Line 47 has extra leading spaces, and line 48 has a missing newline between two dependencies.

Suggested change
"@pnpm/types": "workspace:*",
"@types/normalize-path": "catalog:", "@zkochan/rimraf": "catalog:",
"@pnpm/types": "workspace:*",
"@types/normalize-path": "catalog:",
"@zkochan/rimraf": "catalog:",

Copilot uses AI. Check for mistakes.
Comment on lines +55 to 56
"engines": { "node": ">=20.19"
},

Copilot AI Nov 4, 2025

Copy link

Choose a reason for hiding this comment

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

Inconsistent formatting: missing newline before "engines" property. This should be on a new line for consistency with the rest of the file.

Suggested change
"engines": { "node": ">=20.19"
},
"engines": {
"node": ">=20.19"
},

Copilot uses AI. Check for mistakes.
Comment thread resolving/default-resolver/src/index.ts Outdated
const resolveResult = resolver.resolve(descriptor, {
lockfileDir: opts.lockfileDir,
projectDir: opts.projectDir,
preferredVersions: (opts.preferredVersions ?? {}) as unknown as Record<string, string>,

Copilot AI Nov 4, 2025

Copy link

Choose a reason for hiding this comment

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

Type casting preferredVersions to Record<string, string> is incorrect. Based on the test at line 230 and the actual type usage throughout the codebase, preferredVersions should be Record<string, Record<string, 'version' | 'range' | 'tag'>>, not Record<string, string>.

Copilot uses AI. Check for mistakes.
})

test('getLockfileResolution transforms resolution', async () => {
const getLockfileResolution = jest.fn((resolution: unknown) => ({ ...resolution as Record<string, unknown>, integrity: 'sha512-transformed' }))

Copilot AI Nov 4, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Line length exceeds reasonable limits (over 160 characters). Consider breaking this into multiple lines for better readability.

Copilot uses AI. Check for mistakes.

await resolvePackage(
{ alias: 'any', bareSpecifier: '1.0.0' },
{ lockfileDir: '/test', projectDir: '/test', preferredVersions: { any: { '1.0.0': 'version' } } as unknown as Record<string, Record<string, 'version' | 'range' | 'tag'>> }

Copilot AI Nov 4, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Line length exceeds reasonable limits (over 180 characters). Consider breaking this into multiple lines for better readability.

Copilot uses AI. Check for mistakes.
@zkochan

zkochan commented Nov 5, 2025

Copy link
Copy Markdown
Member

If you want a custom resolver, you need to run that custom resolver here:

resolve: async (wantedDependency, opts) => {
const resolution = await resolveFromNpm(wantedDependency, opts as ResolveFromNpmOptions) ??
await resolveFromJsr(wantedDependency, opts as ResolveFromNpmOptions) ??
(wantedDependency.bareSpecifier && (
await resolveFromTarball(fetchFromRegistry, wantedDependency as { bareSpecifier: string }) ??
await resolveFromGit(wantedDependency as { bareSpecifier: string }) ??
await _resolveFromLocal(wantedDependency as { bareSpecifier: string }, opts)
)) ??
await _resolveNodeRuntime(wantedDependency) ??
await _resolveDenoRuntime(wantedDependency) ??
await _resolveBunRuntime(wantedDependency)
if (!resolution) {
throw new PnpmError(
'SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER',
`${wantedDependency.alias ? wantedDependency.alias + '@' : ''}${wantedDependency.bareSpecifier ?? ''} isn't supported by any available resolver.`)
}
return resolution
},

@TrevorBurnham

Copy link
Copy Markdown
Contributor Author

If you want a custom resolver, you need to run that custom resolver here...

Done! 681e954 I've also added more test coverage for the supportsDescriptor/resolve hooks.

}
}

export async function pkgSnapshotToResolutionWithResolvers (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why is it needed to hook into the lockfile format? If the available resolution types are not sufficient, your custom resolver can return a new resolution with a new type and you can create a custom fetcher for that new type.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The fetchers hook doesn't currently support custom types; you can only use the types listed at https://pnpm.io/next/pnpmfile#hooksfetchers.

The fromLockfileResolution hook is a more flexible solution. This code was overcomplicated, though; I've pushed a commit to simplify it: 821b8be

@zkochan zkochan Nov 5, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It can be easily extended:

const fetch = fetcherByHostingType[fetcherType!]

The fetcher is picked from a dictionary of fetchers by the value of the "type" field.

Also, I don't understand what hooking into the lockfile format gives you except syntactic sugar. If an existing fetcher is going to be used, why should there be any change in the lockfile entries?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

If an existing fetcher is going to be used, why should there be any change in the lockfile entries?

One simple use case is "I want to fetch a tarball from a file, but I don't want that full file: path to live in the lockfile because it's not consistent across systems." (Plus, file: specifiers aren't allowed for peer dependencies: #9485).

The fetcher is picked from a dictionary of fetchers by the value of the "type" field

I think that having true custom fetchers would be great!

Relatedly, I'm realizing that "custom resolver" was a poor choice of terminology on my part; "plugin" conveys the idea better. Plugin objects are portable and composable: You could make a plugin with all of the functionality you want, package it, and distribute for easy use in any pnpmfile, perhaps in combination with other plugins.

With that in mind, I'm imagining a cleaner plugin API with methods like:

  • canResolve and resolve (custom resolver)
  • canFetch and fetch (custom fetcher)

If that sounds like the right approach to you, I'll go to work on that update.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it would be better to solve it via a "true fetcher". Your new resolver would produce whatever new entry it wants and the existing standard types of resolution would remain unchanged.

Regarding the plugin aspect, you can already develop plugins by config dependencies. Your config dependency can set the custom resolvers/fetchers via the updateConfig hook.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think it would be better to solve it via a "true fetcher". Your new resolver would produce whatever new entry it wants and the existing standard types of resolution would remain unchanged.

That works well enough when the custom resolver is called, but it brings us back to lockfiles. When installing from a lockfile (headless install), the resolver is bypassed, so you'd still need some other hook (like the originally proposed fromLockfileResolution) to create a resolution object that tell pnpm which fetcher to use.

I think the canFetch/fetch approach more elegant because it means the custom resolver can be more straightforward. In particular, it removes the need (when using custom types) for the custom resolver to return both a "real" resolution object (for the fetcher to handle) and a separate lockfile entry object.

Regarding the plugin aspect, you can already develop plugins by config dependencies.

Ahh, I hadn't seen this before: "If your config dependency is named following the pnpm-plugin-* or @*/pnpm-plugin-* pattern, pnpm will automatically load the pnpmfile.cjs from its root." Neat!

So the word "plugin" is overloaded, but I still like the idea of having hooks live in objects so that hooks that depend on each other can be defined in one place.

Long-term, I think the new object-based hook API could replace all existing hooks in a way that feels more cohesive and approachable to developers.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

That works well enough when the custom resolver is called, but it brings us back to lockfiles. When installing from a lockfile (headless install), the resolver is bypassed, so you'd still need some other hook (like the originally proposed fromLockfileResolution) to create a resolution object that tell pnpm which fetcher to use.

But the fetcher is not bypassed. That's why I suggested to create a custom fetcher with a new "type" name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

But the fetcher is not bypassed. That's why I suggested to create a custom fetcher with a new "type" name.

I guess I didn't understand your comment. I suggested adding canFetch/fetch methods to provide fetchers for custom types, and you responded

I think it would be better to solve it via a "true fetcher".

So I took "true fetcher" to mean one of the existing fetchers, meaning no custom type.

If you're talking about adding fetchers for custom types, what's the difference between your proposal and the canFetch/fetch methods?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ok, so if you add your own fetch method, there's no need in pkgSnapshotToResolutionWithResolvers

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I think that's correct. I'll give it a try and post an update.

@TrevorBurnham

Copy link
Copy Markdown
Contributor Author

Closing this in favor of #10201, which is a rethink following the discussion above.

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.

Force package reinstall via preResolution hook

3 participants