/**
* Core libraries that every NodeJS toolchain project should use.
*
* @packageDocumentation
*/
///
import * as child_process from 'child_process';
import * as fs from 'fs';
/**
* Specifies the behavior of APIs such as {@link FileSystem.copyFile} or
* {@link FileSystem.createSymbolicLinkFile} when the output file path already exists.
*
* @remarks
* For {@link FileSystem.copyFile} and related APIs, the "output file path" is
* {@link IFileSystemCopyFileOptions.destinationPath}.
*
* For {@link FileSystem.createSymbolicLinkFile} and related APIs, the "output file path" is
* {@link IFileSystemCreateLinkOptions.newLinkPath}.
*
* @public
*/
export declare enum AlreadyExistsBehavior {
/**
* If the output file path already exists, try to overwrite the existing object.
*
* @remarks
* If overwriting the object would require recursively deleting a folder tree,
* then the operation will fail. As an example, suppose {@link FileSystem.copyFile}
* is copying a single file `/a/b/c` to the destination path `/d/e`, and `/d/e` is a
* nonempty folder. In this situation, an error will be reported; specifying
* `AlreadyExistsBehavior.Overwrite` does not help. Empty folders can be overwritten
* depending on the details of the implementation.
*/
Overwrite = "overwrite",
/**
* If the output file path already exists, the operation will fail, and an error
* will be reported.
*/
Error = "error",
/**
* If the output file path already exists, skip this item, and continue the operation.
*/
Ignore = "ignore"
}
/**
* This exception can be thrown to indicate that an operation failed and an error message has already
* been reported appropriately. Thus, the catch handler does not have responsibility for reporting
* the error.
*
* @remarks
* For example, suppose a tool writes interactive output to `console.log()`. When an exception is thrown,
* the `catch` handler will typically provide simplistic reporting such as this:
*
* ```ts
* catch (error) {
* console.log("ERROR: " + error.message);
* }
* ```
*
* Suppose that the code performing the operation normally prints rich output to the console. It may be able to
* present an error message more nicely (for example, as part of a table, or structured log format). Throwing
* `AlreadyReportedError` provides a way to use exception handling to abort the operation, but instruct the `catch`
* handler not to print an error a second time:
*
* ```ts
* catch (error) {
* if (error instanceof AlreadyReportedError) {
* return;
* }
* console.log("ERROR: " + error.message);
* }
* ```
*
* @public
*/
export declare class AlreadyReportedError extends Error {
constructor();
static [Symbol.hasInstance](instance: object): boolean;
}
/**
* Utilities for parallel asynchronous operations, for use with the system `Promise` APIs.
*
* @public
*/
export declare class Async {
/**
* Given an input array and a `callback` function, invoke the callback to start a
* promise for each element in the array. Returns an array containing the results.
*
* @remarks
* This API is similar to the system `Array#map`, except that the loop is asynchronous,
* and the maximum number of concurrent promises can be throttled
* using {@link IAsyncParallelismOptions.concurrency}.
*
* If `callback` throws a synchronous exception, or if it returns a promise that rejects,
* then the loop stops immediately. Any remaining array items will be skipped, and
* overall operation will reject with the first error that was encountered.
*
* @param iterable - the array of inputs for the callback function
* @param callback - a function that starts an asynchronous promise for an element
* from the array
* @param options - options for customizing the control flow
* @returns an array containing the result for each callback, in the same order
* as the original input `array`
*/
static mapAsync(iterable: Iterable | AsyncIterable, callback: (entry: TEntry, arrayIndex: number) => Promise, options?: (IAsyncParallelismOptions & {
weighted?: false;
}) | undefined): Promise;
/**
* Given an input array and a `callback` function, invoke the callback to start a
* promise for each element in the array. Returns an array containing the results.
*
* @remarks
* This API is similar to the system `Array#map`, except that the loop is asynchronous,
* and the maximum number of concurrent units can be throttled
* using {@link IAsyncParallelismOptions.concurrency}. Using the {@link IAsyncParallelismOptions.weighted}
* option, the weight of each operation can be specified, which determines how many concurrent units it takes up.
*
* If `callback` throws a synchronous exception, or if it returns a promise that rejects,
* then the loop stops immediately. Any remaining array items will be skipped, and
* overall operation will reject with the first error that was encountered.
*
* @param iterable - the array of inputs for the callback function
* @param callback - a function that starts an asynchronous promise for an element
* from the array
* @param options - options for customizing the control flow
* @returns an array containing the result for each callback, in the same order
* as the original input `array`
*/
static mapAsync(iterable: Iterable | AsyncIterable, callback: (entry: TEntry, arrayIndex: number) => Promise, options: IAsyncParallelismOptions & {
weighted: true;
}): Promise;
private static _forEachWeightedAsync;
/**
* Given an input array and a `callback` function, invoke the callback to start a
* promise for each element in the array.
*
* @remarks
* This API is similar to the system `Array#forEach`, except that the loop is asynchronous,
* and the maximum number of concurrent promises can be throttled
* using {@link IAsyncParallelismOptions.concurrency}.
*
* If `callback` throws a synchronous exception, or if it returns a promise that rejects,
* then the loop stops immediately. Any remaining array items will be skipped, and
* overall operation will reject with the first error that was encountered.
*
* @param iterable - the array of inputs for the callback function
* @param callback - a function that starts an asynchronous promise for an element
* from the array
* @param options - options for customizing the control flow
*/
static forEachAsync(iterable: Iterable | AsyncIterable, callback: (entry: TEntry, arrayIndex: number) => Promise, options?: (IAsyncParallelismOptions & {
weighted?: false;
}) | undefined): Promise;
/**
* Given an input array and a `callback` function, invoke the callback to start a
* promise for each element in the array.
*
* @remarks
* This API is similar to the other `Array#forEachAsync`, except that each item can have
* a weight that determines how many concurrent operations are allowed. The unweighted
* `Array#forEachAsync` is a special case of this method where weight = 1 for all items.
*
* The maximum number of concurrent operations can still be throttled using
* {@link IAsyncParallelismOptions.concurrency}, however it no longer determines the
* maximum number of operations that can be in progress at once. Instead, it determines the
* number of concurrency units that can be in progress at once. The weight of each operation
* determines how many concurrency units it takes up. For example, if the concurrency is 2
* and the first operation has a weight of 2, then only one more operation can be in progress.
*
* If `callback` throws a synchronous exception, or if it returns a promise that rejects,
* then the loop stops immediately. Any remaining array items will be skipped, and
* overall operation will reject with the first error that was encountered.
*
* @param iterable - the array of inputs for the callback function
* @param callback - a function that starts an asynchronous promise for an element
* from the array
* @param options - options for customizing the control flow
*/
static forEachAsync(iterable: Iterable | AsyncIterable, callback: (entry: TEntry, arrayIndex: number) => Promise, options: IAsyncParallelismOptions & {
weighted: true;
}): Promise;
/**
* Return a promise that resolves after the specified number of milliseconds.
*/
static sleepAsync(ms: number): Promise;
/**
* Executes an async function and optionally retries it if it fails.
*/
static runWithRetriesAsync({ action, maxRetries, retryDelayMs }: IRunWithRetriesOptions): Promise;
/**
* Ensures that the argument is a valid {@link IWeighted}, with a `weight` argument that
* is a positive integer or 0.
*/
static validateWeightedIterable(operation: IWeighted): void;
/**
* Returns a Signal, a.k.a. a "deferred promise".
*/
static getSignal(): [Promise, () => void, (err: Error) => void];
}
/**
* A queue that allows for asynchronous iteration. During iteration, the queue will wait until
* the next item is pushed into the queue before yielding. If instead all queue items are consumed
* and all callbacks have been called, the queue will return.
*
* @public
*/
export declare class AsyncQueue implements AsyncIterable<[T, () => void]> {
private _queue;
private _onPushSignal;
private _onPushResolve;
constructor(iterable?: Iterable);
[Symbol.asyncIterator](): AsyncIterableIterator<[T, () => void]>;
/**
* Adds an item to the queue.
*
* @param item - The item to push into the queue.
*/
push(item: T): void;
}
/**
* A "branded type" is a primitive type with a compile-type key that makes it incompatible with other
* aliases for the primitive type.
*
* @remarks
*
* Example usage:
*
* ```ts
* // PhoneNumber is a branded type based on the "string" primitive.
* type PhoneNumber = Brand;
*
* function createPhoneNumber(input: string): PhoneNumber {
* if (!/\d+(\-\d+)+/.test(input)) {
* throw new Error('Invalid phone number: ' + JSON.stringify(input));
* }
* return input as PhoneNumber;
* }
*
* const p1: PhoneNumber = createPhoneNumber('123-456-7890');
*
* // PhoneNumber is a string and can be used as one:
* const p2: string = p1;
*
* // But an arbitrary string cannot be implicitly type cast as PhoneNumber.
* // ERROR: Type 'string' is not assignable to type 'PhoneNumber'
* const p3: PhoneNumber = '123-456-7890';
* ```
*
* For more information about this pattern, see {@link
* https://github.com/Microsoft/TypeScript/blob/7b48a182c05ea4dea81bab73ecbbe9e013a79e99/src/compiler/types.ts#L693-L698
* | this comment} explaining the TypeScript compiler's introduction of this pattern, and
* {@link https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/ | this article}
* explaining the technique in depth.
*
* @public
*/
export declare type Brand = T & {
__brand: BrandTag;
};
/**
* The allowed types of encodings, as supported by Node.js
* @public
*/
export declare enum Encoding {
Utf8 = "utf8"
}
/**
* A helper for looking up TypeScript `enum` keys/values.
*
* @remarks
* TypeScript enums implement a lookup table for mapping between their keys and values:
*
* ```ts
* enum Colors {
* Red = 1
* }
*
* // Prints "Red"
* console.log(Colors[1]);
*
* // Prints "1"
* console.log(Colors["Red]);
* ```
*
* However the compiler's "noImplicitAny" validation has trouble with these mappings, because
* there are so many possible types for the map elements:
*
* ```ts
* function f(s: string): Colors | undefined {
* // (TS 7015) Element implicitly has an 'any' type because
* // index expression is not of type 'number'.
* return Colors[s];
* }
* ```
*
* The `Enum` helper provides a more specific, strongly typed way to access members:
*
* ```ts
* function f(s: string): Colors | undefined {
* return Enum.tryGetValueByKey(Colors, s);
* }
* ```
*
* @public
*/
export declare class Enum {
private constructor();
/**
* Returns an enum value, given its key. Returns `undefined` if no matching key is found.
*
* @example
*
* Example usage:
* ```ts
* enum Colors {
* Red = 1
* }
*
* // Prints "1"
* console.log(Enum.tryGetValueByKey(Colors, "Red"));
*
* // Prints "undefined"
* console.log(Enum.tryGetValueByKey(Colors, "Black"));
* ```
*/
static tryGetValueByKey(enumObject: {
[key: string]: TEnumValue | string;
[key: number]: TEnumValue | string;
}, key: string): TEnumValue | undefined;
/**
* This API is similar to {@link Enum.tryGetValueByKey}, except that it throws an exception
* if the key is undefined.
*/
static getValueByKey(enumObject: {
[key: string]: TEnumValue | string;
[key: number]: TEnumValue | string;
}, key: string): TEnumValue;
/**
* Returns an enum string key, given its numeric value. Returns `undefined` if no matching value
* is found.
*
* @remarks
* The TypeScript compiler only creates a reverse mapping for enum members whose value is numeric.
* For example:
*
* ```ts
* enum E {
* A = 1,
* B = 'c'
* }
*
* // Prints "A"
* console.log(E[1]);
*
* // Prints "undefined"
* console.log(E["c"]);
* ```
*
* @example
*
* Example usage:
* ```ts
* enum Colors {
* Red = 1,
* Blue = 'blue'
* }
*
* // Prints "Red"
* console.log(Enum.tryGetKeyByNumber(Colors, 1));
*
* // Prints "undefined"
* console.log(Enum.tryGetKeyByNumber(Colors, -1));
* ```
*/
static tryGetKeyByNumber(enumObject: TEnumObject, value: number): keyof typeof enumObject | undefined;
/**
* This API is similar to {@link Enum.tryGetKeyByNumber}, except that it throws an exception
* if the key is undefined.
*/
static getKeyByNumber(enumObject: TEnumObject, value: number): keyof typeof enumObject;
}
/**
* A map data structure that stores process environment variables. On Windows
* operating system, the variable names are case-insensitive.
* @public
*/
export declare class EnvironmentMap {
private readonly _map;
/**
* Whether the environment variable names are case-sensitive.
*
* @remarks
* On Windows operating system, environment variables are case-insensitive.
* The map will preserve the variable name casing from the most recent assignment operation.
*/
readonly caseSensitive: boolean;
constructor(environmentObject?: Record);
/**
* Clears all entries, resulting in an empty map.
*/
clear(): void;
/**
* Assigns the variable to the specified value. A previous value will be overwritten.
*
* @remarks
* The value can be an empty string. To completely remove the entry, use
* {@link EnvironmentMap.unset} instead.
*/
set(name: string, value: string): void;
/**
* Removes the key from the map, if present.
*/
unset(name: string): void;
/**
* Returns the value of the specified variable, or `undefined` if the map does not contain that name.
*/
get(name: string): string | undefined;
/**
* Returns the map keys, which are environment variable names.
*/
names(): IterableIterator;
/**
* Returns the map entries.
*/
entries(): IterableIterator;
/**
* Adds each entry from `environmentMap` to this map.
*/
mergeFrom(environmentMap: EnvironmentMap): void;
/**
* Merges entries from a plain JavaScript object, such as would be used with the `process.env` API.
*/
mergeFromObject(environmentObject?: Record): void;
/**
* Returns the keys as a plain JavaScript object similar to the object returned by the `process.env` API.
*/
toObject(): Record;
}
/**
* The Executable class provides a safe, portable, recommended solution for tools that need
* to launch child processes.
*
* @remarks
* The NodeJS child_process API provides a solution for launching child processes, however
* its design encourages reliance on the operating system shell for certain features.
* Invoking the OS shell is not safe, not portable, and generally not recommended:
*
* - Different shells have different behavior and command-line syntax, and which shell you
* will get with NodeJS is unpredictable. There is no universal shell guaranteed to be
* available on all platforms.
*
* - If a command parameter contains symbol characters, a shell may interpret them, which
* can introduce a security vulnerability
*
* - Each shell has different rules for escaping these symbols. On Windows, the default
* shell is incapable of escaping certain character sequences.
*
* The Executable API provides a pure JavaScript implementation of primitive shell-like
* functionality for searching the default PATH, appending default file extensions on Windows,
* and executing a file that may contain a POSIX shebang. This primitive functionality
* is sufficient (and recommended) for most tooling scenarios.
*
* If you need additional shell features such as wildcard globbing, environment variable
* expansion, piping, or built-in commands, then we recommend to use the `@microsoft/rushell`
* library instead. Rushell is a pure JavaScript shell with a standard syntax that is
* guaranteed to work consistently across all platforms.
*
* @public
*/
export declare class Executable {
/**
* Synchronously create a child process and optionally capture its output.
*
* @remarks
* This function is similar to child_process.spawnSync(). The main differences are:
*
* - It does not invoke the OS shell unless the executable file is a shell script.
* - Command-line arguments containing special characters are more accurately passed
* through to the child process.
* - If the filename is missing a path, then the shell's default PATH will be searched.
* - If the filename is missing a file extension, then Windows default file extensions
* will be searched.
*
* @param filename - The name of the executable file. This string must not contain any
* command-line arguments. If the name contains any path delimiters, then the shell's
* default PATH will not be searched.
* @param args - The command-line arguments to be passed to the process.
* @param options - Additional options
* @returns the same data type as returned by the NodeJS child_process.spawnSync() API
*
* @privateRemarks
*
* NOTE: The NodeJS spawnSync() returns SpawnSyncReturns or SpawnSyncReturns
* polymorphically based on the options.encoding parameter value. This is a fairly confusing
* design. In most cases, developers want string with the default encoding. If/when someone
* wants binary output or a non-default text encoding, we will introduce a separate API function
* with a name like "spawnWithBufferSync".
*/
static spawnSync(filename: string, args: string[], options?: IExecutableSpawnSyncOptions): child_process.SpawnSyncReturns;
/**
* Start a child process.
*
* @remarks
* This function is similar to child_process.spawn(). The main differences are:
*
* - It does not invoke the OS shell unless the executable file is a shell script.
* - Command-line arguments containing special characters are more accurately passed
* through to the child process.
* - If the filename is missing a path, then the shell's default PATH will be searched.
* - If the filename is missing a file extension, then Windows default file extensions
* will be searched.
*
* This command is asynchronous, but it does not return a `Promise`. Instead it returns
* a Node.js `ChildProcess` supporting event notifications.
*
* @param filename - The name of the executable file. This string must not contain any
* command-line arguments. If the name contains any path delimiters, then the shell's
* default PATH will not be searched.
* @param args - The command-line arguments to be passed to the process.
* @param options - Additional options
* @returns the same data type as returned by the NodeJS child_process.spawnSync() API
*/
static spawn(filename: string, args: string[], options?: IExecutableSpawnOptions): child_process.ChildProcess;
/** {@inheritDoc Executable.(waitForExitAsync:3)} */
static waitForExitAsync(childProcess: child_process.ChildProcess, options: IWaitForExitWithStringOptions): Promise>;
/** {@inheritDoc Executable.(waitForExitAsync:3)} */
static waitForExitAsync(childProcess: child_process.ChildProcess, options: IWaitForExitWithBufferOptions): Promise>;
/**
* Wait for a child process to exit and return the result.
*
* @param childProcess - The child process to wait for.
* @param options - Options for waiting for the process to exit.
*/
static waitForExitAsync(childProcess: child_process.ChildProcess, options?: IWaitForExitOptions): Promise>;
/**
* Get the list of processes currently running on the system, keyed by the process ID.
*
* @remarks The underlying implementation depends on the operating system:
* - On Windows, this uses the `wmic.exe` utility.
* - On Unix, this uses the `ps` utility.
*/
static getProcessInfoByIdAsync(): Promise