Primeiro commit do projeto Angular
This commit is contained in:
+23
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @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 { Host } from './host';
|
||||
import { Logger } from './logger';
|
||||
import { PackageManagerName } from './package-manager-descriptor';
|
||||
/**
|
||||
* Discovers the package manager used in a project by searching for lockfiles.
|
||||
*
|
||||
* This function searches for lockfiles in the given directory and its ancestors.
|
||||
* If multiple lockfiles are found, it uses the precedence array to determine
|
||||
* which package manager to use. The search is bounded by the git repository root.
|
||||
*
|
||||
* @param host A `Host` instance for interacting with the file system.
|
||||
* @param startDir The directory to start the search from.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A promise that resolves to the name of the discovered package manager, or null if none is found.
|
||||
*/
|
||||
export declare function discover(host: Host, startDir: string, logger?: Logger): Promise<PackageManagerName | null>;
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.discover = discover;
|
||||
/**
|
||||
* @fileoverview This file contains the logic for discovering the package manager
|
||||
* used in a project by searching for lockfiles. It is designed to be efficient
|
||||
* and to correctly handle monorepo structures.
|
||||
*/
|
||||
const node_path_1 = require("node:path");
|
||||
const package_manager_descriptor_1 = require("./package-manager-descriptor");
|
||||
/**
|
||||
* Searches a directory for lockfiles and returns a set of package managers that correspond to them.
|
||||
* @param host A `Host` instance for interacting with the file system.
|
||||
* @param directory The directory to search.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A promise that resolves to a set of package manager names.
|
||||
*/
|
||||
async function findLockfiles(host, directory, logger) {
|
||||
logger?.debug(`Searching for lockfiles in '${directory}'...`);
|
||||
const foundPackageManagers = new Set();
|
||||
const checks = [];
|
||||
for (const [name, descriptor] of Object.entries(package_manager_descriptor_1.SUPPORTED_PACKAGE_MANAGERS)) {
|
||||
const manager = name;
|
||||
for (const lockfile of descriptor.lockfiles) {
|
||||
checks.push((async () => {
|
||||
try {
|
||||
const path = (0, node_path_1.join)(directory, lockfile);
|
||||
const stats = await host.stat(path);
|
||||
if (stats.isFile()) {
|
||||
logger?.debug(` Found '${lockfile}'.`);
|
||||
foundPackageManagers.add(manager);
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// File does not exist or cannot be accessed.
|
||||
}
|
||||
})());
|
||||
}
|
||||
}
|
||||
await Promise.all(checks);
|
||||
return foundPackageManagers;
|
||||
}
|
||||
/**
|
||||
* Checks if a given path is a directory.
|
||||
* @param host A `Host` instance for interacting with the file system.
|
||||
* @param path The path to check.
|
||||
* @returns A promise that resolves to true if the path is a directory, false otherwise.
|
||||
*/
|
||||
async function isDirectory(host, path) {
|
||||
try {
|
||||
return (await host.stat(path)).isDirectory();
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Discovers the package manager used in a project by searching for lockfiles.
|
||||
*
|
||||
* This function searches for lockfiles in the given directory and its ancestors.
|
||||
* If multiple lockfiles are found, it uses the precedence array to determine
|
||||
* which package manager to use. The search is bounded by the git repository root.
|
||||
*
|
||||
* @param host A `Host` instance for interacting with the file system.
|
||||
* @param startDir The directory to start the search from.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A promise that resolves to the name of the discovered package manager, or null if none is found.
|
||||
*/
|
||||
async function discover(host, startDir, logger) {
|
||||
logger?.debug(`Starting package manager discovery in '${startDir}'...`);
|
||||
let currentDir = startDir;
|
||||
while (true) {
|
||||
const found = await findLockfiles(host, currentDir, logger);
|
||||
if (found.size > 0) {
|
||||
logger?.debug(`Found lockfile(s): [${[...found].join(', ')}]. Applying precedence...`);
|
||||
for (const packageManager of package_manager_descriptor_1.PACKAGE_MANAGER_PRECEDENCE) {
|
||||
if (found.has(packageManager)) {
|
||||
logger?.debug(`Selected '${packageManager}' based on precedence.`);
|
||||
return packageManager;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stop searching if we reach the git repository root.
|
||||
if (await isDirectory(host, (0, node_path_1.join)(currentDir, '.git'))) {
|
||||
logger?.debug(`Reached repository root at '${currentDir}'. Stopping search.`);
|
||||
return null;
|
||||
}
|
||||
const parentDir = (0, node_path_1.dirname)(currentDir);
|
||||
if (parentDir === currentDir) {
|
||||
// We have reached the filesystem root.
|
||||
logger?.debug('Reached filesystem root. No lockfile found.');
|
||||
return null;
|
||||
}
|
||||
currentDir = parentDir;
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=discovery.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["discovery.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAqFH,4BAuCC;AA1HD;;;;GAIG;AAEH,yCAA0C;AAG1C,6EAIsC;AAEtC;;;;;;GAMG;AACH,KAAK,UAAU,aAAa,CAC1B,IAAU,EACV,SAAiB,EACjB,MAAe;IAEf,MAAM,EAAE,KAAK,CAAC,+BAA+B,SAAS,MAAM,CAAC,CAAC;IAE9D,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAsB,CAAC;IAC3D,MAAM,MAAM,GAAoB,EAAE,CAAC;IAEnC,KAAK,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,uDAA0B,CAAC,EAAE,CAAC;QAC5E,MAAM,OAAO,GAAG,IAA0B,CAAC;QAC3C,KAAK,MAAM,QAAQ,IAAI,UAAU,CAAC,SAAS,EAAE,CAAC;YAC5C,MAAM,CAAC,IAAI,CACT,CAAC,KAAK,IAAI,EAAE;gBACV,IAAI,CAAC;oBACH,MAAM,IAAI,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,QAAQ,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CAAC;gBACxD,IAAI,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;oBAC9B,MAAM,EAAE,KAAK,CAAC,aAAa,cAAc,wBAAwB,CAAC,CAAC;oBAEnE,OAAO,cAAc,CAAC;gBACxB,CAAC;YACH,CAAC;QACH,CAAC;QAED,sDAAsD;QACtD,IAAI,MAAM,WAAW,CAAC,IAAI,EAAE,IAAA,gBAAI,EAAC,UAAU,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC;YACtD,MAAM,EAAE,KAAK,CAAC,+BAA+B,UAAU,qBAAqB,CAAC,CAAC;YAE9E,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,SAAS,GAAG,IAAA,mBAAO,EAAC,UAAU,CAAC,CAAC;QACtC,IAAI,SAAS,KAAK,UAAU,EAAE,CAAC;YAC7B,uCAAuC;YACvC,MAAM,EAAE,KAAK,CAAC,6CAA6C,CAAC,CAAC;YAE7D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;AACH,CAAC"}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview This file defines a custom error class for the package manager
|
||||
* abstraction. This allows for structured error handling and provides consumers
|
||||
* with detailed information about the process failure.
|
||||
*/
|
||||
/**
|
||||
* A custom error class for package manager-related errors.
|
||||
*
|
||||
* This error class provides structured data about the failed process,
|
||||
* including stdout, stderr, and the exit code.
|
||||
*/
|
||||
export declare class PackageManagerError extends Error {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number | null;
|
||||
/**
|
||||
* Creates a new `PackageManagerError` instance.
|
||||
* @param message The error message.
|
||||
* @param stdout The standard output of the failed process.
|
||||
* @param stderr The standard error of the failed process.
|
||||
* @param exitCode The exit code of the failed process.
|
||||
*/
|
||||
constructor(message: string, stdout: string, stderr: string, exitCode: number | null);
|
||||
}
|
||||
/**
|
||||
* Represents structured information about an error returned by a package manager command.
|
||||
* This is a data interface, not an `Error` subclass.
|
||||
*/
|
||||
export interface ErrorInfo {
|
||||
/** A specific error code (e.g. 'E404', 'EACCES'). */
|
||||
readonly code: string;
|
||||
/** A short, human-readable summary of the error. */
|
||||
readonly summary: string;
|
||||
/** An optional, detailed description of the error. */
|
||||
readonly detail?: string;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PackageManagerError = void 0;
|
||||
/**
|
||||
* @fileoverview This file defines a custom error class for the package manager
|
||||
* abstraction. This allows for structured error handling and provides consumers
|
||||
* with detailed information about the process failure.
|
||||
*/
|
||||
/**
|
||||
* A custom error class for package manager-related errors.
|
||||
*
|
||||
* This error class provides structured data about the failed process,
|
||||
* including stdout, stderr, and the exit code.
|
||||
*/
|
||||
class PackageManagerError extends Error {
|
||||
stdout;
|
||||
stderr;
|
||||
exitCode;
|
||||
/**
|
||||
* Creates a new `PackageManagerError` instance.
|
||||
* @param message The error message.
|
||||
* @param stdout The standard output of the failed process.
|
||||
* @param stderr The standard error of the failed process.
|
||||
* @param exitCode The exit code of the failed process.
|
||||
*/
|
||||
constructor(message, stdout, stderr, exitCode) {
|
||||
super(message);
|
||||
this.stdout = stdout;
|
||||
this.stderr = stderr;
|
||||
this.exitCode = exitCode;
|
||||
}
|
||||
}
|
||||
exports.PackageManagerError = PackageManagerError;
|
||||
//# sourceMappingURL=error.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error.js","sourceRoot":"","sources":["error.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH;;;;GAIG;AAEH;;;;;GAKG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAU1B;IACA;IACA;IAXlB;;;;;;OAMG;IACH,YACE,OAAe,EACC,MAAc,EACd,MAAc,EACd,QAAuB;QAEvC,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;QACd,aAAQ,GAAR,QAAQ,CAAe;IAGzC,CAAC;CACF;AAhBD,kDAgBC"}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* @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 { Logger } from './logger';
|
||||
import { PackageManager } from './package-manager';
|
||||
import { PackageManagerName } from './package-manager-descriptor';
|
||||
/**
|
||||
* Information about the package manager to use for a given project.
|
||||
*/
|
||||
export type ConfiguredPackageManagerInfo = [name?: PackageManagerName, version?: string];
|
||||
/**
|
||||
* Creates a new `PackageManager` instance for a given project.
|
||||
*
|
||||
* This function is the main entry point for the package manager abstraction.
|
||||
* It will determine, verify, and instantiate the correct package manager.
|
||||
*
|
||||
* @param options An object containing the options for creating the package manager.
|
||||
* @returns A promise that resolves to a new `PackageManager` instance.
|
||||
*/
|
||||
export declare function createPackageManager(options: {
|
||||
cwd: string;
|
||||
configuredPackageManager?: ConfiguredPackageManagerInfo;
|
||||
logger?: Logger;
|
||||
dryRun?: boolean;
|
||||
tempDirectory?: string;
|
||||
}): Promise<PackageManager>;
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createPackageManager = createPackageManager;
|
||||
const strict_1 = __importDefault(require("node:assert/strict"));
|
||||
const semver_1 = require("semver");
|
||||
const discovery_1 = require("./discovery");
|
||||
const host_1 = require("./host");
|
||||
const package_manager_1 = require("./package-manager");
|
||||
const package_manager_descriptor_1 = require("./package-manager-descriptor");
|
||||
/**
|
||||
* The default package manager to use when none is discovered or configured.
|
||||
*/
|
||||
const DEFAULT_PACKAGE_MANAGER = 'npm';
|
||||
/**
|
||||
* Gets the version of the package manager.
|
||||
* @param host A `Host` instance for running commands.
|
||||
* @param cwd The absolute path to the working directory.
|
||||
* @param name The name of the package manager.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A promise that resolves to the version string.
|
||||
*/
|
||||
async function getPackageManagerVersion(host, cwd, name, logger) {
|
||||
const descriptor = package_manager_descriptor_1.SUPPORTED_PACKAGE_MANAGERS[name];
|
||||
logger?.debug(`Getting ${name} version...`);
|
||||
const { stdout } = await host.runCommand(descriptor.binary, descriptor.versionCommand, { cwd });
|
||||
const version = stdout.trim();
|
||||
logger?.debug(`${name} version is '${version}'.`);
|
||||
return version;
|
||||
}
|
||||
/**
|
||||
* Determines the package manager to use for a given project.
|
||||
*
|
||||
* This function will determine the package manager by checking for a configured
|
||||
* package manager, discovering the package manager from lockfiles, or falling
|
||||
* back to a default. It also handles differentiation between yarn classic and modern.
|
||||
*
|
||||
* @param host A `Host` instance for interacting with the file system and running commands.
|
||||
* @param cwd The directory to start the search from.
|
||||
* @param configured An optional, explicitly configured package manager.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A promise that resolves to an object containing the name and source of the package manager.
|
||||
*/
|
||||
async function determinePackageManager(host, cwd, configured = [], logger, dryRun) {
|
||||
let [name, version] = configured;
|
||||
let source;
|
||||
if (name) {
|
||||
source = 'configured';
|
||||
logger?.debug(`Using configured package manager: '${name}'.`);
|
||||
}
|
||||
else {
|
||||
const discovered = await (0, discovery_1.discover)(host, cwd, logger);
|
||||
if (discovered) {
|
||||
name = discovered;
|
||||
source = 'discovered';
|
||||
logger?.debug(`Discovered package manager: '${name}'.`);
|
||||
}
|
||||
else {
|
||||
name = DEFAULT_PACKAGE_MANAGER;
|
||||
source = 'default';
|
||||
logger?.debug(`No lockfile found. Using default package manager: '${DEFAULT_PACKAGE_MANAGER}'.`);
|
||||
}
|
||||
}
|
||||
if (name === 'yarn' && !dryRun) {
|
||||
strict_1.default.deepStrictEqual(package_manager_descriptor_1.SUPPORTED_PACKAGE_MANAGERS.yarn.versionCommand, package_manager_descriptor_1.SUPPORTED_PACKAGE_MANAGERS['yarn-classic'].versionCommand, 'Yarn and Yarn Classic version commands must match for detection logic to be valid.');
|
||||
try {
|
||||
version ??= await getPackageManagerVersion(host, cwd, name, logger);
|
||||
if (version && (0, semver_1.major)(version) < 2) {
|
||||
name = 'yarn-classic';
|
||||
logger?.debug(`Detected yarn classic. Using 'yarn-classic'.`);
|
||||
}
|
||||
}
|
||||
catch {
|
||||
logger?.debug('Failed to get yarn version.');
|
||||
}
|
||||
}
|
||||
else if (name === 'yarn') {
|
||||
logger?.debug('Skipping yarn version check due to dry run. Assuming modern yarn.');
|
||||
}
|
||||
return { name, source, version };
|
||||
}
|
||||
/**
|
||||
* Creates a new `PackageManager` instance for a given project.
|
||||
*
|
||||
* This function is the main entry point for the package manager abstraction.
|
||||
* It will determine, verify, and instantiate the correct package manager.
|
||||
*
|
||||
* @param options An object containing the options for creating the package manager.
|
||||
* @returns A promise that resolves to a new `PackageManager` instance.
|
||||
*/
|
||||
async function createPackageManager(options) {
|
||||
const { cwd, configuredPackageManager, logger, dryRun, tempDirectory } = options;
|
||||
const host = host_1.NodeJS_HOST;
|
||||
const result = await determinePackageManager(host, cwd, configuredPackageManager, logger, dryRun);
|
||||
const { name, source } = result;
|
||||
let { version } = result;
|
||||
const descriptor = package_manager_descriptor_1.SUPPORTED_PACKAGE_MANAGERS[name];
|
||||
if (!descriptor) {
|
||||
throw new Error(`Unsupported package manager: "${name}"`);
|
||||
}
|
||||
// Do not verify if the package manager is installed during a dry run.
|
||||
let initializationError;
|
||||
if (!dryRun && !version) {
|
||||
try {
|
||||
version = await getPackageManagerVersion(host, cwd, name, logger);
|
||||
}
|
||||
catch {
|
||||
if (source === 'default') {
|
||||
initializationError = new Error(`'${DEFAULT_PACKAGE_MANAGER}' was selected as the default package manager, but it is not installed or` +
|
||||
` cannot be found in the PATH. Please install '${DEFAULT_PACKAGE_MANAGER}' to continue.`);
|
||||
}
|
||||
else {
|
||||
initializationError = new Error(`The project is configured to use '${name}', but it is not installed or cannot be` +
|
||||
` found in the PATH. Please install '${name}' to continue.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const packageManager = new package_manager_1.PackageManager(host, cwd, descriptor, {
|
||||
dryRun,
|
||||
logger,
|
||||
tempDirectory,
|
||||
version,
|
||||
initializationError,
|
||||
});
|
||||
logger?.debug(`Successfully created PackageManager for '${name}'.`);
|
||||
return packageManager;
|
||||
}
|
||||
//# sourceMappingURL=factory.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"factory.js","sourceRoot":"","sources":["factory.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;AAyHH,oDAkDC;AAzKD,gEAAwC;AACxC,mCAA+B;AAC/B,2CAAuC;AACvC,iCAA2C;AAE3C,uDAAmD;AACnD,6EAA8F;AAO9F;;GAEG;AACH,MAAM,uBAAuB,GAAuB,KAAK,CAAC;AAE1D;;;;;;;GAOG;AACH,KAAK,UAAU,wBAAwB,CACrC,IAAU,EACV,GAAW,EACX,IAAwB,EACxB,MAAe;IAEf,MAAM,UAAU,GAAG,uDAA0B,CAAC,IAAI,CAAC,CAAC;IACpD,MAAM,EAAE,KAAK,CAAC,WAAW,IAAI,aAAa,CAAC,CAAC;IAE5C,MAAM,EAAE,MAAM,EAAE,GAAG,MAA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AAE,CAAC;QACxB,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,wBAAwB,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QACpE,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;gBACzB,mBAAmB,GAAG,IAAI,KAAK,CAC7B,IAAI,uBAAuB,2EAA2E;oBACpG,iDAAiD,uBAAuB,gBAAgB,CAC3F,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,mBAAmB,GAAG,IAAI,KAAK,CAC7B,qCAAqC,IAAI,yCAAyC;oBAChF,uCAAuC,IAAI,gBAAgB,CAC9D,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,cAAc,GAAG,IAAI,gCAAc,CAAC,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE;QAC/D,MAAM;QACN,MAAM;QACN,aAAa;QACb,OAAO;QACP,mBAAmB;KACpB,CAAC,CAAC;IAEH,MAAM,EAAE,KAAK,CAAC,4CAA4C,IAAI,IAAI,CAAC,CAAC;IAEpE,OAAO,cAAc,CAAC;AACxB,CAAC"}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* @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 { Stats } from 'node:fs';
|
||||
/**
|
||||
* An abstraction layer for side-effectful operations.
|
||||
*/
|
||||
export interface Host {
|
||||
/**
|
||||
* Whether shell quoting is required for package manager specifiers.
|
||||
* This is typically true on Windows, where commands are executed in a shell.
|
||||
*/
|
||||
readonly requiresQuoting?: boolean;
|
||||
/**
|
||||
* Creates a directory.
|
||||
* @param path The path to the directory.
|
||||
* @param options Options for the directory creation.
|
||||
* @returns A promise that resolves when the directory is created.
|
||||
*/
|
||||
mkdir(path: string, options?: {
|
||||
recursive?: boolean;
|
||||
}): Promise<string | undefined>;
|
||||
/**
|
||||
* Gets the stats of a file or directory.
|
||||
* @param path The path to the file or directory.
|
||||
* @returns A promise that resolves to the stats.
|
||||
*/
|
||||
stat(path: string): Promise<Stats>;
|
||||
/**
|
||||
* Reads the content of a file.
|
||||
* @param path The path to the file.
|
||||
* @returns A promise that resolves to the file content as a string.
|
||||
*/
|
||||
readFile(path: string): Promise<string>;
|
||||
/**
|
||||
* Copies a file from the source path to the destination path.
|
||||
* @param src The path to the source file.
|
||||
* @param dest The path to the destination file.
|
||||
* @returns A promise that resolves when the copy is complete.
|
||||
*/
|
||||
copyFile(src: string, dest: string): Promise<void>;
|
||||
/**
|
||||
* Creates a new, unique temporary directory.
|
||||
* @param baseDir The base directory in which to create the temporary directory.
|
||||
* @returns A promise that resolves to the absolute path of the created directory.
|
||||
*/
|
||||
createTempDirectory(baseDir?: string): Promise<string>;
|
||||
/**
|
||||
* Deletes a directory recursively.
|
||||
* @param path The path to the directory to delete.
|
||||
* @returns A promise that resolves when the deletion is complete.
|
||||
*/
|
||||
deleteDirectory(path: string): Promise<void>;
|
||||
/**
|
||||
* Writes content to a file.
|
||||
* @param path The path to the file.
|
||||
* @param content The content to write.
|
||||
* @returns A promise that resolves when the write is complete.
|
||||
*/
|
||||
writeFile(path: string, content: string): Promise<void>;
|
||||
/**
|
||||
* Spawns a child process and returns a promise that resolves with the process's
|
||||
* output or rejects with a structured error.
|
||||
* @param command The command to run.
|
||||
* @param args The arguments to pass to the command.
|
||||
* @param options Options for the child process.
|
||||
* @returns A promise that resolves with the standard output and standard error of the command.
|
||||
*/
|
||||
runCommand(command: string, args: readonly string[], options?: {
|
||||
timeout?: number;
|
||||
stdio?: 'pipe' | 'ignore';
|
||||
cwd?: string;
|
||||
env?: Record<string, string>;
|
||||
}): Promise<{
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}>;
|
||||
}
|
||||
/**
|
||||
* A concrete implementation of the `Host` interface that uses the Node.js APIs.
|
||||
*/
|
||||
export declare const NodeJS_HOST: Host;
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.NodeJS_HOST = void 0;
|
||||
/**
|
||||
* @fileoverview
|
||||
* This file defines an abstraction layer for side-effectful operations, such as
|
||||
* file system access and command execution. This allows for easier testing by
|
||||
* enabling the injection of mock or test-specific implementations.
|
||||
*/
|
||||
const node_child_process_1 = require("node:child_process");
|
||||
const node_fs_1 = require("node:fs");
|
||||
const promises_1 = require("node:fs/promises");
|
||||
const node_os_1 = require("node:os");
|
||||
const node_path_1 = require("node:path");
|
||||
const error_1 = require("./error");
|
||||
/**
|
||||
* A concrete implementation of the `Host` interface that uses the Node.js APIs.
|
||||
*/
|
||||
exports.NodeJS_HOST = {
|
||||
stat: promises_1.stat,
|
||||
requiresQuoting: (0, node_os_1.platform)() === 'win32',
|
||||
mkdir: promises_1.mkdir,
|
||||
readFile: (path) => (0, promises_1.readFile)(path, { encoding: 'utf8' }),
|
||||
copyFile: (src, dest) => (0, promises_1.copyFile)(src, dest, node_fs_1.constants.COPYFILE_FICLONE),
|
||||
writeFile: promises_1.writeFile,
|
||||
createTempDirectory: (baseDir) => (0, promises_1.mkdtemp)((0, node_path_1.join)(baseDir ?? (0, node_os_1.tmpdir)(), 'angular-cli-tmp-packages-')),
|
||||
deleteDirectory: (path) => (0, promises_1.rm)(path, { recursive: true, force: true }),
|
||||
runCommand: async (command, args, options = {}) => {
|
||||
const signal = options.timeout ? AbortSignal.timeout(options.timeout) : undefined;
|
||||
const isWin32 = (0, node_os_1.platform)() === 'win32';
|
||||
return new Promise((resolve, reject) => {
|
||||
const spawnOptions = {
|
||||
shell: isWin32,
|
||||
stdio: options.stdio ?? 'pipe',
|
||||
signal,
|
||||
cwd: options.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...options.env,
|
||||
// NPM updater notifier will prevents the child process from closing until it timeout after 3 minutes.
|
||||
NO_UPDATE_NOTIFIER: '1',
|
||||
NPM_CONFIG_UPDATE_NOTIFIER: 'false',
|
||||
},
|
||||
};
|
||||
const childProcess = isWin32
|
||||
? (0, node_child_process_1.spawn)(`${command} ${args.join(' ')}`, spawnOptions)
|
||||
: (0, node_child_process_1.spawn)(command, args, spawnOptions);
|
||||
let stdout = '';
|
||||
childProcess.stdout?.on('data', (data) => (stdout += data.toString()));
|
||||
let stderr = '';
|
||||
childProcess.stderr?.on('data', (data) => (stderr += data.toString()));
|
||||
childProcess.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
}
|
||||
else {
|
||||
const message = `Process exited with code ${code}.`;
|
||||
reject(new error_1.PackageManagerError(message, stdout, stderr, code));
|
||||
}
|
||||
});
|
||||
childProcess.on('error', (err) => {
|
||||
if (err.name === 'AbortError') {
|
||||
const message = `Process timed out.`;
|
||||
reject(new error_1.PackageManagerError(message, stdout, stderr, null));
|
||||
return;
|
||||
}
|
||||
const message = `Process failed with error: ${err.message}`;
|
||||
reject(new error_1.PackageManagerError(message, stdout, stderr, null));
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
//# sourceMappingURL=host.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"host.js","sourceRoot":"","sources":["host.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH;;;;;GAKG;AAEH,2DAA8D;AAC9D,qCAA2C;AAC3C,+CAAoG;AACpG,qCAA2C;AAC3C,yCAAiC;AACjC,mCAA8C;AAoF9C;;GAEG;AACU,QAAA,WAAW,GAAS;IAC/B,IAAI,EAAJ,eAAI;IACJ,eAAe,EAAE,IAAA,kBAAQ,GAAE,KAAK,OAAO;IACvC,KAAK,EAAL,gBAAK;IACL,QAAQ,EAAE,CAAC,IAAY,E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gBACD,MAAM,OAAO,GAAG,8BAA8B,GAAG,CAAC,OAAO,EAAE,CAAC;gBAC5D,MAAM,CAAC,IAAI,2BAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;YACjE,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC"}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
export { createPackageManager } from './factory';
|
||||
export type { PackageManagerName } from './package-manager-descriptor';
|
||||
export { PackageManager } from './package-manager';
|
||||
export { PackageManagerError } from './error';
|
||||
export type * from './package-metadata';
|
||||
export type { InstalledPackage } from './package-tree';
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PackageManagerError = exports.PackageManager = exports.createPackageManager = void 0;
|
||||
var factory_1 = require("./factory");
|
||||
Object.defineProperty(exports, "createPackageManager", { enumerable: true, get: function () { return factory_1.createPackageManager; } });
|
||||
var package_manager_1 = require("./package-manager");
|
||||
Object.defineProperty(exports, "PackageManager", { enumerable: true, get: function () { return package_manager_1.PackageManager; } });
|
||||
var error_1 = require("./error");
|
||||
Object.defineProperty(exports, "PackageManagerError", { enumerable: true, get: function () { return error_1.PackageManagerError; } });
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,qCAAiD;AAAxC,+GAAA,oBAAoB,OAAA;AAE7B,qDAAmD;AAA1C,iHAAA,cAAc,OAAA;AACvB,iCAA8C;AAArC,4GAAA,mBAAmB,OAAA"}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview This file defines a basic logger interface that is used by
|
||||
* the package manager abstraction. This allows the abstraction to be decoupled
|
||||
* from any specific logging implementation.
|
||||
*/
|
||||
/**
|
||||
* A basic logger interface for the package manager abstraction.
|
||||
*/
|
||||
export interface Logger {
|
||||
/**
|
||||
* Logs a debug message.
|
||||
* @param message The message to log.
|
||||
*/
|
||||
debug(message: string): void;
|
||||
/**
|
||||
* Logs an informational message.
|
||||
* @param message The message to log.
|
||||
*/
|
||||
info(message: string): void;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=logger.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"logger.js","sourceRoot":"","sources":["logger.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG"}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview This file defines the data structures and configuration for
|
||||
* supported package managers. It is the single source of truth for all
|
||||
* package-manager-specific commands, flags, and output parsing.
|
||||
*/
|
||||
import { ErrorInfo } from './error';
|
||||
import { Logger } from './logger';
|
||||
import { PackageManifest, PackageMetadata } from './package-metadata';
|
||||
import { InstalledPackage } from './package-tree';
|
||||
import { parseBunDependencies, parseNpmLikeDependencies, parseNpmLikeError, parseNpmLikeManifest, parseNpmLikeMetadata, parseYarnClassicDependencies, parseYarnClassicError, parseYarnClassicManifest, parseYarnClassicMetadata, parseYarnModernDependencies } from './parsers';
|
||||
/**
|
||||
* An interface that describes the commands and properties of a package manager.
|
||||
*/
|
||||
export interface PackageManagerDescriptor {
|
||||
/** The binary executable for the package manager. */
|
||||
readonly binary: string;
|
||||
/** The lockfile names used by the package manager. */
|
||||
readonly lockfiles: readonly string[];
|
||||
/** The command to add a package. */
|
||||
readonly addCommand: string;
|
||||
/** The command to install all dependencies. */
|
||||
readonly installCommand: readonly string[];
|
||||
/** The flag to force a clean installation. */
|
||||
readonly forceFlag: string;
|
||||
/** The flag to save a package with an exact version. */
|
||||
readonly saveExactFlag: string;
|
||||
/** The flag to save a package with a tilde version range. */
|
||||
readonly saveTildeFlag: string;
|
||||
/** The flag to save a package as a dev dependency. */
|
||||
readonly saveDevFlag: string;
|
||||
/** The flag to prevent the lockfile from being updated. */
|
||||
readonly noLockfileFlag: string;
|
||||
/** The flag to prevent lifecycle scripts from being executed. */
|
||||
readonly ignoreScriptsFlag: string;
|
||||
/** The flag to ignore peer dependency warnings/errors. */
|
||||
readonly ignorePeerDependenciesFlag?: string;
|
||||
/** The configuration files used by the package manager. */
|
||||
readonly configFiles: readonly string[];
|
||||
/**
|
||||
* Whether to copy configuration files from the project root to the temporary directory.
|
||||
* This is necessary for package managers that do not inherit configuration from parent directories (e.g., bun).
|
||||
*/
|
||||
readonly copyConfigFromProject?: boolean;
|
||||
/** A function that returns the arguments and environment variables to use a custom registry. */
|
||||
readonly getRegistryOptions?: (registry: string) => {
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
};
|
||||
/** The command to get the package manager's version. */
|
||||
readonly versionCommand: readonly string[];
|
||||
/** The command to list all installed dependencies. */
|
||||
readonly listDependenciesCommand: 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[];
|
||||
/** 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>;
|
||||
/** 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. */
|
||||
getRegistryMetadata: (stdout: string, logger?: Logger) => PackageMetadata | null;
|
||||
/** A function to parse the output when a command fails. */
|
||||
getError?: (output: string, logger?: Logger) => ErrorInfo | null;
|
||||
};
|
||||
/** A function that checks if a structured error represents a "package not found" error. */
|
||||
readonly isNotFound: (error: ErrorInfo) => boolean;
|
||||
}
|
||||
/** A type that represents the name of a supported package manager. */
|
||||
export type PackageManagerName = keyof typeof SUPPORTED_PACKAGE_MANAGERS;
|
||||
/**
|
||||
* A shared function to check if a structured error represents a "package not found" error.
|
||||
* @param error The structured error to check.
|
||||
* @returns True if the error code is a known "not found" code, false otherwise.
|
||||
*/
|
||||
declare function isKnownNotFound(error: ErrorInfo): boolean;
|
||||
/**
|
||||
* A map of supported package managers to their descriptors.
|
||||
* This is the single source of truth for all package-manager-specific
|
||||
* configuration and behavior.
|
||||
*
|
||||
* Each descriptor is intentionally explicit and self-contained. This approach
|
||||
* avoids inheritance or fallback logic between package managers, ensuring that
|
||||
* the behavior for each one is clear, predictable, and easy to modify in
|
||||
* isolation. For example, `yarn-classic` does not inherit any properties from
|
||||
* the `yarn` descriptor; it is a complete and independent definition.
|
||||
*/
|
||||
export declare const SUPPORTED_PACKAGE_MANAGERS: {
|
||||
npm: {
|
||||
binary: string;
|
||||
lockfiles: string[];
|
||||
addCommand: string;
|
||||
installCommand: string[];
|
||||
forceFlag: string;
|
||||
saveExactFlag: string;
|
||||
saveTildeFlag: string;
|
||||
saveDevFlag: string;
|
||||
noLockfileFlag: string;
|
||||
ignoreScriptsFlag: string;
|
||||
ignorePeerDependenciesFlag: string;
|
||||
configFiles: string[];
|
||||
getRegistryOptions: (registry: string) => {
|
||||
args: string[];
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
viewCommandFieldArgFormatter: (fields: readonly string[]) => string[];
|
||||
outputParsers: {
|
||||
listDependencies: typeof parseNpmLikeDependencies;
|
||||
getRegistryManifest: typeof parseNpmLikeManifest;
|
||||
getRegistryMetadata: typeof parseNpmLikeMetadata;
|
||||
getError: typeof parseNpmLikeError;
|
||||
};
|
||||
isNotFound: typeof isKnownNotFound;
|
||||
};
|
||||
yarn: {
|
||||
binary: string;
|
||||
lockfiles: string[];
|
||||
addCommand: string;
|
||||
installCommand: string[];
|
||||
forceFlag: string;
|
||||
saveExactFlag: string;
|
||||
saveTildeFlag: string;
|
||||
saveDevFlag: string;
|
||||
noLockfileFlag: string;
|
||||
ignoreScriptsFlag: string;
|
||||
configFiles: string[];
|
||||
getRegistryOptions: (registry: string) => {
|
||||
env: {
|
||||
YARN_NPM_REGISTRY_SERVER: string;
|
||||
};
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
viewCommandFieldArgFormatter: (fields: readonly string[]) => string[];
|
||||
outputParsers: {
|
||||
listDependencies: typeof parseYarnModernDependencies;
|
||||
getRegistryManifest: typeof parseNpmLikeManifest;
|
||||
getRegistryMetadata: typeof parseNpmLikeMetadata;
|
||||
getError: typeof parseNpmLikeError;
|
||||
};
|
||||
isNotFound: typeof isKnownNotFound;
|
||||
};
|
||||
'yarn-classic': {
|
||||
binary: string;
|
||||
lockfiles: never[];
|
||||
addCommand: string;
|
||||
installCommand: string[];
|
||||
forceFlag: string;
|
||||
saveExactFlag: string;
|
||||
saveTildeFlag: string;
|
||||
saveDevFlag: string;
|
||||
noLockfileFlag: string;
|
||||
ignoreScriptsFlag: string;
|
||||
configFiles: string[];
|
||||
getRegistryOptions: (registry: string) => {
|
||||
args: string[];
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
requiresManifestVersionLookup: true;
|
||||
outputParsers: {
|
||||
listDependencies: typeof parseYarnClassicDependencies;
|
||||
getRegistryManifest: typeof parseYarnClassicManifest;
|
||||
getRegistryMetadata: typeof parseYarnClassicMetadata;
|
||||
getError: typeof parseYarnClassicError;
|
||||
};
|
||||
isNotFound: typeof isKnownNotFound;
|
||||
};
|
||||
pnpm: {
|
||||
binary: string;
|
||||
lockfiles: string[];
|
||||
addCommand: string;
|
||||
installCommand: string[];
|
||||
forceFlag: string;
|
||||
saveExactFlag: string;
|
||||
saveTildeFlag: string;
|
||||
saveDevFlag: string;
|
||||
noLockfileFlag: string;
|
||||
ignoreScriptsFlag: string;
|
||||
ignorePeerDependenciesFlag: string;
|
||||
configFiles: string[];
|
||||
getRegistryOptions: (registry: string) => {
|
||||
args: string[];
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
viewCommandFieldArgFormatter: (fields: readonly string[]) => string[];
|
||||
outputParsers: {
|
||||
listDependencies: typeof parseNpmLikeDependencies;
|
||||
getRegistryManifest: typeof parseNpmLikeManifest;
|
||||
getRegistryMetadata: typeof parseNpmLikeMetadata;
|
||||
getError: typeof parseNpmLikeError;
|
||||
};
|
||||
isNotFound: typeof isKnownNotFound;
|
||||
};
|
||||
bun: {
|
||||
binary: string;
|
||||
lockfiles: string[];
|
||||
addCommand: string;
|
||||
installCommand: string[];
|
||||
forceFlag: string;
|
||||
saveExactFlag: string;
|
||||
saveTildeFlag: string;
|
||||
saveDevFlag: string;
|
||||
noLockfileFlag: string;
|
||||
ignoreScriptsFlag: string;
|
||||
configFiles: string[];
|
||||
copyConfigFromProject: true;
|
||||
getRegistryOptions: (registry: string) => {
|
||||
args: string[];
|
||||
};
|
||||
versionCommand: string[];
|
||||
listDependenciesCommand: string[];
|
||||
getManifestCommand: string[];
|
||||
outputParsers: {
|
||||
listDependencies: typeof parseBunDependencies;
|
||||
getRegistryManifest: typeof parseNpmLikeManifest;
|
||||
getRegistryMetadata: typeof parseNpmLikeMetadata;
|
||||
getError: typeof parseNpmLikeError;
|
||||
};
|
||||
isNotFound: typeof isKnownNotFound;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* The order of precedence for package managers.
|
||||
* This is a best-effort ordering based on estimated Angular community usage and default presence.
|
||||
*/
|
||||
export declare const PACKAGE_MANAGER_PRECEDENCE: readonly PackageManagerName[];
|
||||
export {};
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PACKAGE_MANAGER_PRECEDENCE = exports.SUPPORTED_PACKAGE_MANAGERS = void 0;
|
||||
const parsers_1 = require("./parsers");
|
||||
/** A set of error codes that are known to indicate a "package not found" error. */
|
||||
const NOT_FOUND_ERROR_CODES = new Set(['E404']);
|
||||
/**
|
||||
* A shared function to check if a structured error represents a "package not found" error.
|
||||
* @param error The structured error to check.
|
||||
* @returns True if the error code is a known "not found" code, false otherwise.
|
||||
*/
|
||||
function isKnownNotFound(error) {
|
||||
return NOT_FOUND_ERROR_CODES.has(error.code);
|
||||
}
|
||||
/**
|
||||
* A map of supported package managers to their descriptors.
|
||||
* This is the single source of truth for all package-manager-specific
|
||||
* configuration and behavior.
|
||||
*
|
||||
* Each descriptor is intentionally explicit and self-contained. This approach
|
||||
* avoids inheritance or fallback logic between package managers, ensuring that
|
||||
* the behavior for each one is clear, predictable, and easy to modify in
|
||||
* isolation. For example, `yarn-classic` does not inherit any properties from
|
||||
* the `yarn` descriptor; it is a complete and independent definition.
|
||||
*/
|
||||
exports.SUPPORTED_PACKAGE_MANAGERS = {
|
||||
npm: {
|
||||
binary: 'npm',
|
||||
lockfiles: ['package-lock.json', 'npm-shrinkwrap.json'],
|
||||
addCommand: 'install',
|
||||
installCommand: ['install'],
|
||||
forceFlag: '--force',
|
||||
saveExactFlag: '--save-exact',
|
||||
saveTildeFlag: '--save-tilde',
|
||||
saveDevFlag: '--save-dev',
|
||||
noLockfileFlag: '--no-package-lock',
|
||||
ignoreScriptsFlag: '--ignore-scripts',
|
||||
ignorePeerDependenciesFlag: '--force',
|
||||
configFiles: ['.npmrc'],
|
||||
getRegistryOptions: (registry) => ({ args: ['--registry', registry] }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['list', '--depth=0', '--json=true', '--all=true'],
|
||||
getManifestCommand: ['view', '--json'],
|
||||
viewCommandFieldArgFormatter: (fields) => [...fields],
|
||||
outputParsers: {
|
||||
listDependencies: parsers_1.parseNpmLikeDependencies,
|
||||
getRegistryManifest: parsers_1.parseNpmLikeManifest,
|
||||
getRegistryMetadata: parsers_1.parseNpmLikeMetadata,
|
||||
getError: parsers_1.parseNpmLikeError,
|
||||
},
|
||||
isNotFound: isKnownNotFound,
|
||||
},
|
||||
yarn: {
|
||||
binary: 'yarn',
|
||||
lockfiles: ['yarn.lock'],
|
||||
addCommand: 'add',
|
||||
installCommand: ['install'],
|
||||
forceFlag: '--force',
|
||||
saveExactFlag: '--exact',
|
||||
saveTildeFlag: '--tilde',
|
||||
saveDevFlag: '--dev',
|
||||
noLockfileFlag: '',
|
||||
ignoreScriptsFlag: '--mode=skip-build',
|
||||
configFiles: ['.yarnrc.yml', '.yarnrc.yaml'],
|
||||
getRegistryOptions: (registry) => ({ env: { YARN_NPM_REGISTRY_SERVER: registry } }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['info', '--name-only', '--json'],
|
||||
getManifestCommand: ['npm', 'info', '--json'],
|
||||
viewCommandFieldArgFormatter: (fields) => ['--fields', fields.join(',')],
|
||||
outputParsers: {
|
||||
listDependencies: parsers_1.parseYarnModernDependencies,
|
||||
getRegistryManifest: parsers_1.parseNpmLikeManifest,
|
||||
getRegistryMetadata: parsers_1.parseNpmLikeMetadata,
|
||||
getError: parsers_1.parseNpmLikeError,
|
||||
},
|
||||
isNotFound: isKnownNotFound,
|
||||
},
|
||||
'yarn-classic': {
|
||||
binary: 'yarn',
|
||||
// This is intentionally empty. `yarn-classic` is not a discoverable package manager.
|
||||
// The discovery process finds `yarn` via `yarn.lock`, and the factory logic
|
||||
// determines whether it is classic or modern by checking the installed version.
|
||||
lockfiles: [],
|
||||
addCommand: 'add',
|
||||
installCommand: ['install'],
|
||||
forceFlag: '--force',
|
||||
saveExactFlag: '--exact',
|
||||
saveTildeFlag: '--tilde',
|
||||
saveDevFlag: '--dev',
|
||||
noLockfileFlag: '--no-lockfile',
|
||||
ignoreScriptsFlag: '--ignore-scripts',
|
||||
configFiles: ['.yarnrc', '.npmrc'],
|
||||
getRegistryOptions: (registry) => ({ args: ['--registry', registry] }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['list', '--depth=0', '--json'],
|
||||
getManifestCommand: ['info', '--json', '--verbose'],
|
||||
requiresManifestVersionLookup: true,
|
||||
outputParsers: {
|
||||
listDependencies: parsers_1.parseYarnClassicDependencies,
|
||||
getRegistryManifest: parsers_1.parseYarnClassicManifest,
|
||||
getRegistryMetadata: parsers_1.parseYarnClassicMetadata,
|
||||
getError: parsers_1.parseYarnClassicError,
|
||||
},
|
||||
isNotFound: isKnownNotFound,
|
||||
},
|
||||
pnpm: {
|
||||
binary: 'pnpm',
|
||||
lockfiles: ['pnpm-lock.yaml'],
|
||||
addCommand: 'add',
|
||||
installCommand: ['install'],
|
||||
forceFlag: '--force',
|
||||
saveExactFlag: '--save-exact',
|
||||
saveTildeFlag: '--save-tilde',
|
||||
saveDevFlag: '--save-dev',
|
||||
noLockfileFlag: '--no-lockfile',
|
||||
ignoreScriptsFlag: '--ignore-scripts',
|
||||
ignorePeerDependenciesFlag: '--strict-peer-dependencies=false',
|
||||
configFiles: ['.npmrc', 'pnpm-workspace.yaml'],
|
||||
getRegistryOptions: (registry) => ({ args: ['--registry', registry] }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['list', '--depth=0', '--json'],
|
||||
getManifestCommand: ['view', '--json'],
|
||||
viewCommandFieldArgFormatter: (fields) => [...fields],
|
||||
outputParsers: {
|
||||
listDependencies: parsers_1.parseNpmLikeDependencies,
|
||||
getRegistryManifest: parsers_1.parseNpmLikeManifest,
|
||||
getRegistryMetadata: parsers_1.parseNpmLikeMetadata,
|
||||
getError: parsers_1.parseNpmLikeError,
|
||||
},
|
||||
isNotFound: isKnownNotFound,
|
||||
},
|
||||
bun: {
|
||||
binary: 'bun',
|
||||
lockfiles: ['bun.lockb', 'bun.lock'],
|
||||
addCommand: 'add',
|
||||
installCommand: ['install'],
|
||||
forceFlag: '--force',
|
||||
saveExactFlag: '--exact',
|
||||
saveTildeFlag: '', // Bun does not have a flag for tilde, it defaults to caret.
|
||||
saveDevFlag: '--development',
|
||||
noLockfileFlag: '', // Bun does not have a flag for this.
|
||||
ignoreScriptsFlag: '--ignore-scripts',
|
||||
configFiles: ['bunfig.toml', '.npmrc'],
|
||||
copyConfigFromProject: true,
|
||||
getRegistryOptions: (registry) => ({ args: ['--registry', registry] }),
|
||||
versionCommand: ['--version'],
|
||||
listDependenciesCommand: ['pm', 'ls'],
|
||||
getManifestCommand: ['pm', 'view', '--json'],
|
||||
outputParsers: {
|
||||
listDependencies: parsers_1.parseBunDependencies,
|
||||
getRegistryManifest: parsers_1.parseNpmLikeManifest,
|
||||
getRegistryMetadata: parsers_1.parseNpmLikeMetadata,
|
||||
getError: parsers_1.parseNpmLikeError,
|
||||
},
|
||||
isNotFound: isKnownNotFound,
|
||||
},
|
||||
};
|
||||
/**
|
||||
* The order of precedence for package managers.
|
||||
* This is a best-effort ordering based on estimated Angular community usage and default presence.
|
||||
*/
|
||||
exports.PACKAGE_MANAGER_PRECEDENCE = [
|
||||
'pnpm',
|
||||
'yarn',
|
||||
'bun',
|
||||
'npm',
|
||||
];
|
||||
//# sourceMappingURL=package-manager-descriptor.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"package-manager-descriptor.js","sourceRoot":"","sources":["package-manager-descriptor.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAYH,uCAWmB;AA2FnB,mFAAmF;AACnF,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAEhD;;;;GAIG;AACH,SAAS,eAAe,CAAC,KAAgB;IACvC,OAAO,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC/C,CAAC;AAED;;;;;;;;;;GAUG;AACU,QAAA,0BAA0B,GAAG;IACxC,GAAG,EAAE;QACH,MAAM,EAAE,KAAK;QACb,SAAS,EAAE,CAAC,mBAAmB,EAAE,qBAAqB,CAAC;QACvD,UAAU,EAAE,SAAS;QACrB,cAAc,EAAE,CAAC,SAAS,CAAC;QAC3B,SAAS,EAAE,SAAS;QACpB,aAAa,EAAE,cAAc;QAC7B,aAAa,EAAE,cAAc;QAC7B,WAAW,EAAE,YAAY;QACzB,cAAc,EAAE,mBAAmB;QACnC,iBAAiB,EAAE,kBAAkB;QACrC,0BAA0B,EAAE,SAAS;QACrC,WAAW,EAAE,CAAC,QAAQ,CAAC;QACvB,kBAAkB,EAAE,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,YAAY,EAAE,QAAQ,CA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BAAkB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC;QAC5C,aAAa,EAAE;YACb,gBAAgB,EAAE,8BAAoB;YACtC,mBAAmB,EAAE,8BAAoB;YACzC,mBAAmB,EAAE,8BAAoB;YACzC,QAAQ,EAAE,2BAAiB;SAC5B;QACD,UAAU,EAAE,eAAe;KAC5B;CACiD,CAAC;AAErD;;;GAGG;AACU,QAAA,0BAA0B,GAAkC;IACvE,MAAM;IACN,MAAM;IACN,KAAK;IACL,KAAK;CACN,CAAC"}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* @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 npa from 'npm-package-arg';
|
||||
import { Host } from './host';
|
||||
import { Logger } from './logger';
|
||||
import { PackageManagerDescriptor } from './package-manager-descriptor';
|
||||
import { PackageManifest, PackageMetadata } from './package-metadata';
|
||||
import { InstalledPackage } from './package-tree';
|
||||
/**
|
||||
* The fields to request from the registry for a package's manifest.
|
||||
* This is a performance optimization to avoid downloading unnecessary data.
|
||||
* These fields are the ones required by the CLI for operations like `ng add` and `ng update`.
|
||||
*/
|
||||
export declare const MANIFEST_FIELDS: readonly ["name", "version", "deprecated", "dependencies", "peerDependencies", "devDependencies", "homepage", "schematics", "ng-add", "ng-update"];
|
||||
/**
|
||||
* Options to configure the `PackageManager` instance.
|
||||
*/
|
||||
export interface PackageManagerOptions {
|
||||
/**
|
||||
* If true, no commands will be executed, but they will be logged to the logger.
|
||||
* A logger must be provided if this is true.
|
||||
*/
|
||||
dryRun?: boolean;
|
||||
/** A logger instance for debugging and dry run output. */
|
||||
logger?: Logger;
|
||||
/**
|
||||
* The base path to use for temporary directories.
|
||||
*/
|
||||
tempDirectory?: string;
|
||||
/**
|
||||
* The version of the package manager.
|
||||
* If provided, the `getVersion` method will return this version
|
||||
* instead of running the version command.
|
||||
*/
|
||||
version?: string;
|
||||
/**
|
||||
* An error that occurred during the initialization of the package manager.
|
||||
* If provided, this error will be thrown when attempting to execute any command.
|
||||
*/
|
||||
initializationError?: Error;
|
||||
}
|
||||
/**
|
||||
* A class that provides a high-level, package-manager-agnostic API for
|
||||
* interacting with a project's dependencies.
|
||||
*
|
||||
* This class is an implementation of the Strategy design pattern. It is
|
||||
* instantiated with a `PackageManagerDescriptor` that defines the specific
|
||||
* commands and flags for a given package manager.
|
||||
*/
|
||||
export declare class PackageManager {
|
||||
#private;
|
||||
private readonly host;
|
||||
private readonly cwd;
|
||||
private readonly descriptor;
|
||||
private readonly options;
|
||||
/**
|
||||
* Creates a new `PackageManager` instance.
|
||||
* @param host A `Host` instance for interacting with the file system and running commands.
|
||||
* @param cwd The absolute path to the project's working directory.
|
||||
* @param descriptor A `PackageManagerDescriptor` that defines the commands for a specific package manager.
|
||||
* @param options An options object to configure the instance.
|
||||
*/
|
||||
constructor(host: Host, cwd: string, descriptor: PackageManagerDescriptor, options?: PackageManagerOptions);
|
||||
/**
|
||||
* The name of the package manager's binary.
|
||||
*/
|
||||
get name(): string;
|
||||
/**
|
||||
* Ensures that the package manager is installed and available in the PATH.
|
||||
* If it is not, this method will throw an error with instructions on how to install it.
|
||||
*
|
||||
* @throws {Error} If the package manager is not installed.
|
||||
*/
|
||||
ensureInstalled(): void;
|
||||
/**
|
||||
* Adds a package to the project's dependencies.
|
||||
* @param packageName The name of the package to add.
|
||||
* @param save The save strategy to use.
|
||||
* - `exact`: The package will be saved with an exact version.
|
||||
* - `tilde`: The package will be saved with a tilde version range (`~`).
|
||||
* - `none`: The package will be saved with the default version range (`^`).
|
||||
* @param asDevDependency Whether to install the package as a dev dependency.
|
||||
* @param noLockfile Whether to skip updating the lockfile.
|
||||
* @param options Extra options for the command.
|
||||
* @returns A promise that resolves when the command is complete.
|
||||
*/
|
||||
add(packageName: string, save: 'exact' | 'tilde' | 'none', asDevDependency: boolean, noLockfile: boolean, ignoreScripts: boolean, options?: {
|
||||
registry?: string;
|
||||
}): Promise<void>;
|
||||
/**
|
||||
* Installs all dependencies in the project.
|
||||
* @param options Options for the installation.
|
||||
* @param options.timeout The maximum time in milliseconds to wait for the command to complete.
|
||||
* @param options.force If true, forces a clean install, potentially overwriting existing modules.
|
||||
* @param options.registry The registry to use for the installation.
|
||||
* @param options.ignoreScripts If true, prevents lifecycle scripts from being executed.
|
||||
* @returns A promise that resolves when the command is complete.
|
||||
*/
|
||||
install(options?: {
|
||||
timeout?: number;
|
||||
force?: boolean;
|
||||
registry?: string;
|
||||
ignoreScripts?: boolean;
|
||||
ignorePeerDependencies?: boolean;
|
||||
}): Promise<void>;
|
||||
/**
|
||||
* Gets the version of the package manager binary.
|
||||
*/
|
||||
getVersion(): Promise<string>;
|
||||
/**
|
||||
* Gets the installed details of a package from the project's dependencies.
|
||||
* @param packageName The name of the package to check.
|
||||
* @returns A promise that resolves to the installed package details, or `null` if the package is not installed.
|
||||
*/
|
||||
getInstalledPackage(packageName: string): Promise<InstalledPackage | null>;
|
||||
/**
|
||||
* Gets a map of all top-level dependencies installed in the project.
|
||||
* @returns A promise that resolves to a map of package names to their installed package details.
|
||||
*/
|
||||
getProjectDependencies(): Promise<Map<string, InstalledPackage>>;
|
||||
/**
|
||||
* Fetches the registry metadata for a package. This is the full metadata,
|
||||
* including all versions and distribution tags.
|
||||
* @param packageName The name of the package to fetch the metadata for.
|
||||
* @param options Options for the fetch.
|
||||
* @param options.timeout The maximum time in milliseconds to wait for the command to complete.
|
||||
* @param options.registry The registry to use for the fetch.
|
||||
* @param options.bypassCache If true, ignores the in-memory cache and fetches fresh data.
|
||||
* @returns A promise that resolves to the `PackageMetadata` object, or `null` if the package is not found.
|
||||
*/
|
||||
getRegistryMetadata(packageName: string, options?: {
|
||||
timeout?: number;
|
||||
registry?: string;
|
||||
bypassCache?: boolean;
|
||||
}): Promise<PackageMetadata | null>;
|
||||
/**
|
||||
* Fetches the registry manifest for a specific version of a package.
|
||||
* The manifest is similar to the package's `package.json` file.
|
||||
* @param packageName The name of the package to fetch the manifest for.
|
||||
* @param version The version of the package to fetch the manifest for.
|
||||
* @param options Options for the fetch.
|
||||
* @param options.timeout The maximum time in milliseconds to wait for the command to complete.
|
||||
* @param options.registry The registry to use for the fetch.
|
||||
* @param options.bypassCache If true, ignores the in-memory cache and fetches fresh data.
|
||||
* @returns A promise that resolves to the `PackageManifest` object, or `null` if the package is not found.
|
||||
*/
|
||||
getRegistryManifest(packageName: string, version: string, options?: {
|
||||
timeout?: number;
|
||||
registry?: string;
|
||||
bypassCache?: boolean;
|
||||
}): Promise<PackageManifest | null>;
|
||||
/**
|
||||
* Fetches the manifest for a package.
|
||||
*
|
||||
* This method can resolve manifests for packages from the registry, as well
|
||||
* as those specified by file paths, directory paths, and remote tarballs.
|
||||
* Caching is only supported for registry packages.
|
||||
*
|
||||
* @param specifier The package specifier to resolve the manifest for.
|
||||
* @param options Options for the fetch.
|
||||
* @returns A promise that resolves to the `PackageManifest` object, or `null` if the package is not found.
|
||||
*/
|
||||
getManifest(specifier: string | npa.Result, options?: {
|
||||
timeout?: number;
|
||||
registry?: string;
|
||||
bypassCache?: boolean;
|
||||
}): Promise<PackageManifest | null>;
|
||||
private getTemporaryDirectory;
|
||||
/**
|
||||
* Acquires a package by installing it into a temporary directory. The caller is
|
||||
* responsible for managing the lifecycle of the temporary directory by calling
|
||||
* the returned `cleanup` function.
|
||||
*
|
||||
* @param specifier The specifier of the package to install.
|
||||
* @param options Options for the installation.
|
||||
* @returns A promise that resolves to an object containing the temporary path
|
||||
* and a cleanup function.
|
||||
*/
|
||||
acquireTempPackage(specifier: string, options?: {
|
||||
registry?: string;
|
||||
ignoreScripts?: boolean;
|
||||
}): Promise<{
|
||||
workingDirectory: string;
|
||||
cleanup: () => Promise<void>;
|
||||
}>;
|
||||
}
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PackageManager = exports.MANIFEST_FIELDS = void 0;
|
||||
/**
|
||||
* @fileoverview This file contains the `PackageManager` class, which is the
|
||||
* core execution engine for all package manager commands. It is designed to be
|
||||
* a flexible and secure abstraction over the various package managers.
|
||||
*/
|
||||
const node_path_1 = require("node:path");
|
||||
const npm_package_arg_1 = __importDefault(require("npm-package-arg"));
|
||||
const semver_1 = require("semver");
|
||||
const error_1 = require("./error");
|
||||
/**
|
||||
* The fields to request from the registry for package metadata.
|
||||
* This is a performance optimization to avoid downloading the full manifest
|
||||
* when only summary data (like versions and tags) is needed.
|
||||
*/
|
||||
const METADATA_FIELDS = ['name', 'dist-tags', 'versions', 'time'];
|
||||
/**
|
||||
* The fields to request from the registry for a package's manifest.
|
||||
* This is a performance optimization to avoid downloading unnecessary data.
|
||||
* These fields are the ones required by the CLI for operations like `ng add` and `ng update`.
|
||||
*/
|
||||
exports.MANIFEST_FIELDS = [
|
||||
'name',
|
||||
'version',
|
||||
'deprecated',
|
||||
'dependencies',
|
||||
'peerDependencies',
|
||||
'devDependencies',
|
||||
'homepage',
|
||||
'schematics',
|
||||
'ng-add',
|
||||
'ng-update',
|
||||
];
|
||||
/**
|
||||
* A class that provides a high-level, package-manager-agnostic API for
|
||||
* interacting with a project's dependencies.
|
||||
*
|
||||
* This class is an implementation of the Strategy design pattern. It is
|
||||
* instantiated with a `PackageManagerDescriptor` that defines the specific
|
||||
* commands and flags for a given package manager.
|
||||
*/
|
||||
class PackageManager {
|
||||
host;
|
||||
cwd;
|
||||
descriptor;
|
||||
options;
|
||||
#manifestCache = new Map();
|
||||
#metadataCache = new Map();
|
||||
#initializationError;
|
||||
#dependencyCache = null;
|
||||
#version;
|
||||
/**
|
||||
* Creates a new `PackageManager` instance.
|
||||
* @param host A `Host` instance for interacting with the file system and running commands.
|
||||
* @param cwd The absolute path to the project's working directory.
|
||||
* @param descriptor A `PackageManagerDescriptor` that defines the commands for a specific package manager.
|
||||
* @param options An options object to configure the instance.
|
||||
*/
|
||||
constructor(host, cwd, descriptor, options = {}) {
|
||||
this.host = host;
|
||||
this.cwd = cwd;
|
||||
this.descriptor = descriptor;
|
||||
this.options = options;
|
||||
if (this.options.dryRun && !this.options.logger) {
|
||||
throw new Error('A logger must be provided when dryRun is enabled.');
|
||||
}
|
||||
this.#version = options.version;
|
||||
this.#initializationError = options.initializationError;
|
||||
}
|
||||
/**
|
||||
* The name of the package manager's binary.
|
||||
*/
|
||||
get name() {
|
||||
return this.descriptor.binary;
|
||||
}
|
||||
/**
|
||||
* Ensures that the package manager is installed and available in the PATH.
|
||||
* If it is not, this method will throw an error with instructions on how to install it.
|
||||
*
|
||||
* @throws {Error} If the package manager is not installed.
|
||||
*/
|
||||
ensureInstalled() {
|
||||
if (this.#initializationError) {
|
||||
throw this.#initializationError;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A private method to lazily populate the dependency cache.
|
||||
* This is a performance optimization to avoid running `npm list` multiple times.
|
||||
* @returns A promise that resolves to the dependency cache map.
|
||||
*/
|
||||
async #populateDependencyCache() {
|
||||
if (this.#dependencyCache !== null) {
|
||||
return this.#dependencyCache;
|
||||
}
|
||||
const args = this.descriptor.listDependenciesCommand;
|
||||
const dependencies = await this.#fetchAndParse(args, (stdout, logger) => this.descriptor.outputParsers.listDependencies(stdout, logger));
|
||||
return (this.#dependencyCache = dependencies ?? new Map());
|
||||
}
|
||||
/**
|
||||
* A private method to run a command using the package manager's binary.
|
||||
* @param args The arguments to pass to the command.
|
||||
* @param options Options for the child process.
|
||||
* @returns A promise that resolves with the standard output and standard error of the command.
|
||||
*/
|
||||
async #run(args, options = {}) {
|
||||
this.ensureInstalled();
|
||||
const { registry, cwd, ...runOptions } = options;
|
||||
const finalArgs = [...args];
|
||||
let finalEnv;
|
||||
if (registry) {
|
||||
const registryOptions = this.descriptor.getRegistryOptions?.(registry);
|
||||
if (!registryOptions) {
|
||||
throw new Error(`The configured package manager, '${this.descriptor.binary}', does not support a custom registry.`);
|
||||
}
|
||||
if (registryOptions.args) {
|
||||
finalArgs.push(...registryOptions.args);
|
||||
}
|
||||
if (registryOptions.env) {
|
||||
finalEnv = registryOptions.env;
|
||||
}
|
||||
}
|
||||
const executionDirectory = cwd ?? this.cwd;
|
||||
if (this.options.dryRun) {
|
||||
this.options.logger?.info(`[DRY RUN] Would execute in [${executionDirectory}]: ${this.descriptor.binary} ${finalArgs.join(' ')}`);
|
||||
return { stdout: '', stderr: '' };
|
||||
}
|
||||
const commandResult = await this.host.runCommand(this.descriptor.binary, finalArgs, {
|
||||
...runOptions,
|
||||
cwd: executionDirectory,
|
||||
stdio: 'pipe',
|
||||
env: finalEnv,
|
||||
});
|
||||
return { stdout: commandResult.stdout.trim(), stderr: commandResult.stderr.trim() };
|
||||
}
|
||||
/**
|
||||
* A private, generic method to encapsulate the common logic of running a command,
|
||||
* handling errors, and parsing the output.
|
||||
* @param args The arguments to pass to the command.
|
||||
* @param parser A function that parses the command's stdout.
|
||||
* @param options Options for the command, including caching.
|
||||
* @returns A promise that resolves to the parsed data, or null if not found.
|
||||
*/
|
||||
async #fetchAndParse(args, parser, options = {}) {
|
||||
const { cache, cacheKey, bypassCache, ...runOptions } = options;
|
||||
if (!bypassCache && cache && cacheKey && cache.has(cacheKey)) {
|
||||
return cache.get(cacheKey);
|
||||
}
|
||||
let stdout;
|
||||
let stderr;
|
||||
let exitCode;
|
||||
let thrownError;
|
||||
try {
|
||||
({ stdout, stderr } = await this.#run(args, runOptions));
|
||||
exitCode = 0;
|
||||
}
|
||||
catch (e) {
|
||||
thrownError = e;
|
||||
if (e instanceof error_1.PackageManagerError) {
|
||||
stdout = e.stdout;
|
||||
stderr = e.stderr;
|
||||
exitCode = e.exitCode;
|
||||
}
|
||||
else {
|
||||
// Re-throw unexpected errors
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
// Yarn classic can exit with code 0 even when an error occurs.
|
||||
// To ensure we capture these cases, we will always attempt to parse a
|
||||
// structured error from the output, regardless of the exit code.
|
||||
const getError = this.descriptor.outputParsers.getError;
|
||||
const parsedError = getError?.(stdout, this.options.logger) ?? getError?.(stderr, this.options.logger) ?? null;
|
||||
if (parsedError) {
|
||||
this.options.logger?.debug(`[${this.descriptor.binary}] Structured error (code: ${parsedError.code}): ${parsedError.summary}`);
|
||||
// Special case for 'not found' errors (e.g., E404). Return null for these.
|
||||
if (this.descriptor.isNotFound(parsedError)) {
|
||||
if (cache && cacheKey) {
|
||||
cache.set(cacheKey, null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
// For all other structured errors, throw a more informative error.
|
||||
throw new error_1.PackageManagerError(parsedError.summary, stdout, stderr, exitCode);
|
||||
}
|
||||
}
|
||||
// If an error was originally thrown and we didn't parse a more specific
|
||||
// structured error, re-throw the original error now.
|
||||
if (thrownError) {
|
||||
throw thrownError;
|
||||
}
|
||||
// If we reach this point, the command succeeded and no structured error was found.
|
||||
// We can now safely parse the successful output.
|
||||
try {
|
||||
const result = parser(stdout, this.options.logger);
|
||||
if (cache && cacheKey) {
|
||||
cache.set(cacheKey, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (e) {
|
||||
const message = `Failed to parse package manager output: ${e instanceof Error ? e.message : ''}`;
|
||||
throw new error_1.PackageManagerError(message, stdout, stderr, exitCode);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Adds a package to the project's dependencies.
|
||||
* @param packageName The name of the package to add.
|
||||
* @param save The save strategy to use.
|
||||
* - `exact`: The package will be saved with an exact version.
|
||||
* - `tilde`: The package will be saved with a tilde version range (`~`).
|
||||
* - `none`: The package will be saved with the default version range (`^`).
|
||||
* @param asDevDependency Whether to install the package as a dev dependency.
|
||||
* @param noLockfile Whether to skip updating the lockfile.
|
||||
* @param options Extra options for the command.
|
||||
* @returns A promise that resolves when the command is complete.
|
||||
*/
|
||||
async add(packageName, save, asDevDependency, noLockfile, ignoreScripts, options = {}) {
|
||||
const flags = [
|
||||
asDevDependency ? this.descriptor.saveDevFlag : '',
|
||||
save === 'exact' ? this.descriptor.saveExactFlag : '',
|
||||
save === 'tilde' ? this.descriptor.saveTildeFlag : '',
|
||||
noLockfile ? this.descriptor.noLockfileFlag : '',
|
||||
ignoreScripts ? this.descriptor.ignoreScriptsFlag : '',
|
||||
].filter((flag) => flag);
|
||||
const args = [this.descriptor.addCommand, packageName, ...flags];
|
||||
await this.#run(args, options);
|
||||
this.#dependencyCache = null;
|
||||
}
|
||||
/**
|
||||
* Installs all dependencies in the project.
|
||||
* @param options Options for the installation.
|
||||
* @param options.timeout The maximum time in milliseconds to wait for the command to complete.
|
||||
* @param options.force If true, forces a clean install, potentially overwriting existing modules.
|
||||
* @param options.registry The registry to use for the installation.
|
||||
* @param options.ignoreScripts If true, prevents lifecycle scripts from being executed.
|
||||
* @returns A promise that resolves when the command is complete.
|
||||
*/
|
||||
async install(options = { ignoreScripts: true }) {
|
||||
const flags = [
|
||||
options.force ? this.descriptor.forceFlag : '',
|
||||
options.ignoreScripts ? this.descriptor.ignoreScriptsFlag : '',
|
||||
options.ignorePeerDependencies ? (this.descriptor.ignorePeerDependenciesFlag ?? '') : '',
|
||||
].filter((flag) => flag);
|
||||
const args = [...this.descriptor.installCommand, ...flags];
|
||||
await this.#run(args, options);
|
||||
this.#dependencyCache = null;
|
||||
}
|
||||
/**
|
||||
* Gets the version of the package manager binary.
|
||||
*/
|
||||
async getVersion() {
|
||||
if (this.#version) {
|
||||
return this.#version;
|
||||
}
|
||||
const { stdout } = await this.#run(this.descriptor.versionCommand);
|
||||
this.#version = stdout.trim();
|
||||
if (!(0, semver_1.valid)(this.#version)) {
|
||||
throw new Error(`Invalid semver version for ${this.name}: "${this.#version}"`);
|
||||
}
|
||||
return this.#version;
|
||||
}
|
||||
/**
|
||||
* Gets the installed details of a package from the project's dependencies.
|
||||
* @param packageName The name of the package to check.
|
||||
* @returns A promise that resolves to the installed package details, or `null` if the package is not installed.
|
||||
*/
|
||||
async getInstalledPackage(packageName) {
|
||||
const cache = await this.#populateDependencyCache();
|
||||
return cache.get(packageName) ?? null;
|
||||
}
|
||||
/**
|
||||
* Gets a map of all top-level dependencies installed in the project.
|
||||
* @returns A promise that resolves to a map of package names to their installed package details.
|
||||
*/
|
||||
async getProjectDependencies() {
|
||||
const cache = await this.#populateDependencyCache();
|
||||
// Return a copy to prevent external mutations of the cache.
|
||||
return new Map(cache);
|
||||
}
|
||||
/**
|
||||
* Fetches the registry metadata for a package. This is the full metadata,
|
||||
* including all versions and distribution tags.
|
||||
* @param packageName The name of the package to fetch the metadata for.
|
||||
* @param options Options for the fetch.
|
||||
* @param options.timeout The maximum time in milliseconds to wait for the command to complete.
|
||||
* @param options.registry The registry to use for the fetch.
|
||||
* @param options.bypassCache If true, ignores the in-memory cache and fetches fresh data.
|
||||
* @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 });
|
||||
}
|
||||
/**
|
||||
* Fetches the registry manifest for a specific version of a package.
|
||||
* The manifest is similar to the package's `package.json` file.
|
||||
* @param packageName The name of the package to fetch the manifest for.
|
||||
* @param version The version of the package to fetch the manifest for.
|
||||
* @param options Options for the fetch.
|
||||
* @param options.timeout The maximum time in milliseconds to wait for the command to complete.
|
||||
* @param options.registry The registry to use for the fetch.
|
||||
* @param options.bypassCache If true, ignores the in-memory cache and fetches fresh data.
|
||||
* @returns A promise that resolves to the `PackageManifest` object, or `null` if the package is not found.
|
||||
*/
|
||||
async getRegistryManifest(packageName, version, options = {}) {
|
||||
const specifier = this.host.requiresQuoting
|
||||
? `"${packageName}@${version}"`
|
||||
: `${packageName}@${version}`;
|
||||
const commandArgs = [...this.descriptor.getManifestCommand, specifier];
|
||||
const formatter = this.descriptor.viewCommandFieldArgFormatter;
|
||||
if (formatter) {
|
||||
commandArgs.push(...formatter(exports.MANIFEST_FIELDS));
|
||||
}
|
||||
const cacheKey = options.registry ? `${specifier}|${options.registry}` : specifier;
|
||||
const manifest = await this.#fetchAndParse(commandArgs, (stdout, logger) => this.descriptor.outputParsers.getRegistryManifest(stdout, logger), { ...options, cache: this.#manifestCache, cacheKey });
|
||||
// If the provided version was not a specific version, also cache the specific fetched version
|
||||
if (manifest && manifest.version !== version) {
|
||||
const manifestSpecifier = `${manifest.name}@${manifest.version}`;
|
||||
const manifestCacheKey = options.registry
|
||||
? `${manifestSpecifier}|${options.registry}`
|
||||
: manifestSpecifier;
|
||||
this.#manifestCache.set(manifestCacheKey, manifest);
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
/**
|
||||
* Fetches the manifest for a package.
|
||||
*
|
||||
* This method can resolve manifests for packages from the registry, as well
|
||||
* as those specified by file paths, directory paths, and remote tarballs.
|
||||
* Caching is only supported for registry packages.
|
||||
*
|
||||
* @param specifier The package specifier to resolve the manifest for.
|
||||
* @param options Options for the fetch.
|
||||
* @returns A promise that resolves to the `PackageManifest` object, or `null` if the package is not found.
|
||||
*/
|
||||
async getManifest(specifier, options = {}) {
|
||||
const { name, type, fetchSpec } = typeof specifier === 'string' ? (0, npm_package_arg_1.default)(specifier) : specifier;
|
||||
switch (type) {
|
||||
case 'range':
|
||||
case 'version':
|
||||
case 'tag': {
|
||||
if (!name) {
|
||||
throw new Error(`Could not parse package name from specifier: ${specifier}`);
|
||||
}
|
||||
// `fetchSpec` is the version, range, or tag.
|
||||
let versionSpec = fetchSpec ?? 'latest';
|
||||
if (this.descriptor.requiresManifestVersionLookup) {
|
||||
if (type === 'tag' || !fetchSpec) {
|
||||
const metadata = await this.getRegistryMetadata(name, options);
|
||||
if (!metadata) {
|
||||
return null;
|
||||
}
|
||||
versionSpec = metadata['dist-tags'][versionSpec];
|
||||
}
|
||||
else if (type === 'range') {
|
||||
const metadata = await this.getRegistryMetadata(name, options);
|
||||
if (!metadata) {
|
||||
return null;
|
||||
}
|
||||
versionSpec = (0, semver_1.maxSatisfying)(metadata.versions, fetchSpec) ?? '';
|
||||
}
|
||||
if (!versionSpec) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return this.getRegistryManifest(name, versionSpec, options);
|
||||
}
|
||||
case 'directory': {
|
||||
if (!fetchSpec) {
|
||||
throw new Error(`Could not parse directory path from specifier: ${specifier}`);
|
||||
}
|
||||
const manifestPath = (0, node_path_1.join)(fetchSpec, 'package.json');
|
||||
const manifest = await this.host.readFile(manifestPath);
|
||||
return JSON.parse(manifest);
|
||||
}
|
||||
case 'file':
|
||||
case 'remote':
|
||||
case 'git': {
|
||||
if (!fetchSpec) {
|
||||
throw new Error(`Could not parse location from specifier: ${specifier}`);
|
||||
}
|
||||
// Caching is not supported for non-registry specifiers.
|
||||
const { workingDirectory, cleanup } = await this.acquireTempPackage(fetchSpec, {
|
||||
...options,
|
||||
ignoreScripts: true,
|
||||
});
|
||||
try {
|
||||
// Discover the package name by reading the temporary `package.json` file.
|
||||
// The package manager will have added the package to the `dependencies`.
|
||||
const tempManifest = await this.host.readFile((0, node_path_1.join)(workingDirectory, 'package.json'));
|
||||
const { dependencies } = JSON.parse(tempManifest);
|
||||
const packageName = dependencies && Object.keys(dependencies)[0];
|
||||
if (!packageName) {
|
||||
throw new Error(`Could not determine package name for specifier: ${specifier}`);
|
||||
}
|
||||
// The package will be installed in `<temp>/node_modules/<name>`.
|
||||
const packagePath = (0, node_path_1.join)(workingDirectory, 'node_modules', packageName);
|
||||
const manifestPath = (0, node_path_1.join)(packagePath, 'package.json');
|
||||
const manifest = await this.host.readFile(manifestPath);
|
||||
return JSON.parse(manifest);
|
||||
}
|
||||
finally {
|
||||
await cleanup();
|
||||
}
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported package specifier type: ${type}`);
|
||||
}
|
||||
}
|
||||
async getTemporaryDirectory() {
|
||||
const { tempDirectory } = this.options;
|
||||
if (tempDirectory && !(0, node_path_1.relative)(this.cwd, tempDirectory).startsWith('..')) {
|
||||
try {
|
||||
await this.host.stat(tempDirectory);
|
||||
}
|
||||
catch {
|
||||
// If the cache directory doesn't exist, create it.
|
||||
await this.host.mkdir(tempDirectory, { recursive: true });
|
||||
}
|
||||
return tempDirectory;
|
||||
}
|
||||
const tempOptions = ['node_modules'];
|
||||
for (const tempOption of tempOptions) {
|
||||
try {
|
||||
const directory = (0, node_path_1.resolve)(this.cwd, tempOption);
|
||||
if ((await this.host.stat(directory)).isDirectory()) {
|
||||
return directory;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Acquires a package by installing it into a temporary directory. The caller is
|
||||
* responsible for managing the lifecycle of the temporary directory by calling
|
||||
* the returned `cleanup` function.
|
||||
*
|
||||
* @param specifier The specifier of the package to install.
|
||||
* @param options Options for the installation.
|
||||
* @returns A promise that resolves to an object containing the temporary path
|
||||
* and a cleanup function.
|
||||
*/
|
||||
async acquireTempPackage(specifier, options = {}) {
|
||||
const workingDirectory = await this.host.createTempDirectory(await this.getTemporaryDirectory());
|
||||
const cleanup = () => this.host.deleteDirectory(workingDirectory);
|
||||
// Some package managers, like yarn classic, do not write a package.json when adding a package.
|
||||
// This can cause issues with subsequent `require.resolve` calls.
|
||||
// Writing an empty package.json file beforehand prevents this.
|
||||
await this.host.writeFile((0, node_path_1.join)(workingDirectory, 'package.json'), '{}');
|
||||
// Copy configuration files if the package manager requires it (e.g., bun).
|
||||
if (this.descriptor.copyConfigFromProject) {
|
||||
for (const configFile of this.descriptor.configFiles) {
|
||||
try {
|
||||
const configPath = (0, node_path_1.join)(this.cwd, configFile);
|
||||
await this.host.copyFile(configPath, (0, node_path_1.join)(workingDirectory, configFile));
|
||||
}
|
||||
catch {
|
||||
// Ignore missing config files.
|
||||
}
|
||||
}
|
||||
}
|
||||
const flags = [options.ignoreScripts ? this.descriptor.ignoreScriptsFlag : ''].filter((flag) => flag);
|
||||
const args = [this.descriptor.addCommand, specifier, ...flags];
|
||||
try {
|
||||
await this.#run(args, { ...options, cwd: workingDirectory });
|
||||
}
|
||||
catch (e) {
|
||||
// If the command fails, clean up the temporary directory immediately.
|
||||
await cleanup();
|
||||
throw e;
|
||||
}
|
||||
return { workingDirectory, cleanup };
|
||||
}
|
||||
}
|
||||
exports.PackageManager = PackageManager;
|
||||
//# sourceMappingURL=package-manager.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+91
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* This file defines the core interfaces for package metadata and manifests,
|
||||
* providing a strongly-typed representation of the data returned by a package
|
||||
* manager registry. These interfaces are crucial for features like `ng add`
|
||||
* and `ng update`.
|
||||
*/
|
||||
/**
|
||||
* Defines how a package's dependencies should be saved to `package.json`
|
||||
* after being installed by the `ng add` command.
|
||||
*
|
||||
* - `dependencies`: Save to the `dependencies` section.
|
||||
* - `devDependencies`: Save to the `devDependencies` section.
|
||||
* - `false`: Do not save to `package.json`.
|
||||
*/
|
||||
export type NgAddSaveDependency = 'dependencies' | 'devDependencies' | false;
|
||||
/**
|
||||
* Represents the configuration for `ng add` found in a package's manifest.
|
||||
*/
|
||||
export interface NgAdd {
|
||||
/**
|
||||
* Specifies how the package should be saved to `package.json`.
|
||||
* @see NgAddSaveDependency
|
||||
*/
|
||||
save?: NgAddSaveDependency;
|
||||
}
|
||||
/**
|
||||
* Represents the configuration for `ng update` found in a package's manifest.
|
||||
*/
|
||||
export interface NgUpdate {
|
||||
/**
|
||||
* The path to the schematics collection for migrations.
|
||||
*/
|
||||
migrations?: string;
|
||||
/**
|
||||
* A list of package names that should be updated together.
|
||||
*/
|
||||
packageGroup?: string[];
|
||||
}
|
||||
/**
|
||||
* Represents the full metadata for a package available in the registry.
|
||||
* This includes a list of all available versions and distribution tags.
|
||||
*/
|
||||
export interface PackageMetadata {
|
||||
/** The name of the package. */
|
||||
name: string;
|
||||
/** A mapping of distribution tags (e.g., 'latest', 'next') to version numbers. */
|
||||
'dist-tags': Record<string, string>;
|
||||
/** An array of all available version strings for the package. */
|
||||
versions: string[];
|
||||
/** A mapping of version numbers to their ISO 8601 publication time string. */
|
||||
time?: Record<string, string>;
|
||||
}
|
||||
/**
|
||||
* Represents the manifest (similar to `package.json`) for a specific version of a package.
|
||||
* It contains metadata essential for the Angular CLI to perform operations like
|
||||
* `ng add` and `ng update`.
|
||||
*/
|
||||
export interface PackageManifest {
|
||||
/** The name of the package. */
|
||||
name: string;
|
||||
/** The version of the package. */
|
||||
version: string;
|
||||
/** A message indicating that the package version is deprecated. */
|
||||
deprecated?: string;
|
||||
/** A mapping of production dependencies. */
|
||||
dependencies?: Record<string, string>;
|
||||
/** A mapping of peer dependencies. */
|
||||
peerDependencies?: Record<string, string>;
|
||||
/** A mapping of peer dependency metadata */
|
||||
peerDependenciesMeta?: Record<string, {
|
||||
optional?: boolean;
|
||||
}>;
|
||||
/** A mapping of development dependencies. */
|
||||
devDependencies?: Record<string, string>;
|
||||
/** The URL to the package's homepage. */
|
||||
homepage?: string;
|
||||
/** The path to the schematics collection definition, used by `ng generate`. */
|
||||
schematics?: string;
|
||||
/** Configuration for the `ng add` command. */
|
||||
'ng-add'?: NgAdd;
|
||||
/** Configuration for the `ng update` command. */
|
||||
'ng-update'?: NgUpdate;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=package-metadata.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"package-metadata.js","sourceRoot":"","sources":["package-metadata.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG"}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* This file defines the interfaces for representing a project's installed
|
||||
* package dependency tree.
|
||||
*/
|
||||
/**
|
||||
* Represents a package that is installed in the project's node_modules.
|
||||
*/
|
||||
export interface InstalledPackage {
|
||||
/** The name of the package. */
|
||||
readonly name: string;
|
||||
/** The installed version of the package. */
|
||||
readonly version: string;
|
||||
/** The absolute path to the package's directory on disk, if available. */
|
||||
readonly path?: string;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=package-tree.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"package-tree.js","sourceRoot":"","sources":["package-tree.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG"}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @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';
|
||||
import { InstalledPackage } from './package-tree';
|
||||
/**
|
||||
* Parses the output of `npm list` or a compatible command.
|
||||
*
|
||||
* The expected JSON structure is:
|
||||
* ```json
|
||||
* {
|
||||
* "dependencies": {
|
||||
* "@angular/cli": {
|
||||
* "version": "18.0.0",
|
||||
* "path": "/path/to/project/node_modules/@angular/cli", // path is optional
|
||||
* ... (other package.json properties)
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @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>;
|
||||
/**
|
||||
* Parses the output of `yarn list` (classic).
|
||||
*
|
||||
* The expected output is a JSON stream (JSONL), where each line is a JSON object.
|
||||
* The relevant object has a `type` of `'tree'` with a `data` property.
|
||||
* Yarn classic does not provide a path, so the `path` property will be `undefined`.
|
||||
*
|
||||
* ```json
|
||||
* {"type":"tree","data":{"trees":[{"name":"@angular/cli@18.0.0","children":[]}]}}
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
export declare function parseYarnClassicDependencies(stdout: string, logger?: Logger): Map<string, InstalledPackage>;
|
||||
/**
|
||||
* Parses the output of `npm view` or a compatible command to get a package manifest.
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package manifest object.
|
||||
*/
|
||||
export declare function parseNpmLikeManifest(stdout: string, logger?: Logger): PackageManifest | null;
|
||||
/**
|
||||
* Parses the output of `npm view` or a compatible command to get package metadata.
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package metadata object.
|
||||
*/
|
||||
export declare function parseNpmLikeMetadata(stdout: string, logger?: Logger): PackageMetadata | null;
|
||||
/**
|
||||
* Parses the output of `yarn info` (classic) to get a package manifest.
|
||||
*
|
||||
* When `yarn info --verbose` is used, the output is a JSONL stream. This function
|
||||
* iterates through the lines to find the object with `type: 'inspect'` which contains
|
||||
* the package manifest.
|
||||
*
|
||||
* For non-verbose output, it falls back to parsing a single JSON object.
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package manifest object, or `null` if not found.
|
||||
*/
|
||||
export declare function parseYarnClassicManifest(stdout: string, logger?: Logger): PackageManifest | null;
|
||||
/**
|
||||
* Parses the output of `yarn info` (classic) to get package metadata.
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package metadata object.
|
||||
*/
|
||||
export declare function parseYarnClassicMetadata(stdout: string, logger?: Logger): PackageMetadata | null;
|
||||
/**
|
||||
* Parses the `stdout` or `stderr` output of npm, pnpm, modern yarn, or bun to extract structured error information.
|
||||
*
|
||||
* This parser uses a multi-stage approach. It first attempts to parse the entire `output` as a
|
||||
* single JSON object, which is the standard for modern tools like pnpm, yarn, and bun. If JSON
|
||||
* parsing fails, it falls back to a line-by-line regex-based approach to handle the plain
|
||||
* text output from older versions of npm.
|
||||
*
|
||||
* Example JSON output (pnpm):
|
||||
* ```json
|
||||
* {
|
||||
* "code": "E404",
|
||||
* "summary": "Not Found - GET https://registry.npmjs.org/@angular%2fnon-existent - Not found",
|
||||
* "detail": "The requested resource '@angular/non-existent@*' could not be found or you do not have permission to access it."
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Example text output (npm):
|
||||
* ```
|
||||
* npm error code E404
|
||||
* npm error 404 Not Found - GET https://registry.npmjs.org/@angular%2fnon-existent - Not found
|
||||
* ```
|
||||
*
|
||||
* @param output The standard output or standard error of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns An `ErrorInfo` object if parsing is successful, otherwise `null`.
|
||||
*/
|
||||
export declare function parseNpmLikeError(output: string, logger?: Logger): ErrorInfo | null;
|
||||
/**
|
||||
* Parses the `stdout` or `stderr` output of yarn classic to extract structured error information.
|
||||
*
|
||||
* This parser first attempts to find an HTTP status code (e.g., 404, 401) in the verbose output.
|
||||
* If found, it returns a standardized error code (`E${statusCode}`).
|
||||
* If no HTTP status code is found, it falls back to parsing generic JSON error lines.
|
||||
*
|
||||
* Example verbose output (with HTTP status code):
|
||||
* ```json
|
||||
* {"type":"verbose","data":"Request \"https://registry.npmjs.org/@angular%2fnon-existent\" finished with status code 404."}
|
||||
* ```
|
||||
*
|
||||
* Example generic JSON error output:
|
||||
* ```json
|
||||
* {"type":"error","data":"Received invalid response from npm."}
|
||||
* ```
|
||||
*
|
||||
* @param output The standard output or standard error of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns An `ErrorInfo` object if parsing is successful, otherwise `null`.
|
||||
*/
|
||||
export declare function parseYarnClassicError(output: string, logger?: Logger): ErrorInfo | null;
|
||||
/**
|
||||
* Parses the output of `bun pm ls`.
|
||||
*
|
||||
* Bun does not support JSON output for `pm ls`. The output is a tree structure:
|
||||
* ```
|
||||
* /path/to/project node_modules (1084)
|
||||
* ├── @angular/core@20.3.15
|
||||
* ├── rxjs @7.8.2
|
||||
* └── zone.js @0.15.1
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
export declare function parseBunDependencies(stdout: string, logger?: Logger): Map<string, InstalledPackage>;
|
||||
/**
|
||||
* Parses the output of `yarn info --name-only --json`.
|
||||
*
|
||||
* The expected output is a JSON stream (JSONL) of strings.
|
||||
* Each string represents a package locator.
|
||||
*
|
||||
* ```
|
||||
* "karma@npm:6.4.4"
|
||||
* "@angular/core@npm:20.3.15"
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
export declare function parseYarnModernDependencies(stdout: string, logger?: Logger): Map<string, InstalledPackage>;
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.parseNpmLikeDependencies = parseNpmLikeDependencies;
|
||||
exports.parseYarnClassicDependencies = parseYarnClassicDependencies;
|
||||
exports.parseNpmLikeManifest = parseNpmLikeManifest;
|
||||
exports.parseNpmLikeMetadata = parseNpmLikeMetadata;
|
||||
exports.parseYarnClassicManifest = parseYarnClassicManifest;
|
||||
exports.parseYarnClassicMetadata = parseYarnClassicMetadata;
|
||||
exports.parseNpmLikeError = parseNpmLikeError;
|
||||
exports.parseYarnClassicError = parseYarnClassicError;
|
||||
exports.parseBunDependencies = parseBunDependencies;
|
||||
exports.parseYarnModernDependencies = parseYarnModernDependencies;
|
||||
const MAX_LOG_LENGTH = 1024;
|
||||
function logStdout(stdout, logger) {
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
let output = stdout;
|
||||
if (output.length > MAX_LOG_LENGTH) {
|
||||
output = `${output.slice(0, MAX_LOG_LENGTH)}... (truncated)`;
|
||||
}
|
||||
logger.debug(` stdout:\n${output}`);
|
||||
}
|
||||
/**
|
||||
* A generator function that parses a string containing JSONL (newline-delimited JSON)
|
||||
* and yields each successfully parsed JSON object.
|
||||
* @param output The string output to parse.
|
||||
* @param logger An optional logger instance.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function* parseJsonLines(output, logger) {
|
||||
for (const line of output.split('\n')) {
|
||||
if (!line.trim()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
yield JSON.parse(line);
|
||||
}
|
||||
catch (e) {
|
||||
logger?.debug(` Ignoring non-JSON line: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Parses the output of `npm list` or a compatible command.
|
||||
*
|
||||
* The expected JSON structure is:
|
||||
* ```json
|
||||
* {
|
||||
* "dependencies": {
|
||||
* "@angular/cli": {
|
||||
* "version": "18.0.0",
|
||||
* "path": "/path/to/project/node_modules/@angular/cli", // path is optional
|
||||
* ... (other package.json properties)
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
function parseNpmLikeDependencies(stdout, logger) {
|
||||
logger?.debug(`Parsing npm-like dependency list...`);
|
||||
logStdout(stdout, logger);
|
||||
const dependencies = new Map();
|
||||
if (!stdout) {
|
||||
logger?.debug(' stdout is empty. No dependencies found.');
|
||||
return dependencies;
|
||||
}
|
||||
let data = JSON.parse(stdout);
|
||||
if (Array.isArray(data)) {
|
||||
// pnpm returns an array of projects.
|
||||
data = data[0];
|
||||
}
|
||||
const dependencyMaps = [data.dependencies, data.devDependencies, data.unsavedDependencies].filter((d) => !!d);
|
||||
if (dependencyMaps.length === 0) {
|
||||
logger?.debug(' `dependencies` property not found. No dependencies found.');
|
||||
return dependencies;
|
||||
}
|
||||
for (const dependencyMap of dependencyMaps) {
|
||||
for (const [name, info] of Object.entries(dependencyMap)) {
|
||||
dependencies.set(name, {
|
||||
name,
|
||||
version: info.version,
|
||||
path: info.path,
|
||||
});
|
||||
}
|
||||
}
|
||||
logger?.debug(` Found ${dependencies.size} dependencies.`);
|
||||
return dependencies;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `yarn list` (classic).
|
||||
*
|
||||
* The expected output is a JSON stream (JSONL), where each line is a JSON object.
|
||||
* The relevant object has a `type` of `'tree'` with a `data` property.
|
||||
* Yarn classic does not provide a path, so the `path` property will be `undefined`.
|
||||
*
|
||||
* ```json
|
||||
* {"type":"tree","data":{"trees":[{"name":"@angular/cli@18.0.0","children":[]}]}}
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
function parseYarnClassicDependencies(stdout, logger) {
|
||||
logger?.debug(`Parsing yarn classic dependency list...`);
|
||||
logStdout(stdout, logger);
|
||||
const dependencies = new Map();
|
||||
if (!stdout) {
|
||||
logger?.debug(' stdout is empty. No dependencies found.');
|
||||
return dependencies;
|
||||
}
|
||||
for (const json of parseJsonLines(stdout, logger)) {
|
||||
if (json.type === 'tree' && json.data?.trees) {
|
||||
for (const info of json.data.trees) {
|
||||
const lastAtIndex = info.name.lastIndexOf('@');
|
||||
const name = info.name.slice(0, lastAtIndex);
|
||||
const version = info.name.slice(lastAtIndex + 1);
|
||||
dependencies.set(name, {
|
||||
name,
|
||||
version,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
logger?.debug(` Found ${dependencies.size} dependencies.`);
|
||||
return dependencies;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `npm view` or a compatible command to get a package manifest.
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package manifest object.
|
||||
*/
|
||||
function parseNpmLikeManifest(stdout, logger) {
|
||||
logger?.debug(`Parsing npm-like manifest...`);
|
||||
logStdout(stdout, logger);
|
||||
if (!stdout) {
|
||||
logger?.debug(' stdout is empty. No manifest found.');
|
||||
return null;
|
||||
}
|
||||
const result = JSON.parse(stdout);
|
||||
return Array.isArray(result) ? result[result.length - 1] : result;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `npm view` or a compatible command to get package metadata.
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package metadata object.
|
||||
*/
|
||||
function parseNpmLikeMetadata(stdout, logger) {
|
||||
logger?.debug(`Parsing npm-like metadata...`);
|
||||
logStdout(stdout, logger);
|
||||
if (!stdout) {
|
||||
logger?.debug(' stdout is empty. No metadata found.');
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
/**
|
||||
* Parses the output of `yarn info` (classic) to get a package manifest.
|
||||
*
|
||||
* When `yarn info --verbose` is used, the output is a JSONL stream. This function
|
||||
* iterates through the lines to find the object with `type: 'inspect'` which contains
|
||||
* the package manifest.
|
||||
*
|
||||
* For non-verbose output, it falls back to parsing a single JSON object.
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package manifest object, or `null` if not found.
|
||||
*/
|
||||
function parseYarnClassicManifest(stdout, logger) {
|
||||
logger?.debug(`Parsing yarn classic manifest...`);
|
||||
logStdout(stdout, logger);
|
||||
if (!stdout) {
|
||||
logger?.debug(' stdout is empty. No manifest found.');
|
||||
return null;
|
||||
}
|
||||
// Yarn classic outputs JSONL. We need to find the relevant object.
|
||||
let manifest;
|
||||
for (const json of parseJsonLines(stdout, logger)) {
|
||||
// The manifest data is in a JSON object with type 'inspect'.
|
||||
if (json.type === 'inspect' && json.data) {
|
||||
manifest = json.data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!manifest) {
|
||||
logger?.debug(' Failed to find manifest in yarn classic output.');
|
||||
return null;
|
||||
}
|
||||
// Yarn classic removes any field with a falsy value
|
||||
// https://github.com/yarnpkg/yarn/blob/7cafa512a777048ce0b666080a24e80aae3d66a9/src/cli/commands/info.js#L26-L29
|
||||
// Add a default of 'false' for the `save` field when the `ng-add` object is present but does not have any fields.
|
||||
// There is a small chance this causes an incorrect value. However, the use of `ng-add` is rare and, in the cases
|
||||
// it is used, save is set to either a `false` literal or a truthy value. Special cases can be added for specific
|
||||
// packages if discovered.
|
||||
if (manifest['ng-add'] &&
|
||||
typeof manifest['ng-add'] === 'object' &&
|
||||
Object.keys(manifest['ng-add']).length === 0) {
|
||||
manifest['ng-add'].save ??= false;
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `yarn info` (classic) to get package metadata.
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns The package metadata object.
|
||||
*/
|
||||
function parseYarnClassicMetadata(stdout, logger) {
|
||||
logger?.debug(`Parsing yarn classic metadata...`);
|
||||
logStdout(stdout, logger);
|
||||
if (!stdout) {
|
||||
logger?.debug(' stdout is empty. No metadata found.');
|
||||
return null;
|
||||
}
|
||||
// Yarn classic outputs JSONL. We need to find the relevant object.
|
||||
let metadata;
|
||||
for (const json of parseJsonLines(stdout, logger)) {
|
||||
// The metadata data is in a JSON object with type 'inspect'.
|
||||
if (json.type === 'inspect' && json.data) {
|
||||
metadata = json.data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!metadata) {
|
||||
logger?.debug(' Failed to find metadata in yarn classic output.');
|
||||
return null;
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
/**
|
||||
* Parses the `stdout` or `stderr` output of npm, pnpm, modern yarn, or bun to extract structured error information.
|
||||
*
|
||||
* This parser uses a multi-stage approach. It first attempts to parse the entire `output` as a
|
||||
* single JSON object, which is the standard for modern tools like pnpm, yarn, and bun. If JSON
|
||||
* parsing fails, it falls back to a line-by-line regex-based approach to handle the plain
|
||||
* text output from older versions of npm.
|
||||
*
|
||||
* Example JSON output (pnpm):
|
||||
* ```json
|
||||
* {
|
||||
* "code": "E404",
|
||||
* "summary": "Not Found - GET https://registry.npmjs.org/@angular%2fnon-existent - Not found",
|
||||
* "detail": "The requested resource '@angular/non-existent@*' could not be found or you do not have permission to access it."
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Example text output (npm):
|
||||
* ```
|
||||
* npm error code E404
|
||||
* npm error 404 Not Found - GET https://registry.npmjs.org/@angular%2fnon-existent - Not found
|
||||
* ```
|
||||
*
|
||||
* @param output The standard output or standard error of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns An `ErrorInfo` object if parsing is successful, otherwise `null`.
|
||||
*/
|
||||
function parseNpmLikeError(output, logger) {
|
||||
logger?.debug(`Parsing npm-like error output...`);
|
||||
logStdout(output, logger); // Log output for debugging purposes
|
||||
if (!output) {
|
||||
logger?.debug(' output is empty. No error found.');
|
||||
return null;
|
||||
}
|
||||
// Attempt to parse as JSON first (common for pnpm, modern yarn, bun)
|
||||
try {
|
||||
const jsonError = JSON.parse(output);
|
||||
if (jsonError &&
|
||||
typeof jsonError.code === 'string' &&
|
||||
(typeof jsonError.summary === 'string' || typeof jsonError.message === 'string')) {
|
||||
const summary = jsonError.summary || jsonError.message;
|
||||
logger?.debug(` Successfully parsed JSON error with code '${jsonError.code}'.`);
|
||||
return {
|
||||
code: jsonError.code,
|
||||
summary,
|
||||
detail: jsonError.detail,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
logger?.debug(` Failed to parse output as JSON: ${e}. Attempting regex fallback.`);
|
||||
// Fallback to regex for plain text errors (common for npm)
|
||||
}
|
||||
// Regex for npm-like error codes (e.g., `npm ERR! code E404` or `npm error code E404`)
|
||||
const errorCodeMatch = output.match(/npm (ERR!|error) code (E\d{3}|[A-Z_]+)/);
|
||||
if (errorCodeMatch) {
|
||||
const code = errorCodeMatch[2]; // Capture group 2 is the actual error code
|
||||
let summary;
|
||||
// Find the most descriptive summary line (the line after `npm ERR! code ...` or `npm error code ...`).
|
||||
for (const line of output.split('\n')) {
|
||||
if (line.startsWith('npm ERR!') && !line.includes(' code ')) {
|
||||
summary = line.replace('npm ERR! ', '').trim();
|
||||
break;
|
||||
}
|
||||
else if (line.startsWith('npm error') && !line.includes(' code ')) {
|
||||
summary = line.replace('npm error ', '').trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
logger?.debug(` Successfully parsed text error with code '${code}'.`);
|
||||
return {
|
||||
code,
|
||||
summary: summary || `Package manager error: ${code}`,
|
||||
};
|
||||
}
|
||||
logger?.debug(' Failed to parse npm-like error. No structured error found.');
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Parses the `stdout` or `stderr` output of yarn classic to extract structured error information.
|
||||
*
|
||||
* This parser first attempts to find an HTTP status code (e.g., 404, 401) in the verbose output.
|
||||
* If found, it returns a standardized error code (`E${statusCode}`).
|
||||
* If no HTTP status code is found, it falls back to parsing generic JSON error lines.
|
||||
*
|
||||
* Example verbose output (with HTTP status code):
|
||||
* ```json
|
||||
* {"type":"verbose","data":"Request \"https://registry.npmjs.org/@angular%2fnon-existent\" finished with status code 404."}
|
||||
* ```
|
||||
*
|
||||
* Example generic JSON error output:
|
||||
* ```json
|
||||
* {"type":"error","data":"Received invalid response from npm."}
|
||||
* ```
|
||||
*
|
||||
* @param output The standard output or standard error of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns An `ErrorInfo` object if parsing is successful, otherwise `null`.
|
||||
*/
|
||||
function parseYarnClassicError(output, logger) {
|
||||
logger?.debug(`Parsing yarn classic error output...`);
|
||||
logStdout(output, logger); // Log output for debugging purposes
|
||||
if (!output) {
|
||||
logger?.debug(' output is empty. No error found.');
|
||||
return null;
|
||||
}
|
||||
// First, check for any HTTP status code in the verbose output.
|
||||
const statusCodeMatch = output.match(/finished with status code (\d{3})/);
|
||||
if (statusCodeMatch) {
|
||||
const statusCode = Number(statusCodeMatch[1]);
|
||||
// Status codes in the 200-299 range are successful.
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
logger?.debug(` Detected HTTP error status code '${statusCode}' in verbose output.`);
|
||||
return {
|
||||
code: `E${statusCode}`,
|
||||
summary: `Request failed with status code ${statusCode}.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
// Fallback to the JSON error type if no HTTP status code is present.
|
||||
for (const json of parseJsonLines(output, logger)) {
|
||||
if (json.type === 'error' && typeof json.data === 'string') {
|
||||
const summary = json.data;
|
||||
logger?.debug(` Successfully parsed generic yarn classic error.`);
|
||||
return {
|
||||
code: 'UNKNOWN_ERROR',
|
||||
summary,
|
||||
};
|
||||
}
|
||||
}
|
||||
logger?.debug(' Failed to parse yarn classic error. No structured error found.');
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `bun pm ls`.
|
||||
*
|
||||
* Bun does not support JSON output for `pm ls`. The output is a tree structure:
|
||||
* ```
|
||||
* /path/to/project node_modules (1084)
|
||||
* ├── @angular/core@20.3.15
|
||||
* ├── rxjs @7.8.2
|
||||
* └── zone.js @0.15.1
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
function parseBunDependencies(stdout, logger) {
|
||||
logger?.debug('Parsing Bun dependency list...');
|
||||
logStdout(stdout, logger);
|
||||
const dependencies = new Map();
|
||||
if (!stdout) {
|
||||
return dependencies;
|
||||
}
|
||||
const lines = stdout.split('\n');
|
||||
// Skip the first line (project info)
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
if (!line) {
|
||||
continue;
|
||||
}
|
||||
// Remove tree structure characters
|
||||
const cleanLine = line.replace(/^[└├]──\s*/, '');
|
||||
// Parse name and version
|
||||
// Scoped: @angular/core@20.3.15
|
||||
// Unscoped: rxjs @7.8.2
|
||||
const match = cleanLine.match(/^(.+?)\s?@([^@\s]+)$/);
|
||||
if (match) {
|
||||
const name = match[1];
|
||||
const version = match[2];
|
||||
dependencies.set(name, { name, version });
|
||||
}
|
||||
}
|
||||
logger?.debug(` Found ${dependencies.size} dependencies.`);
|
||||
return dependencies;
|
||||
}
|
||||
/**
|
||||
* Parses the output of `yarn info --name-only --json`.
|
||||
*
|
||||
* The expected output is a JSON stream (JSONL) of strings.
|
||||
* Each string represents a package locator.
|
||||
*
|
||||
* ```
|
||||
* "karma@npm:6.4.4"
|
||||
* "@angular/core@npm:20.3.15"
|
||||
* ```
|
||||
*
|
||||
* @param stdout The standard output of the command.
|
||||
* @param logger An optional logger instance.
|
||||
* @returns A map of package names to their installed package details.
|
||||
*/
|
||||
function parseYarnModernDependencies(stdout, logger) {
|
||||
logger?.debug('Parsing Yarn Berry dependency list...');
|
||||
logStdout(stdout, logger);
|
||||
const dependencies = new Map();
|
||||
if (!stdout) {
|
||||
return dependencies;
|
||||
}
|
||||
for (const json of parseJsonLines(stdout, logger)) {
|
||||
if (typeof json === 'string') {
|
||||
const match = json.match(/^(@?[^@]+)@(.+)$/);
|
||||
if (match) {
|
||||
const name = match[1];
|
||||
let version = match[2];
|
||||
// Handle "npm:" prefix
|
||||
if (version.startsWith('npm:')) {
|
||||
version = version.slice(4);
|
||||
}
|
||||
// Handle complex locators with embedded version metadata (e.g., "patch:...", "virtual:...")
|
||||
// Yarn Berry often appends metadata like "::version=x.y.z"
|
||||
const versionParamMatch = version.match(/::version=([^&]+)/);
|
||||
if (versionParamMatch) {
|
||||
version = versionParamMatch[1];
|
||||
}
|
||||
dependencies.set(name, { name, version });
|
||||
}
|
||||
}
|
||||
}
|
||||
logger?.debug(` Found ${dependencies.size} dependencies.`);
|
||||
return dependencies;
|
||||
}
|
||||
//# sourceMappingURL=parsers.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user