@pnpm/resolving.git-resolver 1001.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015-2016 Rico Sta. Cruz and other contributors
4
+ Copyright (c) 2016-2026 Zoltan Kochan and other contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # @pnpm/git-resolver
2
+
3
+ > Resolver for git-hosted packages
4
+
5
+ <!--@shields('npm')-->
6
+ [![npm version](https://img.shields.io/npm/v/@pnpm/git-resolver.svg)](https://www.npmjs.com/package/@pnpm/git-resolver)
7
+ <!--/@-->
8
+
9
+ ## Installation
10
+
11
+ ```
12
+ pnpm add @pnpm/git-resolver
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ <!--@example('./example.js')-->
18
+ ```js
19
+ 'use strict'
20
+ const createResolveFromNpm = require('@pnpm/git-resolver').default
21
+
22
+ const resolveFromNpm = createResolveFromNpm({})
23
+
24
+ resolveFromNpm({
25
+ bareSpecifier: 'kevva/is-negative#16fd36fe96106175d02d066171c44e2ff83bc055'
26
+ })
27
+ .then(resolveResult => console.log(JSON.stringify(resolveResult, null, 2)))
28
+ //> {
29
+ // "id": "github.com/kevva/is-negative/16fd36fe96106175d02d066171c44e2ff83bc055",
30
+ // "normalizedBareSpecifier": "github:kevva/is-negative#16fd36fe96106175d02d066171c44e2ff83bc055",
31
+ // "resolution": {
32
+ // "tarball": "https://codeload.github.com/kevva/is-negative/tar.gz/16fd36fe96106175d02d066171c44e2ff83bc055"
33
+ // },
34
+ // "resolvedVia": "git-repository"
35
+ // }
36
+ ```
37
+ <!--/@-->
38
+
39
+ ## License
40
+
41
+ MIT
@@ -0,0 +1,6 @@
1
+ import type { PkgResolutionId } from '@pnpm/resolving.resolver-base';
2
+ export declare function createGitHostedPkgId({ repo, commit, path }: {
3
+ repo: string;
4
+ commit: string;
5
+ path?: string;
6
+ }): PkgResolutionId;
@@ -0,0 +1,10 @@
1
+ export function createGitHostedPkgId({ repo, commit, path }) {
2
+ let id = `${repo.includes('://') ? '' : 'https://'}${repo}#${commit}`;
3
+ if (!id.startsWith('git+'))
4
+ id = `git+${id}`;
5
+ if (path) {
6
+ id += `&path:${path}`;
7
+ }
8
+ return id;
9
+ }
10
+ //# sourceMappingURL=createGitHostedPkgId.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { AgentOptions } from '@pnpm/network.agent';
2
+ import type { GitResolution, ResolveOptions, ResolveResult, TarballResolution } from '@pnpm/resolving.resolver-base';
3
+ import { createGitHostedPkgId } from './createGitHostedPkgId.js';
4
+ import { type HostedPackageSpec } from './parseBareSpecifier.js';
5
+ export { createGitHostedPkgId };
6
+ export type { HostedPackageSpec };
7
+ export interface GitResolveResult extends ResolveResult {
8
+ normalizedBareSpecifier?: string;
9
+ resolution: GitResolution | TarballResolution;
10
+ resolvedVia: 'git-repository';
11
+ }
12
+ export type GitResolver = (wantedDependency: {
13
+ bareSpecifier: string;
14
+ }, opts?: Pick<ResolveOptions, 'currentPkg' | 'update'>) => Promise<GitResolveResult | null>;
15
+ export declare function createGitResolver(opts: AgentOptions): GitResolver;
package/lib/index.js ADDED
@@ -0,0 +1,152 @@
1
+ import { PnpmError } from '@pnpm/error';
2
+ import { gracefulGit as git } from 'graceful-git';
3
+ import semver from 'semver';
4
+ import { createGitHostedPkgId } from './createGitHostedPkgId.js';
5
+ import { parseBareSpecifier } from './parseBareSpecifier.js';
6
+ export { createGitHostedPkgId };
7
+ export function createGitResolver(opts) {
8
+ return async function resolveGit(wantedDependency, resolveOpts) {
9
+ const parsedSpecFunc = parseBareSpecifier(wantedDependency.bareSpecifier, opts);
10
+ if (parsedSpecFunc == null)
11
+ return null;
12
+ // Skip resolution if we have currentPkg and not updating
13
+ if (resolveOpts?.currentPkg && !resolveOpts.update) {
14
+ const currentResolution = resolveOpts.currentPkg.resolution;
15
+ // Return existing resolution for git packages
16
+ if ('type' in currentResolution && currentResolution.type === 'git') {
17
+ return {
18
+ id: resolveOpts.currentPkg.id,
19
+ resolution: currentResolution,
20
+ resolvedVia: 'git-repository',
21
+ };
22
+ }
23
+ // Also handle tarballs from git (e.g., GitHub hosted)
24
+ if ('tarball' in currentResolution && currentResolution.tarball) {
25
+ return {
26
+ id: resolveOpts.currentPkg.id,
27
+ resolution: currentResolution,
28
+ resolvedVia: 'git-repository',
29
+ };
30
+ }
31
+ }
32
+ const parsedSpec = await parsedSpecFunc();
33
+ const bareSpecifier = parsedSpec.gitCommittish == null || parsedSpec.gitCommittish === ''
34
+ ? 'HEAD'
35
+ : parsedSpec.gitCommittish;
36
+ const commit = await resolveRef(parsedSpec.fetchSpec, bareSpecifier, parsedSpec.gitRange);
37
+ let resolution;
38
+ if ((parsedSpec.hosted != null) && !isSsh(parsedSpec.fetchSpec)) {
39
+ // don't use tarball for ssh url, they are likely private repo
40
+ const hosted = parsedSpec.hosted;
41
+ // use resolved committish
42
+ hosted.committish = commit;
43
+ const tarball = hosted.tarball?.();
44
+ if (tarball) {
45
+ resolution = { tarball };
46
+ }
47
+ }
48
+ if (resolution == null) {
49
+ resolution = {
50
+ commit,
51
+ repo: parsedSpec.fetchSpec,
52
+ type: 'git',
53
+ };
54
+ }
55
+ if (parsedSpec.path) {
56
+ resolution.path = parsedSpec.path;
57
+ }
58
+ let id;
59
+ if ('tarball' in resolution) {
60
+ id = resolution.tarball;
61
+ if (resolution.path) {
62
+ id = `${id}#path:${resolution.path}`;
63
+ }
64
+ }
65
+ else {
66
+ id = createGitHostedPkgId(resolution);
67
+ }
68
+ return {
69
+ id,
70
+ normalizedBareSpecifier: parsedSpec.normalizedBareSpecifier,
71
+ resolution,
72
+ resolvedVia: 'git-repository',
73
+ };
74
+ };
75
+ }
76
+ function resolveVTags(vTags, range) {
77
+ return semver.maxSatisfying(vTags, range, true);
78
+ }
79
+ async function getRepoRefs(repo, ref) {
80
+ const gitArgs = [repo];
81
+ if (ref) {
82
+ gitArgs.push(ref);
83
+ // Also request the peeled ref for annotated tags (e.g., refs/tags/v1.0.0^{})
84
+ // This is needed because annotated tags have their own SHA, and we need the commit SHA they point to
85
+ gitArgs.push(`${ref}^{}`);
86
+ }
87
+ // graceful-git by default retries 10 times, reduce to single retry
88
+ const result = await git(['ls-remote', ...gitArgs], { retries: 1 });
89
+ const refs = {};
90
+ for (const line of result.stdout.split('\n')) {
91
+ const [commit, refName] = line.split('\t');
92
+ refs[refName] = commit;
93
+ }
94
+ return refs;
95
+ }
96
+ async function resolveRef(repo, ref, range) {
97
+ const committish = ref.match(/^[0-9a-f]{7,40}$/) !== null;
98
+ if (committish && ref.length === 40) {
99
+ return ref;
100
+ }
101
+ const refs = await getRepoRefs(repo, (range ?? committish) ? null : ref);
102
+ const result = resolveRefFromRefs(refs, repo, ref, committish, range);
103
+ if (committish && !result.startsWith(ref)) {
104
+ throw new PnpmError('GIT_AMBIGUOUS_REF', `resolved commit ${result} from commit-ish reference ${ref}`);
105
+ }
106
+ return result;
107
+ }
108
+ function resolveRefFromRefs(refs, repo, ref, committish, range) {
109
+ if (!range) {
110
+ let commitId = refs[ref] ||
111
+ refs[`refs/${ref}`] ||
112
+ refs[`refs/tags/${ref}^{}`] || // prefer annotated tags
113
+ refs[`refs/tags/${ref}`] ||
114
+ refs[`refs/heads/${ref}`];
115
+ if (!commitId) {
116
+ // check for a partial commit
117
+ // Use Set to deduplicate since multiple refs can point to the same commit
118
+ const commits = committish ? [...new Set(Object.values(refs).filter((value) => value.startsWith(ref)))] : [];
119
+ if (commits.length === 1) {
120
+ commitId = commits[0];
121
+ }
122
+ else {
123
+ throw new Error(`Could not resolve ${ref} to a commit of ${repo}.`);
124
+ }
125
+ }
126
+ return commitId;
127
+ }
128
+ else {
129
+ const vTags = [...new Set(Object.keys(refs)
130
+ // using the same semantics of version tags as https://github.com/zkat/pacote
131
+ .filter((key) => /^refs\/tags\/v?\d+\.\d+\.\d+(?:[-+].+)?(?:\^\{\})?$/.test(key))
132
+ .map((key) => {
133
+ return key
134
+ .replace(/^refs\/tags\//, '')
135
+ .replace(/\^\{\}$/, ''); // accept annotated tags
136
+ })
137
+ .filter((key) => semver.valid(key, true)))];
138
+ const refVTag = resolveVTags(vTags, range);
139
+ const commitId = refVTag &&
140
+ (refs[`refs/tags/${refVTag}^{}`] || // prefer annotated tags
141
+ refs[`refs/tags/${refVTag}`]);
142
+ if (!commitId) {
143
+ throw new Error(`Could not resolve ${range} to a commit of ${repo}. Available versions are: ${vTags.join(', ')}`);
144
+ }
145
+ return commitId;
146
+ }
147
+ }
148
+ function isSsh(gitSpec) {
149
+ return gitSpec.slice(0, 10) === 'git+ssh://' ||
150
+ gitSpec.slice(0, 4) === 'git@';
151
+ }
152
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ import type { AgentOptions } from '@pnpm/network.agent';
2
+ export interface HostedPackageSpec {
3
+ fetchSpec: string;
4
+ hosted?: {
5
+ type: string;
6
+ user: string;
7
+ project: string;
8
+ committish: string;
9
+ tarball: () => string | undefined;
10
+ };
11
+ normalizedBareSpecifier: string;
12
+ gitCommittish: string | null;
13
+ gitRange?: string;
14
+ path?: string;
15
+ }
16
+ export declare function parseBareSpecifier(bareSpecifier: string, opts: AgentOptions): null | (() => Promise<HostedPackageSpec>);
@@ -0,0 +1,169 @@
1
+ // cspell:ignore sshurl
2
+ import urlLib, { URL } from 'node:url';
3
+ import { fetchWithAgent } from '@pnpm/network.fetch';
4
+ import { gracefulGit as git } from 'graceful-git';
5
+ import HostedGit from 'hosted-git-info';
6
+ const gitProtocols = new Set([
7
+ 'git',
8
+ 'git+http',
9
+ 'git+https',
10
+ 'git+rsync',
11
+ 'git+ftp',
12
+ 'git+file',
13
+ 'git+ssh',
14
+ 'ssh',
15
+ ]);
16
+ export function parseBareSpecifier(bareSpecifier, opts) {
17
+ const hosted = HostedGit.fromUrl(bareSpecifier);
18
+ if (hosted != null) {
19
+ return () => fromHostedGit(hosted, opts);
20
+ }
21
+ const colonsPos = bareSpecifier.indexOf(':');
22
+ if (colonsPos === -1)
23
+ return null;
24
+ const protocol = bareSpecifier.slice(0, colonsPos);
25
+ // Also detect http/https URLs ending in .git as git repositories
26
+ const isGitUrl = gitProtocols.has(protocol.toLocaleLowerCase()) ||
27
+ ((protocol === 'http' || protocol === 'https') && /\.git(?:#|$)/.test(bareSpecifier));
28
+ if (protocol && isGitUrl) {
29
+ const correctBareSpecifier = correctUrl(bareSpecifier);
30
+ const url = new URL(correctBareSpecifier);
31
+ if (!url?.protocol)
32
+ return null;
33
+ const hash = (url.hash?.length > 1) ? decodeURIComponent(url.hash.slice(1)) : null;
34
+ return async () => ({
35
+ fetchSpec: urlToFetchSpec(url),
36
+ normalizedBareSpecifier: bareSpecifier,
37
+ ...parseGitParams(hash),
38
+ });
39
+ }
40
+ return null;
41
+ }
42
+ function urlToFetchSpec(url) {
43
+ url.hash = '';
44
+ const fetchSpec = urlLib.format(url);
45
+ if (fetchSpec.startsWith('git+')) {
46
+ return fetchSpec.slice(4);
47
+ }
48
+ return fetchSpec;
49
+ }
50
+ async function fromHostedGit(hosted, agentOptions) {
51
+ let fetchSpec = null;
52
+ // try git/https url before fallback to ssh url
53
+ const gitHttpsUrl = hosted.https({ noCommittish: true, noGitPlus: true });
54
+ if (gitHttpsUrl && await isRepoPublic(gitHttpsUrl, agentOptions) && await accessRepository(gitHttpsUrl)) {
55
+ fetchSpec = gitHttpsUrl;
56
+ }
57
+ else {
58
+ const gitSshUrl = hosted.ssh({ noCommittish: true });
59
+ if (gitSshUrl && await accessRepository(gitSshUrl)) {
60
+ fetchSpec = gitSshUrl;
61
+ }
62
+ }
63
+ if (!fetchSpec) {
64
+ const httpsUrl = hosted.https({ noGitPlus: true, noCommittish: true });
65
+ if (httpsUrl) {
66
+ if ((hosted.auth || !await isRepoPublic(httpsUrl, agentOptions)) && await accessRepository(httpsUrl)) {
67
+ return {
68
+ fetchSpec: httpsUrl,
69
+ hosted: {
70
+ ...hosted,
71
+ _fill: hosted._fill,
72
+ tarball: undefined,
73
+ },
74
+ normalizedBareSpecifier: `git+${httpsUrl}`,
75
+ ...parseGitParams(hosted.committish),
76
+ };
77
+ }
78
+ else {
79
+ try {
80
+ // when git ls-remote private repo, it asks for login credentials.
81
+ // use HTTP HEAD request to test whether this is a private repo, to avoid login prompt.
82
+ // this is very similar to yarn classic's behavior.
83
+ // npm instead tries git ls-remote directly which prompts user for login credentials.
84
+ // HTTP HEAD on https://domain/user/repo, strip out ".git"
85
+ const response = await fetchWithAgent(httpsUrl.replace(/\.git$/, ''), { method: 'HEAD', follow: 0, retry: { retries: 0 }, agentOptions });
86
+ if (response.ok) {
87
+ fetchSpec = httpsUrl;
88
+ }
89
+ }
90
+ catch {
91
+ // ignore
92
+ }
93
+ }
94
+ }
95
+ }
96
+ if (!fetchSpec) {
97
+ // use ssh url for likely private repo
98
+ fetchSpec = hosted.sshurl({ noCommittish: true });
99
+ }
100
+ return {
101
+ fetchSpec: fetchSpec,
102
+ hosted: {
103
+ ...hosted,
104
+ _fill: hosted._fill,
105
+ tarball: hosted.tarball,
106
+ },
107
+ normalizedBareSpecifier: hosted.shortcut(),
108
+ ...parseGitParams(hosted.committish),
109
+ };
110
+ }
111
+ async function isRepoPublic(httpsUrl, agentOptions) {
112
+ try {
113
+ const response = await fetchWithAgent(httpsUrl.replace(/\.git$/, ''), { method: 'HEAD', follow: 0, retry: { retries: 0 }, agentOptions });
114
+ return response.ok;
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ }
120
+ async function accessRepository(repository) {
121
+ try {
122
+ await git(['ls-remote', '--exit-code', repository, 'HEAD'], { retries: 0 });
123
+ return true;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
129
+ function parseGitParams(committish) {
130
+ const result = { gitCommittish: null };
131
+ if (!committish) {
132
+ return result;
133
+ }
134
+ const params = committish.split('&');
135
+ for (const param of params) {
136
+ if (param.length >= 7 && param.slice(0, 7) === 'semver:') {
137
+ result.gitRange = param.slice(7);
138
+ }
139
+ else if (param.slice(0, 5) === 'path:') {
140
+ result.path = param.slice(5);
141
+ }
142
+ else {
143
+ result.gitCommittish = param;
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+ // handle SCP-like URLs
149
+ // see https://github.com/yarnpkg/yarn/blob/5682d55/src/util/git.js#L103
150
+ function correctUrl(gitUrl) {
151
+ let _gitUrl = gitUrl.replace(/^git\+/, '');
152
+ if (_gitUrl.startsWith('ssh://')) {
153
+ const hashIndex = _gitUrl.indexOf('#');
154
+ let hash = '';
155
+ if (hashIndex !== -1) {
156
+ hash = _gitUrl.slice(hashIndex);
157
+ _gitUrl = _gitUrl.slice(0, hashIndex);
158
+ }
159
+ const [auth, ...pathname] = _gitUrl.slice(6).split('/');
160
+ const [, host] = auth.split('@');
161
+ if (host.includes(':') && !/:\d+$/.test(host)) {
162
+ const authArr = auth.split(':');
163
+ const protocol = gitUrl.split('://')[0];
164
+ gitUrl = `${protocol}://${authArr.slice(0, -1).join(':') + '/' + authArr[authArr.length - 1]}${pathname.length ? '/' + pathname.join('/') : ''}${hash}`;
165
+ }
166
+ }
167
+ return gitUrl;
168
+ }
169
+ //# sourceMappingURL=parseBareSpecifier.js.map
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@pnpm/resolving.git-resolver",
3
+ "version": "1001.1.5",
4
+ "description": "Resolver for git-hosted packages",
5
+ "keywords": [
6
+ "pnpm",
7
+ "pnpm11",
8
+ "npm",
9
+ "resolver"
10
+ ],
11
+ "license": "MIT",
12
+ "funding": "https://opencollective.com/pnpm",
13
+ "repository": "https://github.com/pnpm/pnpm/tree/main/resolving/git-resolver",
14
+ "homepage": "https://github.com/pnpm/pnpm/tree/main/resolving/git-resolver#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/pnpm/pnpm/issues"
17
+ },
18
+ "type": "module",
19
+ "main": "lib/index.js",
20
+ "types": "lib/index.d.ts",
21
+ "exports": {
22
+ ".": "./lib/index.js"
23
+ },
24
+ "files": [
25
+ "lib",
26
+ "!*.map"
27
+ ],
28
+ "dependencies": {
29
+ "graceful-git": "^5.0.0",
30
+ "hosted-git-info": "npm:@pnpm/hosted-git-info@1.0.0",
31
+ "semver": "^7.7.2",
32
+ "@pnpm/error": "1000.0.5",
33
+ "@pnpm/resolving.resolver-base": "1005.1.0",
34
+ "@pnpm/network.fetch": "1000.2.6"
35
+ },
36
+ "devDependencies": {
37
+ "@jest/globals": "30.0.5",
38
+ "@pnpm/network.agent": "^2.0.3",
39
+ "@types/hosted-git-info": "^3.0.5",
40
+ "@types/is-windows": "^1.0.2",
41
+ "@types/semver": "7.7.1",
42
+ "is-windows": "^1.0.2",
43
+ "@pnpm/resolving.git-resolver": "1001.1.5"
44
+ },
45
+ "engines": {
46
+ "node": ">=22.13"
47
+ },
48
+ "jest": {
49
+ "preset": "@pnpm/jest-config"
50
+ },
51
+ "scripts": {
52
+ "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
53
+ "_test": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules --disable-warning=ExperimentalWarning --disable-warning=DEP0169\" jest",
54
+ "test": "pnpm run compile && pnpm run _test",
55
+ "fix": "tslint -c tslint.json src/**/*.ts test/**/*.ts --fix",
56
+ "compile": "tsgo --build && pnpm run lint --fix"
57
+ }
58
+ }