forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpackage-metadata.ts
332 lines (289 loc) · 9.65 KB
/
package-metadata.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { logging } from '@angular-devkit/core';
import * as lockfile from '@yarnpkg/lockfile';
import * as ini from 'ini';
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import * as path from 'node:path';
import type { Manifest, Packument } from 'pacote';
export interface PackageMetadata extends Packument, NgPackageManifestProperties {
tags: Record<string, PackageManifest>;
versions: Record<string, PackageManifest>;
}
export interface NpmRepositoryPackageJson extends PackageMetadata {
requestedName?: string;
}
export type NgAddSaveDependency = 'dependencies' | 'devDependencies' | boolean;
export interface PackageIdentifier {
type: 'git' | 'tag' | 'version' | 'range' | 'file' | 'directory' | 'remote';
name: string;
scope: string | null;
registry: boolean;
raw: string;
fetchSpec: string;
rawSpec: string;
}
export interface NgPackageManifestProperties {
'ng-add'?: {
save?: NgAddSaveDependency;
};
'ng-update'?: {
migrations?: string;
packageGroup?: string[] | Record<string, string>;
packageGroupName?: string;
requirements?: string[] | Record<string, string>;
};
}
export interface PackageManifest extends Manifest, NgPackageManifestProperties {
deprecated?: boolean;
}
interface PackageManagerOptions extends Record<string, unknown> {
forceAuth?: Record<string, unknown>;
}
let npmrc: PackageManagerOptions;
const npmPackageJsonCache = new Map<string, Promise<Partial<NpmRepositoryPackageJson>>>();
function ensureNpmrc(logger: logging.LoggerApi, usingYarn: boolean, verbose: boolean): void {
if (!npmrc) {
try {
npmrc = readOptions(logger, false, verbose);
} catch {}
if (usingYarn) {
try {
npmrc = { ...npmrc, ...readOptions(logger, true, verbose) };
} catch {}
}
}
}
function readOptions(
logger: logging.LoggerApi,
yarn = false,
showPotentials = false,
): PackageManagerOptions {
const cwd = process.cwd();
const baseFilename = yarn ? 'yarnrc' : 'npmrc';
const dotFilename = '.' + baseFilename;
let globalPrefix: string;
if (process.env.PREFIX) {
globalPrefix = process.env.PREFIX;
} else {
globalPrefix = path.dirname(process.execPath);
if (process.platform !== 'win32') {
globalPrefix = path.dirname(globalPrefix);
}
}
const defaultConfigLocations = [
(!yarn && process.env.NPM_CONFIG_GLOBALCONFIG) || path.join(globalPrefix, 'etc', baseFilename),
(!yarn && process.env.NPM_CONFIG_USERCONFIG) || path.join(homedir(), dotFilename),
];
const projectConfigLocations: string[] = [path.join(cwd, dotFilename)];
if (yarn) {
const root = path.parse(cwd).root;
for (let curDir = path.dirname(cwd); curDir && curDir !== root; curDir = path.dirname(curDir)) {
projectConfigLocations.unshift(path.join(curDir, dotFilename));
}
}
if (showPotentials) {
logger.info(`Locating potential ${baseFilename} files:`);
}
let rcOptions: PackageManagerOptions = {};
for (const location of [...defaultConfigLocations, ...projectConfigLocations]) {
if (existsSync(location)) {
if (showPotentials) {
logger.info(`Trying '${location}'...found.`);
}
const data = readFileSync(location, 'utf8');
// Normalize RC options that are needed by 'npm-registry-fetch'.
// See: https://github.com/npm/npm-registry-fetch/blob/ebddbe78a5f67118c1f7af2e02c8a22bcaf9e850/index.js#L99-L126
const rcConfig: PackageManagerOptions = yarn ? lockfile.parse(data) : ini.parse(data);
rcOptions = normalizeOptions(rcConfig, location, rcOptions);
}
}
const envVariablesOptions: PackageManagerOptions = {};
for (const [key, value] of Object.entries(process.env)) {
if (!value) {
continue;
}
let normalizedName = key.toLowerCase();
if (normalizedName.startsWith('npm_config_')) {
normalizedName = normalizedName.substring(11);
} else if (yarn && normalizedName.startsWith('yarn_')) {
normalizedName = normalizedName.substring(5);
} else {
continue;
}
if (
normalizedName === 'registry' &&
rcOptions['registry'] &&
value === 'https://registry.yarnpkg.com' &&
process.env['npm_config_user_agent']?.includes('yarn')
) {
// When running `ng update` using yarn (`yarn ng update`), yarn will set the `npm_config_registry` env variable to `https://registry.yarnpkg.com`
// even when an RC file is present with a different repository.
// This causes the registry specified in the RC to always be overridden with the below logic.
continue;
}
normalizedName = normalizedName.replace(/(?!^)_/g, '-'); // don't replace _ at the start of the key.s
envVariablesOptions[normalizedName] = value;
}
return normalizeOptions(envVariablesOptions, undefined, rcOptions);
}
function normalizeOptions(
rawOptions: PackageManagerOptions,
location = process.cwd(),
existingNormalizedOptions: PackageManagerOptions = {},
): PackageManagerOptions {
const options = { ...existingNormalizedOptions };
for (const [key, value] of Object.entries(rawOptions)) {
let substitutedValue = value;
// Substitute any environment variable references.
if (typeof value === 'string') {
substitutedValue = value.replace(/\$\{([^}]+)\}/, (_, name) => process.env[name] || '');
}
switch (key) {
// Unless auth options are scope with the registry url it appears that npm-registry-fetch ignores them,
// even though they are documented.
// https://github.com/npm/npm-registry-fetch/blob/8954f61d8d703e5eb7f3d93c9b40488f8b1b62ac/README.md
// https://github.com/npm/npm-registry-fetch/blob/8954f61d8d703e5eb7f3d93c9b40488f8b1b62ac/auth.js#L45-L91
case '_authToken':
case 'token':
case 'username':
case 'password':
case '_auth':
case 'auth':
options['forceAuth'] ??= {};
options['forceAuth'][key] = substitutedValue;
break;
case 'noproxy':
case 'no-proxy':
options['noProxy'] = substitutedValue;
break;
case 'maxsockets':
options['maxSockets'] = substitutedValue;
break;
case 'https-proxy':
case 'proxy':
options['proxy'] = substitutedValue;
break;
case 'strict-ssl':
options['strictSSL'] = substitutedValue;
break;
case 'local-address':
options['localAddress'] = substitutedValue;
break;
case 'cafile':
if (typeof substitutedValue === 'string') {
const cafile = path.resolve(path.dirname(location), substitutedValue);
try {
options['ca'] = readFileSync(cafile, 'utf8').replace(/\r?\n/g, '\n');
} catch {}
}
break;
case 'before':
options['before'] =
typeof substitutedValue === 'string' ? new Date(substitutedValue) : substitutedValue;
break;
default:
options[key] = substitutedValue;
break;
}
}
return options;
}
export async function fetchPackageMetadata(
name: string,
logger: logging.LoggerApi,
options?: {
registry?: string;
usingYarn?: boolean;
verbose?: boolean;
},
): Promise<PackageMetadata> {
const { usingYarn, verbose, registry } = {
registry: undefined,
usingYarn: false,
verbose: false,
...options,
};
ensureNpmrc(logger, usingYarn, verbose);
const { packument } = await import('pacote');
const response = await packument(name, {
fullMetadata: true,
...npmrc,
...(registry ? { registry } : {}),
});
if (!response.versions) {
// While pacote type declares that versions cannot be undefined this is not the case.
response.versions = {};
}
// Normalize the response
const metadata: PackageMetadata = {
...response,
tags: {},
};
if (response['dist-tags']) {
for (const [tag, version] of Object.entries(response['dist-tags'])) {
const manifest = metadata.versions[version];
if (manifest) {
metadata.tags[tag] = manifest;
} else if (verbose) {
logger.warn(`Package ${metadata.name} has invalid version metadata for '${tag}'.`);
}
}
}
return metadata;
}
export async function fetchPackageManifest(
name: string,
logger: logging.LoggerApi,
options: {
registry?: string;
usingYarn?: boolean;
verbose?: boolean;
} = {},
): Promise<PackageManifest> {
const { usingYarn = false, verbose = false, registry } = options;
ensureNpmrc(logger, usingYarn, verbose);
const { manifest } = await import('pacote');
const response = await manifest(name, {
fullMetadata: true,
...npmrc,
...(registry ? { registry } : {}),
});
return response;
}
export async function getNpmPackageJson(
packageName: string,
logger: logging.LoggerApi,
options: {
registry?: string;
usingYarn?: boolean;
verbose?: boolean;
} = {},
): Promise<Partial<NpmRepositoryPackageJson>> {
const cachedResponse = npmPackageJsonCache.get(packageName);
if (cachedResponse) {
return cachedResponse;
}
const { usingYarn = false, verbose = false, registry } = options;
ensureNpmrc(logger, usingYarn, verbose);
const { packument } = await import('pacote');
const response = packument(packageName, {
fullMetadata: true,
...npmrc,
...(registry ? { registry } : {}),
}).then((response) => {
// While pacote type declares that versions cannot be undefined this is not the case.
if (!response.versions) {
response.versions = {};
}
return response;
});
npmPackageJsonCache.set(packageName, response);
return response;
}