formacao
This commit is contained in:
+14
-1
@@ -57,16 +57,22 @@ export interface PackageManagerDescriptor {
|
||||
readonly versionCommand: readonly string[];
|
||||
/** The command to list all installed dependencies. */
|
||||
readonly listDependenciesCommand: readonly string[];
|
||||
/** The command to get the current package name. */
|
||||
readonly getPackageNameCommand?: readonly string[];
|
||||
/** The command to fetch the registry manifest of a package. */
|
||||
readonly getManifestCommand: readonly string[];
|
||||
/** Whether a specific version lookup is needed prior to fetching a registry manifest. */
|
||||
readonly requiresManifestVersionLookup?: boolean;
|
||||
/** A function that formats the arguments for field-filtered registry views. */
|
||||
readonly viewCommandFieldArgFormatter?: (fields: readonly string[]) => string[];
|
||||
/** An optional custom function to fetch registry metadata when the default logic is not sufficient. */
|
||||
readonly getRegistryMetadata?: (packageName: string, fetchAndParse: <T>(args: readonly string[], parser: (stdout: string, logger?: Logger) => T | null) => Promise<T | null>) => Promise<PackageMetadata | null>;
|
||||
/** A collection of functions to parse the output of specific commands. */
|
||||
readonly outputParsers: {
|
||||
/** A function to parse the output of `listDependenciesCommand`. */
|
||||
listDependencies: (stdout: string, logger?: Logger) => Map<string, InstalledPackage>;
|
||||
listDependencies: (stdout: string, logger?: Logger, options?: {
|
||||
workspacePackageName?: string;
|
||||
}) => Map<string, InstalledPackage>;
|
||||
/** A function to parse the output of `getManifestCommand` for a specific version. */
|
||||
getRegistryManifest: (stdout: string, logger?: Logger) => PackageManifest | null;
|
||||
/** A function to parse the output of `getManifestCommand` for the full package metadata. */
|
||||
@@ -115,6 +121,7 @@ export declare const SUPPORTED_PACKAGE_MANAGERS: {
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getPackageNameCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
viewCommandFieldArgFormatter: (fields: readonly string[]) => string[];
|
||||
outputParsers: {
|
||||
@@ -199,6 +206,7 @@ export declare const SUPPORTED_PACKAGE_MANAGERS: {
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getPackageNameCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
viewCommandFieldArgFormatter: (fields: readonly string[]) => string[];
|
||||
outputParsers: {
|
||||
@@ -228,6 +236,11 @@ export declare const SUPPORTED_PACKAGE_MANAGERS: {
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
getRegistryMetadata: (packageName: string, fetchAndParse: <T>(args: readonly string[], parser: (stdout: string, logger?: Logger) => T | null) => Promise<T | null>) => Promise<{
|
||||
name: string;
|
||||
'dist-tags': Record<string, string>;
|
||||
versions: string[];
|
||||
} | null>;
|
||||
outputParsers: {
|
||||
listDependencies: typeof parseBunDependencies;
|
||||
getRegistryManifest: typeof parseNpmLikeManifest;
|
||||
|
||||
+26
@@ -47,6 +47,7 @@ exports.SUPPORTED_PACKAGE_MANAGERS = {
|
||||
getRegistryOptions: (registry) => ({ args: ['--registry', registry] }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['list', '--depth=0', '--json=true', '--all=true'],
|
||||
getPackageNameCommand: ['pkg', 'get', 'name'],
|
||||
getManifestCommand: ['view', '--json'],
|
||||
viewCommandFieldArgFormatter: (fields) => [...fields],
|
||||
outputParsers: {
|
||||
@@ -126,6 +127,7 @@ exports.SUPPORTED_PACKAGE_MANAGERS = {
|
||||
getRegistryOptions: (registry) => ({ args: ['--registry', registry] }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['list', '--depth=0', '--json'],
|
||||
getPackageNameCommand: ['pkg', 'get', 'name'],
|
||||
getManifestCommand: ['view', '--json'],
|
||||
viewCommandFieldArgFormatter: (fields) => [...fields],
|
||||
outputParsers: {
|
||||
@@ -153,6 +155,30 @@ exports.SUPPORTED_PACKAGE_MANAGERS = {
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['pm', 'ls'],
|
||||
getManifestCommand: ['pm', 'view', '--json'],
|
||||
getRegistryMetadata: async (packageName, fetchAndParse) => {
|
||||
const [distTags, versions] = await Promise.all([
|
||||
fetchAndParse(['pm', 'view', '--json', packageName, 'dist-tags'], (stdout) => {
|
||||
if (!stdout) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}),
|
||||
fetchAndParse(['pm', 'view', '--json', packageName, 'versions'], (stdout) => {
|
||||
if (!stdout) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}),
|
||||
]);
|
||||
if (!distTags || !versions) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
name: packageName,
|
||||
'dist-tags': distTags,
|
||||
versions: versions,
|
||||
};
|
||||
},
|
||||
outputParsers: {
|
||||
listDependencies: parsers_1.parseBunDependencies,
|
||||
getRegistryManifest: parsers_1.parseNpmLikeManifest,
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+4
@@ -108,6 +108,10 @@ export declare class PackageManager {
|
||||
ignoreScripts?: boolean;
|
||||
ignorePeerDependencies?: boolean;
|
||||
}): Promise<void>;
|
||||
/**
|
||||
* Gets the name of the package in the current project.
|
||||
*/
|
||||
getCurrentPackageName(): Promise<string | undefined>;
|
||||
/**
|
||||
* Gets the version of the package manager binary.
|
||||
*/
|
||||
|
||||
+48
-8
@@ -106,7 +106,8 @@ class PackageManager {
|
||||
return this.#dependencyCache;
|
||||
}
|
||||
const args = this.descriptor.listDependenciesCommand;
|
||||
const dependencies = await this.#fetchAndParse(args, (stdout, logger) => this.descriptor.outputParsers.listDependencies(stdout, logger));
|
||||
const workspacePackageName = await this.getCurrentPackageName();
|
||||
const dependencies = await this.#fetchAndParse(args, (stdout, logger) => this.descriptor.outputParsers.listDependencies(stdout, logger, { workspacePackageName }));
|
||||
return (this.#dependencyCache = dependencies ?? new Map());
|
||||
}
|
||||
/**
|
||||
@@ -236,7 +237,8 @@ class PackageManager {
|
||||
noLockfile ? this.descriptor.noLockfileFlag : '',
|
||||
ignoreScripts ? this.descriptor.ignoreScriptsFlag : '',
|
||||
].filter((flag) => flag);
|
||||
const args = [this.descriptor.addCommand, packageName, ...flags];
|
||||
const specifier = this.host.requiresQuoting ? `"${packageName}"` : packageName;
|
||||
const args = [this.descriptor.addCommand, specifier, ...flags];
|
||||
await this.#run(args, options);
|
||||
this.#dependencyCache = null;
|
||||
}
|
||||
@@ -259,6 +261,30 @@ class PackageManager {
|
||||
await this.#run(args, options);
|
||||
this.#dependencyCache = null;
|
||||
}
|
||||
/**
|
||||
* Gets the name of the package in the current project.
|
||||
*/
|
||||
async getCurrentPackageName() {
|
||||
if (this.descriptor.getPackageNameCommand) {
|
||||
try {
|
||||
const { stdout } = await this.#run(this.descriptor.getPackageNameCommand);
|
||||
if (stdout) {
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// Fall back to reading file if command fails
|
||||
}
|
||||
}
|
||||
try {
|
||||
const content = await this.host.readFile((0, node_path_1.join)(this.cwd, 'package.json'));
|
||||
const pkgJson = JSON.parse(content);
|
||||
return pkgJson.name;
|
||||
}
|
||||
catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets the version of the package manager binary.
|
||||
*/
|
||||
@@ -302,13 +328,27 @@ class PackageManager {
|
||||
* @returns A promise that resolves to the `PackageMetadata` object, or `null` if the package is not found.
|
||||
*/
|
||||
async getRegistryMetadata(packageName, options = {}) {
|
||||
const commandArgs = [...this.descriptor.getManifestCommand, packageName];
|
||||
const formatter = this.descriptor.viewCommandFieldArgFormatter;
|
||||
if (formatter) {
|
||||
commandArgs.push(...formatter(METADATA_FIELDS));
|
||||
}
|
||||
const cacheKey = options.registry ? `${packageName}|${options.registry}` : packageName;
|
||||
return this.#fetchAndParse(commandArgs, (stdout, logger) => this.descriptor.outputParsers.getRegistryMetadata(stdout, logger), { ...options, cache: this.#metadataCache, cacheKey });
|
||||
if (!options.bypassCache) {
|
||||
const cached = this.#metadataCache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
let metadata = null;
|
||||
if (this.descriptor.getRegistryMetadata) {
|
||||
metadata = await this.descriptor.getRegistryMetadata(packageName, (args, parser) => this.#fetchAndParse(args, parser, options));
|
||||
}
|
||||
else {
|
||||
const commandArgs = [...this.descriptor.getManifestCommand, packageName];
|
||||
const formatter = this.descriptor.viewCommandFieldArgFormatter;
|
||||
if (formatter) {
|
||||
commandArgs.push(...formatter(METADATA_FIELDS));
|
||||
}
|
||||
metadata = await this.#fetchAndParse(commandArgs, (stdout, logger) => this.descriptor.outputParsers.getRegistryMetadata(stdout, logger), options);
|
||||
}
|
||||
this.#metadataCache.set(cacheKey, metadata);
|
||||
return metadata;
|
||||
}
|
||||
/**
|
||||
* Fetches the registry manifest for a specific version of a package.
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+3
-6
@@ -5,11 +5,6 @@
|
||||
* 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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview This file contains the parser functions that are used to
|
||||
* interpret the output of various package manager commands. Separating these
|
||||
* into their own file improves modularity and allows for focused testing.
|
||||
*/
|
||||
import { ErrorInfo } from './error';
|
||||
import { Logger } from './logger';
|
||||
import { PackageManifest, PackageMetadata } from './package-metadata';
|
||||
@@ -34,7 +29,9 @@ import { InstalledPackage } from './package-tree';
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
export declare function parseNpmLikeDependencies(stdout: string, logger?: Logger): Map<string, InstalledPackage>;
|
||||
export declare function parseNpmLikeDependencies(stdout: string, logger?: Logger, options?: {
|
||||
workspacePackageName?: string;
|
||||
}): Map<string, InstalledPackage>;
|
||||
/**
|
||||
* Parses the output of `yarn list` (classic).
|
||||
*
|
||||
|
||||
+84
-7
@@ -17,6 +17,12 @@ exports.parseNpmLikeError = parseNpmLikeError;
|
||||
exports.parseYarnClassicError = parseYarnClassicError;
|
||||
exports.parseBunDependencies = parseBunDependencies;
|
||||
exports.parseYarnModernDependencies = parseYarnModernDependencies;
|
||||
/**
|
||||
* @fileoverview This file contains the parser functions that are used to
|
||||
* interpret the output of various package manager commands. Separating these
|
||||
* into their own file improves modularity and allows for focused testing.
|
||||
*/
|
||||
const semver_1 = require("semver");
|
||||
const MAX_LOG_LENGTH = 1024;
|
||||
function logStdout(stdout, logger) {
|
||||
if (!logger) {
|
||||
@@ -68,7 +74,7 @@ function* parseJsonLines(output, logger) {
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
function parseNpmLikeDependencies(stdout, logger) {
|
||||
function parseNpmLikeDependencies(stdout, logger, options) {
|
||||
logger?.debug(`Parsing npm-like dependency list...`);
|
||||
logStdout(stdout, logger);
|
||||
const dependencies = new Map();
|
||||
@@ -86,13 +92,48 @@ function parseNpmLikeDependencies(stdout, logger) {
|
||||
logger?.debug(' `dependencies` property not found. No dependencies found.');
|
||||
return dependencies;
|
||||
}
|
||||
const workspacePackageName = options?.workspacePackageName;
|
||||
if (workspacePackageName) {
|
||||
for (const dependencyMap of dependencyMaps) {
|
||||
const info = dependencyMap[workspacePackageName];
|
||||
if (info && typeof info === 'object') {
|
||||
const nestedMaps = [
|
||||
info.dependencies,
|
||||
info.devDependencies,
|
||||
info.unsavedDependencies,
|
||||
].filter((d) => !!d);
|
||||
for (const nestedMap of nestedMaps) {
|
||||
for (const [name, nestedInfo] of Object.entries(nestedMap)) {
|
||||
if (nestedInfo && typeof nestedInfo === 'object' && nestedInfo.version) {
|
||||
dependencies.set(name, {
|
||||
name,
|
||||
version: nestedInfo.version,
|
||||
path: nestedInfo.path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Extract top-level dependencies (root), without overwriting subproject dependencies
|
||||
for (const dependencyMap of dependencyMaps) {
|
||||
for (const [name, info] of Object.entries(dependencyMap)) {
|
||||
dependencies.set(name, {
|
||||
name,
|
||||
version: info.version,
|
||||
path: info.path,
|
||||
});
|
||||
if (!info || typeof info !== 'object') {
|
||||
continue;
|
||||
}
|
||||
// Exclude local monorepo workspace packages (which originate from a local file/dir
|
||||
// and contain nested dependency maps in the output of `npm list --depth=0`),
|
||||
// while preserving third-party packages installed from local paths.
|
||||
const isWorkspacePackage = info.resolved?.startsWith('file:') &&
|
||||
(!!info.dependencies || !!info.devDependencies || !!info.unsavedDependencies);
|
||||
if (info.version && !dependencies.has(name) && !isWorkspacePackage) {
|
||||
dependencies.set(name, {
|
||||
name,
|
||||
version: info.version,
|
||||
path: info.path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
logger?.debug(` Found ${dependencies.size} dependencies.`);
|
||||
@@ -137,6 +178,15 @@ function parseYarnClassicDependencies(stdout, logger) {
|
||||
logger?.debug(` Found ${dependencies.size} dependencies.`);
|
||||
return dependencies;
|
||||
}
|
||||
function isValidManifest(obj) {
|
||||
if (typeof obj !== 'object' || obj === null) {
|
||||
return false;
|
||||
}
|
||||
const record = obj;
|
||||
const name = record.name;
|
||||
const version = record.version;
|
||||
return typeof name === 'string' && typeof version === 'string' && (0, semver_1.valid)(version) !== null;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `npm view` or a compatible command to get a package manifest.
|
||||
* @param stdout The standard output of the command.
|
||||
@@ -151,7 +201,30 @@ function parseNpmLikeManifest(stdout, logger) {
|
||||
return null;
|
||||
}
|
||||
const result = JSON.parse(stdout);
|
||||
return Array.isArray(result) ? result[result.length - 1] : result;
|
||||
// npm view returns an array of manifests if the query matches multiple versions
|
||||
// (e.g. when using a version range). We find the highest version to ensure
|
||||
// we get the latest relevant manifest, even if the output is not sorted.
|
||||
if (Array.isArray(result)) {
|
||||
let maxManifest = null;
|
||||
for (const manifest of result) {
|
||||
if (!isValidManifest(manifest)) {
|
||||
logger?.debug(' Skipping invalid manifest in array (missing name, version, or invalid SemVer).');
|
||||
continue;
|
||||
}
|
||||
if (!maxManifest || (0, semver_1.compare)(manifest.version, maxManifest.version) > 0) {
|
||||
maxManifest = manifest;
|
||||
}
|
||||
}
|
||||
if (!maxManifest) {
|
||||
logger?.debug(' No valid manifests found in the array.');
|
||||
}
|
||||
return maxManifest;
|
||||
}
|
||||
if (!isValidManifest(result)) {
|
||||
logger?.debug(' Parsed JSON is not a valid manifest (missing name, version, or invalid SemVer).');
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `npm view` or a compatible command to get package metadata.
|
||||
@@ -212,6 +285,10 @@ function parseYarnClassicManifest(stdout, logger) {
|
||||
Object.keys(manifest['ng-add']).length === 0) {
|
||||
manifest['ng-add'].save ??= false;
|
||||
}
|
||||
if (!isValidManifest(manifest)) {
|
||||
logger?.debug(' Parsed JSON is not a valid manifest (missing name, version, or invalid SemVer).');
|
||||
return null;
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
/**
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user