@rushstack/node-core-library
Advanced tools
+8
-1
| # Change Log - @rushstack/node-core-library | ||
| This log was last generated on Tue, 30 Sep 2025 23:57:45 GMT and should not be manually modified. | ||
| This log was last generated on Fri, 03 Oct 2025 20:09:59 GMT and should not be manually modified. | ||
| ## 5.16.0 | ||
| Fri, 03 Oct 2025 20:09:59 GMT | ||
| ### Minor changes | ||
| - Normalize import of builtin modules to use the `node:` protocol. | ||
| ## 5.15.1 | ||
@@ -6,0 +13,0 @@ Tue, 30 Sep 2025 23:57:45 GMT |
@@ -8,5 +8,5 @@ // This file is read by tools that parse documentation comments conforming to the TSDoc standard. | ||
| "packageName": "@microsoft/api-extractor", | ||
| "packageVersion": "7.52.11" | ||
| "packageVersion": "7.52.15" | ||
| } | ||
| ] | ||
| } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"EnvironmentMap.d.ts","sourceRoot":"","sources":["../src/EnvironmentMap.ts"],"names":[],"mappings":"AAMA;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;GAIG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6C;IAElE;;;;;;OAMG;IACH,SAAgB,aAAa,EAAE,OAAO,CAAC;gBAEpB,iBAAiB,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAM;IAe7E;;OAEG;IACI,KAAK,IAAI,IAAI;IAIpB;;;;;;OAMG;IACI,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAK7C;;OAEG;IACI,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAKhC;;OAEG;IACI,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAS5C;;OAEG;IACI,KAAK,IAAI,gBAAgB,CAAC,MAAM,CAAC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AAM,GAAG,SAAS,CAAM,GAAG,IAAI;IAQxF;;OAEG;IACI,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;CAO1C"} |
@@ -9,3 +9,3 @@ "use strict"; | ||
| exports.EnvironmentMap = void 0; | ||
| const process_1 = __importDefault(require("process")); | ||
| const node_process_1 = __importDefault(require("node:process")); | ||
| const InternalError_1 = require("./InternalError"); | ||
@@ -29,3 +29,3 @@ /** | ||
| }); | ||
| this.caseSensitive = process_1.default.platform !== 'win32'; | ||
| this.caseSensitive = node_process_1.default.platform !== 'win32'; | ||
| this.mergeFromObject(environmentObject); | ||
@@ -32,0 +32,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"EnvironmentMap.js","sourceRoot":"","sources":["../src/EnvironmentMap.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;AAE3D,sDAA8B;AAC9B,mDAAgD;AAkBhD;;;;GAIG;AACH,MAAa,cAAc;IAYzB,YAAmB,oBAAwD,EAAE;QAX5D,SAAI,GAAmC,IAAI,GAAG,EAAE,CAAC;QAYhE,sGAAsG;QACtG,oGAAoG;QACpG,qGAAqG;QACrG,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,cAAc,EAAE;YAC1C,UAAU,EAAE,IAAI;YAChB,GAAG,EAAE;gBACH,MAAM,IAAI,6BAAa,CAAC,mDAAmD,CAAC,CAAC;YAC/E,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,aAAa,GAAG,iBAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;QAClD,IAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC,CAAC;IAC1C,CAAC;IAED;;OAEG;IACI,KAAK;QACV,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACI,GAAG,CAAC,IAAY,EAAE,KAAa;QACpC,MAAM,GAAG,GAAW,IAAI,CAAC,aAAa,CAAC,CAAC,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K,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,CAAC;YAC9D,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACxB,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YACxB,CAAC;QACH,CAAC;IACH,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,MAAM,MAAM,GAA2B,EAAE,CAAC;QAC1C,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;YACnC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;QACnC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA9GD,wCA8GC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport process from 'process';\nimport { InternalError } from './InternalError';\n\n/**\n * A process environment variable name and its value. Used by {@link EnvironmentMap}.\n * @public\n */\nexport interface IEnvironmentEntry {\n /**\n * The name of the environment variable.\n */\n name: string;\n\n /**\n * The value of the environment variable.\n */\n value: string;\n}\n\n/**\n * A map data structure that stores process environment variables. On Windows\n * operating system, the variable names are case-insensitive.\n * @public\n */\nexport class EnvironmentMap {\n private readonly _map: Map<string, IEnvironmentEntry> = new Map();\n\n /**\n * Whether the environment variable names are case-sensitive.\n *\n * @remarks\n * On Windows operating system, environment variables are case-insensitive.\n * The map will preserve the variable name casing from the most recent assignment operation.\n */\n public readonly caseSensitive: boolean;\n\n public constructor(environmentObject: Record<string, string | undefined> = {}) {\n // This property helps catch a mistake where an instance of `EnvironmentMap` is accidentally passed to\n // a function that expects a `Record<string, string>` (as would be used with the `process.env` API).\n // The property getter will throw an exception if that function tries to enumerate the object values.\n Object.defineProperty(this, '_sanityCheck', {\n enumerable: true,\n get: function () {\n throw new InternalError('Attempt to read EnvironmentMap class as an object');\n }\n });\n\n this.caseSensitive = process.platform !== 'win32';\n this.mergeFromObject(environmentObject);\n }\n\n /**\n * Clears all entries, resulting in an empty map.\n */\n public clear(): void {\n this._map.clear();\n }\n\n /**\n * Assigns the variable to the specified value. A previous value will be overwritten.\n *\n * @remarks\n * The value can be an empty string. To completely remove the entry, use\n * {@link EnvironmentMap.unset} instead.\n */\n public set(name: string, value: string): void {\n const key: string = this.caseSensitive ? name : name.toUpperCase();\n this._map.set(key, { name: name, value });\n }\n\n /**\n * Removes the key from the map, if present.\n */\n public unset(name: string): void {\n const key: string = this.caseSensitive ? name : name.toUpperCase();\n this._map.delete(key);\n }\n\n /**\n * Returns the value of the specified variable, or `undefined` if the map does not contain that name.\n */\n public get(name: string): string | undefined {\n const key: string = this.caseSensitive ? name : name.toUpperCase();\n const entry: IEnvironmentEntry | undefined = this._map.get(key);\n if (entry === undefined) {\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Returns the map keys, which are environment variable names.\n */\n public names(): IterableIterator<string> {\n return this._map.keys();\n }\n\n /**\n * Returns the map entries.\n */\n public entries(): IterableIterator<IEnvironmentEntry> {\n return this._map.values();\n }\n\n /**\n * Adds each entry from `environmentMap` to this map.\n */\n public mergeFrom(environmentMap: EnvironmentMap): void {\n for (const entry of environmentMap.entries()) {\n this.set(entry.name, entry.value);\n }\n }\n\n /**\n * Merges entries from a plain JavaScript object, such as would be used with the `process.env` API.\n */\n public mergeFromObject(environmentObject: Record<string, string | undefined> = {}): void {\n for (const [name, value] of Object.entries(environmentObject)) {\n if (value !== undefined) {\n this.set(name, value);\n }\n }\n }\n\n /**\n * Returns the keys as a plain JavaScript object similar to the object returned by the `process.env` API.\n */\n public toObject(): Record<string, string> {\n const result: Record<string, string> = {};\n for (const entry of this.entries()) {\n result[entry.name] = entry.value;\n }\n return result;\n }\n}\n"]} | ||
| {"version":3,"file":"EnvironmentMap.js","sourceRoot":"","sources":["../src/EnvironmentMap.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;AAE3D,gEAAmC;A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AAK,GAAkC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAChE,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,KAAK,CAAC,KAAK,CAAC;IACrB,CAAC;IAED;;OAEG;IACI,KAAK;QACV,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAC1B,CAAC;IAED;;OAEG;IACI,OAAO;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IAC5B,CAAC;IAED;;OAEG;IACI,SAAS,CAAC,cAA8B;QAC7C,KAAK,MAAM,KAAK,IAAI,cAAc,CAAC,OAAO,EAAE,EAAE,CAAC;YAC7C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IAED;;OAEG;IACI,eAAe,CAAC,oBAAwD,EAAE;QAC/E,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,CAAC;YAC9D,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACxB,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YACxB,CAAC;QACH,CAAC;IACH,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,MAAM,MAAM,GAA2B,EAAE,CAAC;QAC1C,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;YACnC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;QACnC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA9GD,wCA8GC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport process from 'node:process';\n\nimport { InternalError } from './InternalError';\n\n/**\n * A process environment variable name and its value. Used by {@link EnvironmentMap}.\n * @public\n */\nexport interface IEnvironmentEntry {\n /**\n * The name of the environment variable.\n */\n name: string;\n\n /**\n * The value of the environment variable.\n */\n value: string;\n}\n\n/**\n * A map data structure that stores process environment variables. On Windows\n * operating system, the variable names are case-insensitive.\n * @public\n */\nexport class EnvironmentMap {\n private readonly _map: Map<string, IEnvironmentEntry> = new Map();\n\n /**\n * Whether the environment variable names are case-sensitive.\n *\n * @remarks\n * On Windows operating system, environment variables are case-insensitive.\n * The map will preserve the variable name casing from the most recent assignment operation.\n */\n public readonly caseSensitive: boolean;\n\n public constructor(environmentObject: Record<string, string | undefined> = {}) {\n // This property helps catch a mistake where an instance of `EnvironmentMap` is accidentally passed to\n // a function that expects a `Record<string, string>` (as would be used with the `process.env` API).\n // The property getter will throw an exception if that function tries to enumerate the object values.\n Object.defineProperty(this, '_sanityCheck', {\n enumerable: true,\n get: function () {\n throw new InternalError('Attempt to read EnvironmentMap class as an object');\n }\n });\n\n this.caseSensitive = process.platform !== 'win32';\n this.mergeFromObject(environmentObject);\n }\n\n /**\n * Clears all entries, resulting in an empty map.\n */\n public clear(): void {\n this._map.clear();\n }\n\n /**\n * Assigns the variable to the specified value. A previous value will be overwritten.\n *\n * @remarks\n * The value can be an empty string. To completely remove the entry, use\n * {@link EnvironmentMap.unset} instead.\n */\n public set(name: string, value: string): void {\n const key: string = this.caseSensitive ? name : name.toUpperCase();\n this._map.set(key, { name: name, value });\n }\n\n /**\n * Removes the key from the map, if present.\n */\n public unset(name: string): void {\n const key: string = this.caseSensitive ? name : name.toUpperCase();\n this._map.delete(key);\n }\n\n /**\n * Returns the value of the specified variable, or `undefined` if the map does not contain that name.\n */\n public get(name: string): string | undefined {\n const key: string = this.caseSensitive ? name : name.toUpperCase();\n const entry: IEnvironmentEntry | undefined = this._map.get(key);\n if (entry === undefined) {\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Returns the map keys, which are environment variable names.\n */\n public names(): IterableIterator<string> {\n return this._map.keys();\n }\n\n /**\n * Returns the map entries.\n */\n public entries(): IterableIterator<IEnvironmentEntry> {\n return this._map.values();\n }\n\n /**\n * Adds each entry from `environmentMap` to this map.\n */\n public mergeFrom(environmentMap: EnvironmentMap): void {\n for (const entry of environmentMap.entries()) {\n this.set(entry.name, entry.value);\n }\n }\n\n /**\n * Merges entries from a plain JavaScript object, such as would be used with the `process.env` API.\n */\n public mergeFromObject(environmentObject: Record<string, string | undefined> = {}): void {\n for (const [name, value] of Object.entries(environmentObject)) {\n if (value !== undefined) {\n this.set(name, value);\n }\n }\n }\n\n /**\n * Returns the keys as a plain JavaScript object similar to the object returned by the `process.env` API.\n */\n public toObject(): Record<string, string> {\n const result: Record<string, string> = {};\n for (const entry of this.entries()) {\n result[entry.name] = entry.value;\n }\n return result;\n }\n}\n"]} |
@@ -1,2 +0,2 @@ | ||
| import * as child_process from 'child_process'; | ||
| import * as child_process from 'node:child_process'; | ||
| import { EnvironmentMap } from './EnvironmentMap'; | ||
@@ -3,0 +3,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Executable.d.ts","sourceRoot":"","sources":["../src/Executable.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,aAAa,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AASlD;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GACpC,MAAM,GACN,QAAQ,GACR,SAAS,GACT,MAAM,CAAC,cAAc,GACrB,MAAM,CAAC,cAAc,GACrB,MAAM,GACN,SAAS,CAAC;AAEd;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,4BAA4B,EAAE,CAAC;AAEpG;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,uBAAuB,CAAC,EAAE,MAAM,CAAC;IAEjC;;;;;;OAMG;IACH,WAAW,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CAAC,WAAW;IAgC1B;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAsChC,OAAO,CAAC,MAAM,CAAC,qBAAqB;IAqCpC;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,0BAA0B;IAKzC;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,4BAA4B;CAwB5C"} |
@@ -41,5 +41,5 @@ "use strict"; | ||
| exports.parseProcessListOutput = parseProcessListOutput; | ||
| const os = __importStar(require("os")); | ||
| const child_process = __importStar(require("child_process")); | ||
| const path = __importStar(require("path")); | ||
| const os = __importStar(require("node:os")); | ||
| const child_process = __importStar(require("node:child_process")); | ||
| const path = __importStar(require("node:path")); | ||
| const EnvironmentMap_1 = require("./EnvironmentMap"); | ||
@@ -46,0 +46,0 @@ const FileSystem_1 = require("./FileSystem"); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Executable.js","sourceRoot":"","sources":["../src/Executable.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8O3D,kEAcC;AAED,wDAeC;AA3QD,uCAAyB;AACzB,6DAA+C;AAC/C,2CAA6B;AAC7B,qDAAkD;AAElD,6CAA0C;AAC1C,mDAAgD;AAChD,iCAA8B;AAC9B,mDAAgD;AAEhD,MAAM,WAAW,GAAoB,EAAE,CAAC,QAAQ,EAAE,CAAC;AAkO5C,KAAK,UAAU,2BAA2B,CAC/C,MAA6B,EAC7B,WAA4B,WAAW;IAEvC,MAAM,eAAe,GAA8B,IAAI,GAAG,EAAwB,CAAC;IACnF,IAAI,WAAW,GAAY,KAAK,CAAC;IACjC,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,WAAI,CAAC,0BAA0B,CAAC,MAAM,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;QAC7F,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,WAAW,GAAG,IAAI,CA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AAG,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;YACpE,IAAI,KAAK,EAAE,CAAC;gBACV,4EAA4E;gBAC5E,4EAA4E;gBAC5E,2EAA2E;gBAC3E,yEAAyE;gBACzE,iFAAiF;gBACjF,4EAA4E;gBAC5E,4DAA4D;gBAC5D,EAAE;gBACF,0EAA0E;gBAC1E,sEAAsE;gBACtE,qEAAqE;gBACrE,MAAM,IAAI,KAAK,CACb,6BAA6B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa;oBAC3D,sBAAsB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,+CAA+C,CAChG,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAxlBD,gCAwlBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'os';\nimport * as child_process from 'child_process';\nimport * as path from 'path';\nimport { EnvironmentMap } from './EnvironmentMap';\n\nimport { FileSystem } from './FileSystem';\nimport { PosixModeBits } from './PosixModeBits';\nimport { Text } from './Text';\nimport { InternalError } from './InternalError';\n\nconst OS_PLATFORM: NodeJS.Platform = os.platform();\n\n/**\n * Typings for one of the streams inside IExecutableSpawnSyncOptions.stdio.\n * @public\n */\nexport type ExecutableStdioStreamMapping =\n | 'pipe'\n | 'ignore'\n | 'inherit'\n | NodeJS.WritableStream\n | NodeJS.ReadableStream\n | number\n | undefined;\n\n/**\n * Types for {@link IExecutableSpawnSyncOptions.stdio}\n * and {@link IExecutableSpawnOptions.stdio}\n * @public\n */\nexport type ExecutableStdioMapping = 'pipe' | 'ignore' | 'inherit' | ExecutableStdioStreamMapping[];\n\n/**\n * Options for Executable.tryResolve().\n * @public\n */\nexport interface IExecutableResolveOptions {\n /**\n * The current working directory. If omitted, process.cwd() will be used.\n */\n currentWorkingDirectory?: string;\n\n /**\n * The environment variables for the child process.\n *\n * @remarks\n * If `environment` and `environmentMap` are both omitted, then `process.env` will be used.\n * If `environment` and `environmentMap` cannot both be specified.\n */\n environment?: NodeJS.ProcessEnv;\n\n /**\n * The environment variables for the child process.\n *\n * @remarks\n * If `environment` and `environmentMap` are both omitted, then `process.env` will be used.\n * If `environment` and `environmentMap` cannot both be specified.\n */\n environmentMap?: EnvironmentMap;\n}\n\n/**\n * Options for {@link Executable.spawnSync}\n * @public\n */\nexport interface IExecutableSpawnSyncOptions extends IExecutableResolveOptions {\n /**\n * The content to be passed to the child process's stdin.\n *\n * NOTE: If specified, this content replaces any IExecutableSpawnSyncOptions.stdio[0]\n * mapping for stdin.\n */\n input?: string;\n\n /**\n * The stdio mappings for the child process.\n *\n * NOTE: If IExecutableSpawnSyncOptions.input is provided, it will take precedence\n * over the stdin mapping (stdio[0]).\n */\n stdio?: ExecutableStdioMapping;\n\n /**\n * The maximum time the process is allowed to run before it will be terminated.\n */\n timeoutMs?: number;\n\n /**\n * The largest amount of bytes allowed on stdout or stderr for this synchronous operation.\n * If exceeded, the child process will be terminated. The default is 200 * 1024.\n */\n maxBuffer?: number;\n}\n\n/**\n * Options for {@link Executable.spawn}\n * @public\n */\nexport interface IExecutableSpawnOptions extends IExecutableResolveOptions {\n /**\n * The stdio mappings for the child process.\n *\n * NOTE: If IExecutableSpawnSyncOptions.input is provided, it will take precedence\n * over the stdin mapping (stdio[0]).\n */\n stdio?: ExecutableStdioMapping;\n}\n\n/**\n * The options for running a process to completion using {@link Executable.(waitForExitAsync:3)}.\n *\n * @public\n */\nexport interface IWaitForExitOptions {\n /**\n * Whether or not to throw when the process completes with a non-zero exit code. Defaults to false.\n *\n * @defaultValue false\n */\n throwOnNonZeroExitCode?: boolean;\n\n /**\n * Whether or not to throw when the process is terminated by a signal. Defaults to false.\n *\n * @defaultValue false\n */\n throwOnSignal?: boolean;\n\n /**\n * The encoding of the output. If not provided, the output will not be collected.\n */\n encoding?: BufferEncoding | 'buffer';\n}\n\n/**\n * {@inheritDoc IWaitForExitOptions}\n *\n * @public\n */\nexport interface IWaitForExitWithStringOptions extends IWaitForExitOptions {\n /**\n * {@inheritDoc IWaitForExitOptions.encoding}\n */\n encoding: BufferEncoding;\n}\n\n/**\n * {@inheritDoc IWaitForExitOptions}\n *\n * @public\n */\nexport interface IWaitForExitWithBufferOptions extends IWaitForExitOptions {\n /**\n * {@inheritDoc IWaitForExitOptions.encoding}\n */\n encoding: 'buffer';\n}\n\n/**\n * The result of running a process to completion using {@link Executable.(waitForExitAsync:3)}.\n *\n * @public\n */\nexport interface IWaitForExitResult<T extends Buffer | string | never = never> {\n /**\n * The process stdout output, if encoding was specified.\n */\n stdout: T;\n\n /**\n * The process stderr output, if encoding was specified.\n */\n stderr: T;\n\n /**\n * The process exit code. If the process was terminated, this will be null.\n */\n // eslint-disable-next-line @rushstack/no-new-null\n exitCode: number | null;\n\n /**\n * The process signal that terminated the process. If the process exited normally, this will be null.\n */\n // eslint-disable-next-line @rushstack/no-new-null\n signal: string | null;\n}\n\n// Common environmental state used by Executable members\ninterface IExecutableContext {\n currentWorkingDirectory: string;\n environmentMap: EnvironmentMap;\n // For Windows, the parsed PATHEXT environment variable\n windowsExecutableExtensions: string[];\n}\n\ninterface ICommandLineOptions {\n path: string;\n args: string[];\n}\n\n/**\n * Process information sourced from the system. This process info is sourced differently depending\n * on the operating system:\n * - On Windows, this uses the `wmic.exe` utility.\n * - On Unix, this uses the `ps` utility.\n *\n * @public\n */\nexport interface IProcessInfo {\n /**\n * The name of the process.\n *\n * @remarks On Windows, the process name will be empty if the process is a kernel process.\n * On Unix, the process name will be empty if the process is the root process.\n */\n processName: string;\n\n /**\n * The process ID.\n */\n processId: number;\n\n /**\n * The parent process info.\n *\n * @remarks On Windows, the parent process info will be undefined if the process is a kernel process.\n * On Unix, the parent process info will be undefined if the process is the root process.\n */\n parentProcessInfo: IProcessInfo | undefined;\n\n /**\n * The child process infos.\n */\n childProcessInfos: IProcessInfo[];\n}\n\nexport async function parseProcessListOutputAsync(\n stream: NodeJS.ReadableStream,\n platform: NodeJS.Platform = OS_PLATFORM\n): Promise<Map<number, IProcessInfo>> {\n const processInfoById: Map<number, IProcessInfo> = new Map<number, IProcessInfo>();\n let seenHeaders: boolean = false;\n for await (const line of Text.readLinesFromIterableAsync(stream, { ignoreEmptyLines: true })) {\n if (!seenHeaders) {\n seenHeaders = true;\n } else {\n parseProcessInfoEntry(line, processInfoById, platform);\n }\n }\n return processInfoById;\n}\n\nexport function parseProcessListOutput(\n // eslint-disable-next-line @rushstack/no-new-null\n output: Iterable<string | null>,\n platform: NodeJS.Platform = OS_PLATFORM\n): Map<number, IProcessInfo> {\n const processInfoById: Map<number, IProcessInfo> = new Map<number, IProcessInfo>();\n let seenHeaders: boolean = false;\n for (const line of Text.readLinesFromIterable(output, { ignoreEmptyLines: true })) {\n if (!seenHeaders) {\n seenHeaders = true;\n } else {\n parseProcessInfoEntry(line, processInfoById, platform);\n }\n }\n return processInfoById;\n}\n\n// win32 format:\n// Name ParentProcessId ProcessId\n// process name 1234 5678\n// unix format:\n// PPID PID COMMAND\n// 51234 56784 process name\nconst NAME_GROUP: 'name' = 'name';\nconst PROCESS_ID_GROUP: 'pid' = 'pid';\nconst PARENT_PROCESS_ID_GROUP: 'ppid' = 'ppid';\nconst PROCESS_LIST_ENTRY_REGEX_WIN32: RegExp = new RegExp(\n `^(?<${NAME_GROUP}>.+?)\\\\s+(?<${PARENT_PROCESS_ID_GROUP}>\\\\d+)\\\\s+(?<${PROCESS_ID_GROUP}>\\\\d+)\\\\s*$`\n);\nconst PROCESS_LIST_ENTRY_REGEX_UNIX: RegExp = new RegExp(\n `^\\\\s*(?<${PARENT_PROCESS_ID_GROUP}>\\\\d+)\\\\s+(?<${PROCESS_ID_GROUP}>\\\\d+)\\\\s+(?<${NAME_GROUP}>.+?)\\\\s*$`\n);\n\nfunction parseProcessInfoEntry(\n line: string,\n existingProcessInfoById: Map<number, IProcessInfo>,\n platform: NodeJS.Platform\n): void {\n const processListEntryRegex: RegExp =\n platform === 'win32' ? PROCESS_LIST_ENTRY_REGEX_WIN32 : PROCESS_LIST_ENTRY_REGEX_UNIX;\n const match: RegExpMatchArray | null = line.match(processListEntryRegex);\n if (!match?.groups) {\n throw new InternalError(`Invalid process list entry: ${line}`);\n }\n\n const processName: string = match.groups[NAME_GROUP];\n const processId: number = parseInt(match.groups[PROCESS_ID_GROUP], 10);\n const parentProcessId: number = parseInt(match.groups[PARENT_PROCESS_ID_GROUP], 10);\n\n // Only care about the parent process if it is not the same as the current process.\n let parentProcessInfo: IProcessInfo | undefined;\n if (parentProcessId !== processId) {\n parentProcessInfo = existingProcessInfoById.get(parentProcessId);\n if (!parentProcessInfo) {\n // Create a new placeholder entry for the parent with the information we have so far\n parentProcessInfo = {\n processName: '',\n processId: parentProcessId,\n parentProcessInfo: undefined,\n childProcessInfos: []\n };\n existingProcessInfoById.set(parentProcessId, parentProcessInfo);\n }\n }\n\n let processInfo: IProcessInfo | undefined = existingProcessInfoById.get(processId);\n if (!processInfo) {\n // Create a new entry\n processInfo = {\n processName,\n processId,\n parentProcessInfo,\n childProcessInfos: []\n };\n existingProcessInfoById.set(processId, processInfo);\n } else {\n // Update placeholder entry\n processInfo.processName = processName;\n processInfo.parentProcessInfo = parentProcessInfo;\n }\n\n // Add the process as a child of the parent process\n parentProcessInfo?.childProcessInfos.push(processInfo);\n}\n\nfunction convertToProcessInfoByNameMap(\n processInfoById: Map<number, IProcessInfo>\n): Map<string, IProcessInfo[]> {\n const processInfoByNameMap: Map<string, IProcessInfo[]> = new Map<string, IProcessInfo[]>();\n for (const processInfo of processInfoById.values()) {\n let processInfoNameEntries: IProcessInfo[] | undefined = processInfoByNameMap.get(\n processInfo.processName\n );\n if (!processInfoNameEntries) {\n processInfoNameEntries = [];\n processInfoByNameMap.set(processInfo.processName, processInfoNameEntries);\n }\n processInfoNameEntries.push(processInfo);\n }\n return processInfoByNameMap;\n}\n\nfunction getProcessListProcessOptions(): ICommandLineOptions {\n let command: string;\n let args: string[];\n if (OS_PLATFORM === 'win32') {\n command = 'wmic.exe';\n // Order of declared properties does not impact the order of the output\n args = ['process', 'get', 'Name,ParentProcessId,ProcessId'];\n } else {\n command = 'ps';\n // -A: Select all processes\n // -w: Wide format\n // -o: User-defined format\n // Order of declared properties impacts the order of the output. We will\n // need to request the \"comm\" property last in order to ensure that the\n // process names are not truncated on certain platforms\n args = ['-Awo', 'ppid,pid,comm'];\n }\n return { path: command, args };\n}\n\n/**\n * The Executable class provides a safe, portable, recommended solution for tools that need\n * to launch child processes.\n *\n * @remarks\n * The NodeJS child_process API provides a solution for launching child processes, however\n * its design encourages reliance on the operating system shell for certain features.\n * Invoking the OS shell is not safe, not portable, and generally not recommended:\n *\n * - Different shells have different behavior and command-line syntax, and which shell you\n * will get with NodeJS is unpredictable. There is no universal shell guaranteed to be\n * available on all platforms.\n *\n * - If a command parameter contains symbol characters, a shell may interpret them, which\n * can introduce a security vulnerability\n *\n * - Each shell has different rules for escaping these symbols. On Windows, the default\n * shell is incapable of escaping certain character sequences.\n *\n * The Executable API provides a pure JavaScript implementation of primitive shell-like\n * functionality for searching the default PATH, appending default file extensions on Windows,\n * and executing a file that may contain a POSIX shebang. This primitive functionality\n * is sufficient (and recommended) for most tooling scenarios.\n *\n * If you need additional shell features such as wildcard globbing, environment variable\n * expansion, piping, or built-in commands, then we recommend to use the `@microsoft/rushell`\n * library instead. Rushell is a pure JavaScript shell with a standard syntax that is\n * guaranteed to work consistently across all platforms.\n *\n * @public\n */\nexport class Executable {\n /**\n * Synchronously create a child process and optionally capture its output.\n *\n * @remarks\n * This function is similar to child_process.spawnSync(). The main differences are:\n *\n * - It does not invoke the OS shell unless the executable file is a shell script.\n * - Command-line arguments containing special characters are more accurately passed\n * through to the child process.\n * - If the filename is missing a path, then the shell's default PATH will be searched.\n * - If the filename is missing a file extension, then Windows default file extensions\n * will be searched.\n *\n * @param filename - The name of the executable file. This string must not contain any\n * command-line arguments. If the name contains any path delimiters, then the shell's\n * default PATH will not be searched.\n * @param args - The command-line arguments to be passed to the process.\n * @param options - Additional options\n * @returns the same data type as returned by the NodeJS child_process.spawnSync() API\n *\n * @privateRemarks\n *\n * NOTE: The NodeJS spawnSync() returns SpawnSyncReturns<string> or SpawnSyncReturns<Buffer>\n * polymorphically based on the options.encoding parameter value. This is a fairly confusing\n * design. In most cases, developers want string with the default encoding. If/when someone\n * wants binary output or a non-default text encoding, we will introduce a separate API function\n * with a name like \"spawnWithBufferSync\".\n */\n public static spawnSync(\n filename: string,\n args: string[],\n options?: IExecutableSpawnSyncOptions\n ): child_process.SpawnSyncReturns<string> {\n if (!options) {\n options = {};\n }\n\n const context: IExecutableContext = Executable._getExecutableContext(options);\n\n const resolvedPath: string | undefined = Executable._tryResolve(filename, options, context);\n if (!resolvedPath) {\n throw new Error(`The executable file was not found: \"${filename}\"`);\n }\n\n const spawnOptions: child_process.SpawnSyncOptionsWithStringEncoding = {\n cwd: context.currentWorkingDirectory,\n env: context.environmentMap.toObject(),\n input: options.input,\n stdio: options.stdio as child_process.StdioOptions,\n timeout: options.timeoutMs,\n maxBuffer: options.maxBuffer,\n\n // Contrary to what the NodeJS typings imply, we must explicitly specify \"utf8\" here\n // if we want the result to be SpawnSyncReturns<string> instead of SpawnSyncReturns<Buffer>.\n encoding: 'utf8',\n\n // NOTE: This is always false, because Rushell will be recommended instead of relying on the OS shell.\n shell: false\n };\n\n const normalizedCommandLine: ICommandLineOptions = Executable._buildCommandLineFixup(\n resolvedPath,\n args,\n context\n );\n\n return child_process.spawnSync(normalizedCommandLine.path, normalizedCommandLine.args, spawnOptions);\n }\n\n /**\n * Start a child process.\n *\n * @remarks\n * This function is similar to child_process.spawn(). The main differences are:\n *\n * - It does not invoke the OS shell unless the executable file is a shell script.\n * - Command-line arguments containing special characters are more accurately passed\n * through to the child process.\n * - If the filename is missing a path, then the shell's default PATH will be searched.\n * - If the filename is missing a file extension, then Windows default file extensions\n * will be searched.\n *\n * This command is asynchronous, but it does not return a `Promise`. Instead it returns\n * a Node.js `ChildProcess` supporting event notifications.\n *\n * @param filename - The name of the executable file. This string must not contain any\n * command-line arguments. If the name contains any path delimiters, then the shell's\n * default PATH will not be searched.\n * @param args - The command-line arguments to be passed to the process.\n * @param options - Additional options\n * @returns the same data type as returned by the NodeJS child_process.spawnSync() API\n */\n public static spawn(\n filename: string,\n args: string[],\n options?: IExecutableSpawnOptions\n ): child_process.ChildProcess {\n if (!options) {\n options = {};\n }\n\n const context: IExecutableContext = Executable._getExecutableContext(options);\n\n const resolvedPath: string | undefined = Executable._tryResolve(filename, options, context);\n if (!resolvedPath) {\n throw new Error(`The executable file was not found: \"${filename}\"`);\n }\n\n const spawnOptions: child_process.SpawnOptions = {\n cwd: context.currentWorkingDirectory,\n env: context.environmentMap.toObject(),\n stdio: options.stdio as child_process.StdioOptions,\n\n // NOTE: This is always false, because Rushell will be recommended instead of relying on the OS shell.\n shell: false\n };\n\n const normalizedCommandLine: ICommandLineOptions = Executable._buildCommandLineFixup(\n resolvedPath,\n args,\n context\n );\n\n return child_process.spawn(normalizedCommandLine.path, normalizedCommandLine.args, spawnOptions);\n }\n\n /** {@inheritDoc Executable.(waitForExitAsync:3)} */\n public static async waitForExitAsync(\n childProcess: child_process.ChildProcess,\n options: IWaitForExitWithStringOptions\n ): Promise<IWaitForExitResult<string>>;\n\n /** {@inheritDoc Executable.(waitForExitAsync:3)} */\n public static async waitForExitAsync(\n childProcess: child_process.ChildProcess,\n options: IWaitForExitWithBufferOptions\n ): Promise<IWaitForExitResult<Buffer>>;\n\n /**\n * Wait for a child process to exit and return the result.\n *\n * @param childProcess - The child process to wait for.\n * @param options - Options for waiting for the process to exit.\n */\n public static async waitForExitAsync(\n childProcess: child_process.ChildProcess,\n options?: IWaitForExitOptions\n ): Promise<IWaitForExitResult<never>>;\n\n public static async waitForExitAsync<T extends Buffer | string | never = never>(\n childProcess: child_process.ChildProcess,\n options: IWaitForExitOptions = {}\n ): Promise<IWaitForExitResult<T>> {\n const { throwOnNonZeroExitCode, throwOnSignal, encoding } = options;\n if (encoding && (!childProcess.stdout || !childProcess.stderr)) {\n throw new Error(\n 'An encoding was specified, but stdout and/or stderr on the child process are not defined'\n );\n }\n\n const collectedStdout: T[] = [];\n const collectedStderr: T[] = [];\n const useBufferEncoding: boolean = encoding === 'buffer';\n\n function normalizeChunk<TChunk extends Buffer | string>(chunk: Buffer | string): TChunk {\n if (typeof chunk === 'string') {\n return (useBufferEncoding ? Buffer.from(chunk) : chunk) as TChunk;\n } else {\n return (useBufferEncoding ? chunk : chunk.toString(encoding as BufferEncoding)) as TChunk;\n }\n }\n\n type ISignalAndExitCode = Pick<IWaitForExitResult<T>, 'exitCode' | 'signal'>;\n\n let errorThrown: Error | undefined = undefined;\n const { exitCode, signal } = await new Promise<ISignalAndExitCode>(\n (resolve: (result: ISignalAndExitCode) => void, reject: (error: Error) => void) => {\n if (encoding) {\n childProcess.stdout!.on('data', (chunk: Buffer | string) => {\n collectedStdout.push(normalizeChunk(chunk));\n });\n childProcess.stderr!.on('data', (chunk: Buffer | string) => {\n collectedStderr.push(normalizeChunk(chunk));\n });\n }\n childProcess.on('error', (error: Error) => {\n // Wait to call reject() until any output is collected\n errorThrown = error;\n });\n childProcess.on('close', (closeExitCode: number | null, closeSignal: NodeJS.Signals | null) => {\n if (errorThrown) {\n reject(errorThrown);\n }\n if (closeSignal && throwOnSignal) {\n reject(new Error(`Process terminated by ${closeSignal}`));\n } else if (closeExitCode !== 0 && throwOnNonZeroExitCode) {\n reject(new Error(`Process exited with code ${closeExitCode}`));\n } else {\n resolve({ exitCode: closeExitCode, signal: closeSignal });\n }\n });\n }\n );\n\n let stdout: T | undefined;\n let stderr: T | undefined;\n if (encoding === 'buffer') {\n stdout = Buffer.concat(collectedStdout as Buffer[]) as T;\n stderr = Buffer.concat(collectedStderr as Buffer[]) as T;\n } else if (encoding !== undefined) {\n stdout = collectedStdout.join('') as T;\n stderr = collectedStderr.join('') as T;\n }\n\n const result: IWaitForExitResult<T> = {\n stdout: stdout as T,\n stderr: stderr as T,\n exitCode,\n signal\n };\n\n return result;\n }\n\n /**\n * Get the list of processes currently running on the system, keyed by the process ID.\n *\n * @remarks The underlying implementation depends on the operating system:\n * - On Windows, this uses the `wmic.exe` utility.\n * - On Unix, this uses the `ps` utility.\n */\n public static async getProcessInfoByIdAsync(): Promise<Map<number, IProcessInfo>> {\n const { path: command, args } = getProcessListProcessOptions();\n const process: child_process.ChildProcess = Executable.spawn(command, args, {\n stdio: ['ignore', 'pipe', 'ignore']\n });\n if (process.stdout === null) {\n throw new InternalError('Child process did not provide stdout');\n }\n const [processInfoByIdMap] = await Promise.all([\n parseProcessListOutputAsync(process.stdout),\n // Don't collect output in the result since we process it directly\n Executable.waitForExitAsync(process, { throwOnNonZeroExitCode: true, throwOnSignal: true })\n ]);\n return processInfoByIdMap;\n }\n\n /**\n * {@inheritDoc Executable.getProcessInfoByIdAsync}\n */\n public static getProcessInfoById(): Map<number, IProcessInfo> {\n const { path: command, args } = getProcessListProcessOptions();\n const processOutput: child_process.SpawnSyncReturns<string> = Executable.spawnSync(command, args);\n if (processOutput.error) {\n throw new Error(`Unable to list processes: ${command} failed with error ${processOutput.error}`);\n }\n if (processOutput.status !== 0) {\n throw new Error(`Unable to list processes: ${command} exited with code ${processOutput.status}`);\n }\n return parseProcessListOutput(processOutput.output);\n }\n\n /**\n * Get the list of processes currently running on the system, keyed by the process name. All processes\n * with the same name will be grouped.\n *\n * @remarks The underlying implementation depends on the operating system:\n * - On Windows, this uses the `wmic.exe` utility.\n * - On Unix, this uses the `ps` utility.\n */\n public static async getProcessInfoByNameAsync(): Promise<Map<string, IProcessInfo[]>> {\n const processInfoById: Map<number, IProcessInfo> = await Executable.getProcessInfoByIdAsync();\n return convertToProcessInfoByNameMap(processInfoById);\n }\n\n /**\n * {@inheritDoc Executable.getProcessInfoByNameAsync}\n */\n public static getProcessInfoByName(): Map<string, IProcessInfo[]> {\n const processInfoByIdMap: Map<number, IProcessInfo> = Executable.getProcessInfoById();\n return convertToProcessInfoByNameMap(processInfoByIdMap);\n }\n\n // PROBLEM: Given an \"args\" array of strings that may contain special characters (e.g. spaces,\n // backslashes, quotes), ensure that these strings pass through to the child process's ARGV array\n // without anything getting corrupted along the way.\n //\n // On Unix you just pass the array to spawnSync(). But on Windows, this is a very complex problem:\n // - The Win32 CreateProcess() API expects the args to be encoded as a single text string\n // - The decoding of this string is up to the application (not the OS), and there are 3 different\n // algorithms in common usage: the cmd.exe shell, the Microsoft CRT library init code, and\n // the Win32 CommandLineToArgvW()\n // - The encodings are counterintuitive and have lots of special cases\n // - NodeJS spawnSync() tries do the encoding without knowing which decoder will be used\n //\n // See these articles for a full analysis:\n // http://www.windowsinspired.com/understanding-the-command-line-string-and-arguments-received-by-a-windows-program/\n // http://www.windowsinspired.com/how-a-windows-programs-splits-its-command-line-into-individual-arguments/\n private static _buildCommandLineFixup(\n resolvedPath: string,\n args: string[],\n context: IExecutableContext\n ): ICommandLineOptions {\n const fileExtension: string = path.extname(resolvedPath);\n\n if (OS_PLATFORM === 'win32') {\n // Do we need a custom handler for this file type?\n switch (fileExtension.toUpperCase()) {\n case '.EXE':\n case '.COM':\n // okay to execute directly\n break;\n case '.BAT':\n case '.CMD': {\n Executable._validateArgsForWindowsShell(args);\n\n // These file types must be invoked via the Windows shell\n let shellPath: string | undefined = context.environmentMap.get('COMSPEC');\n if (!shellPath || !Executable._canExecute(shellPath, context)) {\n shellPath = Executable.tryResolve('cmd.exe');\n }\n if (!shellPath) {\n throw new Error(\n `Unable to execute \"${path.basename(resolvedPath)}\" ` +\n `because CMD.exe was not found in the PATH`\n );\n }\n\n const shellArgs: string[] = [];\n // /D: Disable execution of AutoRun commands when starting the new shell context\n shellArgs.push('/d');\n // /S: Disable Cmd.exe's parsing of double-quote characters inside the command-line\n shellArgs.push('/s');\n // /C: Execute the following command and then exit immediately\n shellArgs.push('/c');\n\n // If the path contains special charactrers (e.g. spaces), escape them so that\n // they don't get interpreted by the shell\n shellArgs.push(Executable._getEscapedForWindowsShell(resolvedPath));\n shellArgs.push(...args);\n\n return { path: shellPath, args: shellArgs };\n }\n default:\n throw new Error(\n `Cannot execute \"${path.basename(resolvedPath)}\" because the file type is not supported`\n );\n }\n }\n\n return {\n path: resolvedPath,\n args: args\n };\n }\n\n /**\n * Given a filename, this determines the absolute path of the executable file that would\n * be executed by a shell:\n *\n * - If the filename is missing a path, then the shell's default PATH will be searched.\n * - If the filename is missing a file extension, then Windows default file extensions\n * will be searched.\n *\n * @remarks\n *\n * @param filename - The name of the executable file. This string must not contain any\n * command-line arguments. If the name contains any path delimiters, then the shell's\n * default PATH will not be searched.\n * @param options - optional other parameters\n * @returns the absolute path of the executable, or undefined if it was not found\n */\n public static tryResolve(filename: string, options?: IExecutableResolveOptions): string | undefined {\n return Executable._tryResolve(filename, options || {}, Executable._getExecutableContext(options));\n }\n\n private static _tryResolve(\n filename: string,\n options: IExecutableResolveOptions,\n context: IExecutableContext\n ): string | undefined {\n // NOTE: Since \"filename\" cannot contain command-line arguments, the \"/\" here\n // must be interpreted as a path delimiter\n const hasPathSeparators: boolean =\n filename.indexOf('/') >= 0 || (OS_PLATFORM === 'win32' && filename.indexOf('\\\\') >= 0);\n\n // Are there any path separators?\n if (hasPathSeparators) {\n // If so, then don't search the PATH. Just resolve relative to the current working directory\n const resolvedPath: string = path.resolve(context.currentWorkingDirectory, filename);\n return Executable._tryResolveFileExtension(resolvedPath, context);\n } else {\n // Otherwise if it's a bare name, then try everything in the shell PATH\n const pathsToSearch: string[] = Executable._getSearchFolders(context);\n\n for (const pathToSearch of pathsToSearch) {\n const resolvedPath: string = path.join(pathToSearch, filename);\n const result: string | undefined = Executable._tryResolveFileExtension(resolvedPath, context);\n if (result) {\n return result;\n }\n }\n\n // No match was found\n return undefined;\n }\n }\n\n private static _tryResolveFileExtension(\n resolvedPath: string,\n context: IExecutableContext\n ): string | undefined {\n if (Executable._canExecute(resolvedPath, context)) {\n return resolvedPath;\n }\n\n // Try the default file extensions\n for (const shellExtension of context.windowsExecutableExtensions) {\n const resolvedNameWithExtension: string = resolvedPath + shellExtension;\n\n if (Executable._canExecute(resolvedNameWithExtension, context)) {\n return resolvedNameWithExtension;\n }\n }\n\n return undefined;\n }\n\n private static _buildEnvironmentMap(options: IExecutableResolveOptions): EnvironmentMap {\n const environmentMap: EnvironmentMap = new EnvironmentMap();\n if (options.environment !== undefined && options.environmentMap !== undefined) {\n throw new Error(\n 'IExecutableResolveOptions.environment and IExecutableResolveOptions.environmentMap' +\n ' cannot both be specified'\n );\n }\n if (options.environment !== undefined) {\n environmentMap.mergeFromObject(options.environment);\n } else if (options.environmentMap !== undefined) {\n environmentMap.mergeFrom(options.environmentMap);\n } else {\n environmentMap.mergeFromObject(process.env);\n }\n return environmentMap;\n }\n\n /**\n * This is used when searching the shell PATH for an executable, to determine\n * whether a match should be skipped or not. If it returns true, this does not\n * guarantee that the file can be successfully executed.\n */\n private static _canExecute(filePath: string, context: IExecutableContext): boolean {\n if (!FileSystem.exists(filePath)) {\n return false;\n }\n\n if (OS_PLATFORM === 'win32') {\n // NOTE: For Windows, we don't validate that the file extension appears in PATHEXT.\n // That environment variable determines which extensions can be appended if the\n // extension is missing, but it does not affect whether a file may be executed or not.\n // Windows does have a (seldom used) ACL that can be used to deny execution permissions\n // for a file, but NodeJS doesn't expose that API, so we don't bother checking it.\n\n // However, Windows *does* require that the file has some kind of file extension\n if (path.extname(filePath) === '') {\n return false;\n }\n } else {\n // For Unix, check whether any of the POSIX execute bits are set\n try {\n // eslint-disable-next-line no-bitwise\n if ((FileSystem.getPosixModeBits(filePath) & PosixModeBits.AllExecute) === 0) {\n return false; // not executable\n }\n } catch (error) {\n // If we have trouble accessing the file, ignore the error and consider it \"not executable\"\n // since that's what a shell would do\n }\n }\n\n return true;\n }\n\n /**\n * Returns the list of folders where we will search for an executable,\n * based on the PATH environment variable.\n */\n private static _getSearchFolders(context: IExecutableContext): string[] {\n const pathList: string = context.environmentMap.get('PATH') || '';\n\n const folders: string[] = [];\n\n // Avoid processing duplicates\n const seenPaths: Set<string> = new Set<string>();\n\n // NOTE: Cmd.exe on Windows always searches the current working directory first.\n // PowerShell and Unix shells do NOT do that, because it's a security concern.\n // We follow their behavior.\n\n for (const splitPath of pathList.split(path.delimiter)) {\n const trimmedPath: string = splitPath.trim();\n if (trimmedPath !== '') {\n if (!seenPaths.has(trimmedPath)) {\n // Fun fact: If you put relative paths in your PATH environment variable,\n // all shells will dynamically match them against the current working directory.\n // This is a terrible design, and in practice nobody does that, but it is supported...\n // so we allow it here.\n const resolvedPath: string = path.resolve(context.currentWorkingDirectory, trimmedPath);\n\n if (!seenPaths.has(resolvedPath)) {\n if (FileSystem.exists(resolvedPath)) {\n folders.push(resolvedPath);\n }\n\n seenPaths.add(resolvedPath);\n }\n\n seenPaths.add(trimmedPath);\n }\n }\n }\n\n return folders;\n }\n\n private static _getExecutableContext(options: IExecutableResolveOptions | undefined): IExecutableContext {\n if (!options) {\n options = {};\n }\n\n const environment: EnvironmentMap = Executable._buildEnvironmentMap(options);\n\n let currentWorkingDirectory: string;\n if (options.currentWorkingDirectory) {\n currentWorkingDirectory = path.resolve(options.currentWorkingDirectory);\n } else {\n currentWorkingDirectory = process.cwd();\n }\n\n const windowsExecutableExtensions: string[] = [];\n\n if (OS_PLATFORM === 'win32') {\n const pathExtVariable: string = environment.get('PATHEXT') || '';\n for (const splitValue of pathExtVariable.split(';')) {\n const trimmed: string = splitValue.trim().toLowerCase();\n // Ignore malformed extensions\n if (/^\\.[a-z0-9\\.]*[a-z0-9]$/i.test(trimmed)) {\n // Don't add the same extension twice\n if (windowsExecutableExtensions.indexOf(trimmed) < 0) {\n windowsExecutableExtensions.push(trimmed);\n }\n }\n }\n }\n\n return {\n environmentMap: environment,\n currentWorkingDirectory,\n windowsExecutableExtensions\n };\n }\n\n /**\n * Given an input string containing special symbol characters, this inserts the \"^\" escape\n * character to ensure the symbols are interpreted literally by the Windows shell.\n */\n private static _getEscapedForWindowsShell(text: string): string {\n const escapableCharRegExp: RegExp = /[%\\^&|<> ]/g;\n return text.replace(escapableCharRegExp, (value) => '^' + value);\n }\n\n /**\n * Checks for characters that are unsafe to pass to a Windows batch file\n * due to the way that cmd.exe implements escaping.\n */\n private static _validateArgsForWindowsShell(args: string[]): void {\n const specialCharRegExp: RegExp = /[%\\^&|<>\\r\\n]/g;\n\n for (const arg of args) {\n const match: RegExpMatchArray | null = arg.match(specialCharRegExp);\n if (match) {\n // NOTE: It is possible to escape some of these characters by prefixing them\n // with a caret (^), which allows these characters to be successfully passed\n // through to the batch file %1 variables. But they will be expanded again\n // whenever they are used. For example, NPM's binary wrapper batch files\n // use \"%*\" to pass their arguments to Node.exe, which causes them to be expanded\n // again. Unfortunately the Cmd.exe batch language provides native escaping\n // function (that could be used to insert the carets again).\n //\n // We could work around that by adding double carets, but in general there\n // is no way to predict how many times the variable will get expanded.\n // Thus, there is no generally reliable way to pass these characters.\n throw new Error(\n `The command line argument ${JSON.stringify(arg)} contains a` +\n ` special character ${JSON.stringify(match[0])} that cannot be escaped for the Windows shell`\n );\n }\n }\n }\n}\n"]} | ||
| {"version":3,"file":"Executable.js","sourceRoot":"","sources":["../src/Executable.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8O3D,kEAcC;AAED,wDAeC;AA3QD,4CAA8B;AAC9B,kEAAoD;AACpD,gDAAkC;AAElC,qDAAkD;AAClD,6CAA0C;AAC1C,mDAAgD;AAChD,iCAA8B;AAC9B,mDAAgD;AAEhD,MAAM,WAAW,GAAoB,EAAE,CAAC,QAAQ,EAAE,CAAC;AAkO5C,KAAK,UAAU,2BAA2B,CAC/C,MAA6B,EAC7B,WAA4B,WAAW;IAEvC,MAAM,eAAe,GAA8B,IAAI,GAAG,EAAwB,CAAC;IACnF,IAAI,WAAW,GAAY,KAAK,CAAC;IACjC,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,WAAI,CAAC,0BAA0B,CAAC,MAAM,EAAE,EAAE,gBAAgB,EA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,GAAW,gBAAgB,CAAC;QAEnD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,KAAK,GAA4B,GAAG,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;YACpE,IAAI,KAAK,EAAE,CAAC;gBACV,4EAA4E;gBAC5E,4EAA4E;gBAC5E,2EAA2E;gBAC3E,yEAAyE;gBACzE,iFAAiF;gBACjF,4EAA4E;gBAC5E,4DAA4D;gBAC5D,EAAE;gBACF,0EAA0E;gBAC1E,sEAAsE;gBACtE,qEAAqE;gBACrE,MAAM,IAAI,KAAK,CACb,6BAA6B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa;oBAC3D,sBAAsB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,+CAA+C,CAChG,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAxlBD,gCAwlBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'node:os';\nimport * as child_process from 'node:child_process';\nimport * as path from 'node:path';\n\nimport { EnvironmentMap } from './EnvironmentMap';\nimport { FileSystem } from './FileSystem';\nimport { PosixModeBits } from './PosixModeBits';\nimport { Text } from './Text';\nimport { InternalError } from './InternalError';\n\nconst OS_PLATFORM: NodeJS.Platform = os.platform();\n\n/**\n * Typings for one of the streams inside IExecutableSpawnSyncOptions.stdio.\n * @public\n */\nexport type ExecutableStdioStreamMapping =\n | 'pipe'\n | 'ignore'\n | 'inherit'\n | NodeJS.WritableStream\n | NodeJS.ReadableStream\n | number\n | undefined;\n\n/**\n * Types for {@link IExecutableSpawnSyncOptions.stdio}\n * and {@link IExecutableSpawnOptions.stdio}\n * @public\n */\nexport type ExecutableStdioMapping = 'pipe' | 'ignore' | 'inherit' | ExecutableStdioStreamMapping[];\n\n/**\n * Options for Executable.tryResolve().\n * @public\n */\nexport interface IExecutableResolveOptions {\n /**\n * The current working directory. If omitted, process.cwd() will be used.\n */\n currentWorkingDirectory?: string;\n\n /**\n * The environment variables for the child process.\n *\n * @remarks\n * If `environment` and `environmentMap` are both omitted, then `process.env` will be used.\n * If `environment` and `environmentMap` cannot both be specified.\n */\n environment?: NodeJS.ProcessEnv;\n\n /**\n * The environment variables for the child process.\n *\n * @remarks\n * If `environment` and `environmentMap` are both omitted, then `process.env` will be used.\n * If `environment` and `environmentMap` cannot both be specified.\n */\n environmentMap?: EnvironmentMap;\n}\n\n/**\n * Options for {@link Executable.spawnSync}\n * @public\n */\nexport interface IExecutableSpawnSyncOptions extends IExecutableResolveOptions {\n /**\n * The content to be passed to the child process's stdin.\n *\n * NOTE: If specified, this content replaces any IExecutableSpawnSyncOptions.stdio[0]\n * mapping for stdin.\n */\n input?: string;\n\n /**\n * The stdio mappings for the child process.\n *\n * NOTE: If IExecutableSpawnSyncOptions.input is provided, it will take precedence\n * over the stdin mapping (stdio[0]).\n */\n stdio?: ExecutableStdioMapping;\n\n /**\n * The maximum time the process is allowed to run before it will be terminated.\n */\n timeoutMs?: number;\n\n /**\n * The largest amount of bytes allowed on stdout or stderr for this synchronous operation.\n * If exceeded, the child process will be terminated. The default is 200 * 1024.\n */\n maxBuffer?: number;\n}\n\n/**\n * Options for {@link Executable.spawn}\n * @public\n */\nexport interface IExecutableSpawnOptions extends IExecutableResolveOptions {\n /**\n * The stdio mappings for the child process.\n *\n * NOTE: If IExecutableSpawnSyncOptions.input is provided, it will take precedence\n * over the stdin mapping (stdio[0]).\n */\n stdio?: ExecutableStdioMapping;\n}\n\n/**\n * The options for running a process to completion using {@link Executable.(waitForExitAsync:3)}.\n *\n * @public\n */\nexport interface IWaitForExitOptions {\n /**\n * Whether or not to throw when the process completes with a non-zero exit code. Defaults to false.\n *\n * @defaultValue false\n */\n throwOnNonZeroExitCode?: boolean;\n\n /**\n * Whether or not to throw when the process is terminated by a signal. Defaults to false.\n *\n * @defaultValue false\n */\n throwOnSignal?: boolean;\n\n /**\n * The encoding of the output. If not provided, the output will not be collected.\n */\n encoding?: BufferEncoding | 'buffer';\n}\n\n/**\n * {@inheritDoc IWaitForExitOptions}\n *\n * @public\n */\nexport interface IWaitForExitWithStringOptions extends IWaitForExitOptions {\n /**\n * {@inheritDoc IWaitForExitOptions.encoding}\n */\n encoding: BufferEncoding;\n}\n\n/**\n * {@inheritDoc IWaitForExitOptions}\n *\n * @public\n */\nexport interface IWaitForExitWithBufferOptions extends IWaitForExitOptions {\n /**\n * {@inheritDoc IWaitForExitOptions.encoding}\n */\n encoding: 'buffer';\n}\n\n/**\n * The result of running a process to completion using {@link Executable.(waitForExitAsync:3)}.\n *\n * @public\n */\nexport interface IWaitForExitResult<T extends Buffer | string | never = never> {\n /**\n * The process stdout output, if encoding was specified.\n */\n stdout: T;\n\n /**\n * The process stderr output, if encoding was specified.\n */\n stderr: T;\n\n /**\n * The process exit code. If the process was terminated, this will be null.\n */\n // eslint-disable-next-line @rushstack/no-new-null\n exitCode: number | null;\n\n /**\n * The process signal that terminated the process. If the process exited normally, this will be null.\n */\n // eslint-disable-next-line @rushstack/no-new-null\n signal: string | null;\n}\n\n// Common environmental state used by Executable members\ninterface IExecutableContext {\n currentWorkingDirectory: string;\n environmentMap: EnvironmentMap;\n // For Windows, the parsed PATHEXT environment variable\n windowsExecutableExtensions: string[];\n}\n\ninterface ICommandLineOptions {\n path: string;\n args: string[];\n}\n\n/**\n * Process information sourced from the system. This process info is sourced differently depending\n * on the operating system:\n * - On Windows, this uses the `wmic.exe` utility.\n * - On Unix, this uses the `ps` utility.\n *\n * @public\n */\nexport interface IProcessInfo {\n /**\n * The name of the process.\n *\n * @remarks On Windows, the process name will be empty if the process is a kernel process.\n * On Unix, the process name will be empty if the process is the root process.\n */\n processName: string;\n\n /**\n * The process ID.\n */\n processId: number;\n\n /**\n * The parent process info.\n *\n * @remarks On Windows, the parent process info will be undefined if the process is a kernel process.\n * On Unix, the parent process info will be undefined if the process is the root process.\n */\n parentProcessInfo: IProcessInfo | undefined;\n\n /**\n * The child process infos.\n */\n childProcessInfos: IProcessInfo[];\n}\n\nexport async function parseProcessListOutputAsync(\n stream: NodeJS.ReadableStream,\n platform: NodeJS.Platform = OS_PLATFORM\n): Promise<Map<number, IProcessInfo>> {\n const processInfoById: Map<number, IProcessInfo> = new Map<number, IProcessInfo>();\n let seenHeaders: boolean = false;\n for await (const line of Text.readLinesFromIterableAsync(stream, { ignoreEmptyLines: true })) {\n if (!seenHeaders) {\n seenHeaders = true;\n } else {\n parseProcessInfoEntry(line, processInfoById, platform);\n }\n }\n return processInfoById;\n}\n\nexport function parseProcessListOutput(\n // eslint-disable-next-line @rushstack/no-new-null\n output: Iterable<string | null>,\n platform: NodeJS.Platform = OS_PLATFORM\n): Map<number, IProcessInfo> {\n const processInfoById: Map<number, IProcessInfo> = new Map<number, IProcessInfo>();\n let seenHeaders: boolean = false;\n for (const line of Text.readLinesFromIterable(output, { ignoreEmptyLines: true })) {\n if (!seenHeaders) {\n seenHeaders = true;\n } else {\n parseProcessInfoEntry(line, processInfoById, platform);\n }\n }\n return processInfoById;\n}\n\n// win32 format:\n// Name ParentProcessId ProcessId\n// process name 1234 5678\n// unix format:\n// PPID PID COMMAND\n// 51234 56784 process name\nconst NAME_GROUP: 'name' = 'name';\nconst PROCESS_ID_GROUP: 'pid' = 'pid';\nconst PARENT_PROCESS_ID_GROUP: 'ppid' = 'ppid';\nconst PROCESS_LIST_ENTRY_REGEX_WIN32: RegExp = new RegExp(\n `^(?<${NAME_GROUP}>.+?)\\\\s+(?<${PARENT_PROCESS_ID_GROUP}>\\\\d+)\\\\s+(?<${PROCESS_ID_GROUP}>\\\\d+)\\\\s*$`\n);\nconst PROCESS_LIST_ENTRY_REGEX_UNIX: RegExp = new RegExp(\n `^\\\\s*(?<${PARENT_PROCESS_ID_GROUP}>\\\\d+)\\\\s+(?<${PROCESS_ID_GROUP}>\\\\d+)\\\\s+(?<${NAME_GROUP}>.+?)\\\\s*$`\n);\n\nfunction parseProcessInfoEntry(\n line: string,\n existingProcessInfoById: Map<number, IProcessInfo>,\n platform: NodeJS.Platform\n): void {\n const processListEntryRegex: RegExp =\n platform === 'win32' ? PROCESS_LIST_ENTRY_REGEX_WIN32 : PROCESS_LIST_ENTRY_REGEX_UNIX;\n const match: RegExpMatchArray | null = line.match(processListEntryRegex);\n if (!match?.groups) {\n throw new InternalError(`Invalid process list entry: ${line}`);\n }\n\n const processName: string = match.groups[NAME_GROUP];\n const processId: number = parseInt(match.groups[PROCESS_ID_GROUP], 10);\n const parentProcessId: number = parseInt(match.groups[PARENT_PROCESS_ID_GROUP], 10);\n\n // Only care about the parent process if it is not the same as the current process.\n let parentProcessInfo: IProcessInfo | undefined;\n if (parentProcessId !== processId) {\n parentProcessInfo = existingProcessInfoById.get(parentProcessId);\n if (!parentProcessInfo) {\n // Create a new placeholder entry for the parent with the information we have so far\n parentProcessInfo = {\n processName: '',\n processId: parentProcessId,\n parentProcessInfo: undefined,\n childProcessInfos: []\n };\n existingProcessInfoById.set(parentProcessId, parentProcessInfo);\n }\n }\n\n let processInfo: IProcessInfo | undefined = existingProcessInfoById.get(processId);\n if (!processInfo) {\n // Create a new entry\n processInfo = {\n processName,\n processId,\n parentProcessInfo,\n childProcessInfos: []\n };\n existingProcessInfoById.set(processId, processInfo);\n } else {\n // Update placeholder entry\n processInfo.processName = processName;\n processInfo.parentProcessInfo = parentProcessInfo;\n }\n\n // Add the process as a child of the parent process\n parentProcessInfo?.childProcessInfos.push(processInfo);\n}\n\nfunction convertToProcessInfoByNameMap(\n processInfoById: Map<number, IProcessInfo>\n): Map<string, IProcessInfo[]> {\n const processInfoByNameMap: Map<string, IProcessInfo[]> = new Map<string, IProcessInfo[]>();\n for (const processInfo of processInfoById.values()) {\n let processInfoNameEntries: IProcessInfo[] | undefined = processInfoByNameMap.get(\n processInfo.processName\n );\n if (!processInfoNameEntries) {\n processInfoNameEntries = [];\n processInfoByNameMap.set(processInfo.processName, processInfoNameEntries);\n }\n processInfoNameEntries.push(processInfo);\n }\n return processInfoByNameMap;\n}\n\nfunction getProcessListProcessOptions(): ICommandLineOptions {\n let command: string;\n let args: string[];\n if (OS_PLATFORM === 'win32') {\n command = 'wmic.exe';\n // Order of declared properties does not impact the order of the output\n args = ['process', 'get', 'Name,ParentProcessId,ProcessId'];\n } else {\n command = 'ps';\n // -A: Select all processes\n // -w: Wide format\n // -o: User-defined format\n // Order of declared properties impacts the order of the output. We will\n // need to request the \"comm\" property last in order to ensure that the\n // process names are not truncated on certain platforms\n args = ['-Awo', 'ppid,pid,comm'];\n }\n return { path: command, args };\n}\n\n/**\n * The Executable class provides a safe, portable, recommended solution for tools that need\n * to launch child processes.\n *\n * @remarks\n * The NodeJS child_process API provides a solution for launching child processes, however\n * its design encourages reliance on the operating system shell for certain features.\n * Invoking the OS shell is not safe, not portable, and generally not recommended:\n *\n * - Different shells have different behavior and command-line syntax, and which shell you\n * will get with NodeJS is unpredictable. There is no universal shell guaranteed to be\n * available on all platforms.\n *\n * - If a command parameter contains symbol characters, a shell may interpret them, which\n * can introduce a security vulnerability\n *\n * - Each shell has different rules for escaping these symbols. On Windows, the default\n * shell is incapable of escaping certain character sequences.\n *\n * The Executable API provides a pure JavaScript implementation of primitive shell-like\n * functionality for searching the default PATH, appending default file extensions on Windows,\n * and executing a file that may contain a POSIX shebang. This primitive functionality\n * is sufficient (and recommended) for most tooling scenarios.\n *\n * If you need additional shell features such as wildcard globbing, environment variable\n * expansion, piping, or built-in commands, then we recommend to use the `@microsoft/rushell`\n * library instead. Rushell is a pure JavaScript shell with a standard syntax that is\n * guaranteed to work consistently across all platforms.\n *\n * @public\n */\nexport class Executable {\n /**\n * Synchronously create a child process and optionally capture its output.\n *\n * @remarks\n * This function is similar to child_process.spawnSync(). The main differences are:\n *\n * - It does not invoke the OS shell unless the executable file is a shell script.\n * - Command-line arguments containing special characters are more accurately passed\n * through to the child process.\n * - If the filename is missing a path, then the shell's default PATH will be searched.\n * - If the filename is missing a file extension, then Windows default file extensions\n * will be searched.\n *\n * @param filename - The name of the executable file. This string must not contain any\n * command-line arguments. If the name contains any path delimiters, then the shell's\n * default PATH will not be searched.\n * @param args - The command-line arguments to be passed to the process.\n * @param options - Additional options\n * @returns the same data type as returned by the NodeJS child_process.spawnSync() API\n *\n * @privateRemarks\n *\n * NOTE: The NodeJS spawnSync() returns SpawnSyncReturns<string> or SpawnSyncReturns<Buffer>\n * polymorphically based on the options.encoding parameter value. This is a fairly confusing\n * design. In most cases, developers want string with the default encoding. If/when someone\n * wants binary output or a non-default text encoding, we will introduce a separate API function\n * with a name like \"spawnWithBufferSync\".\n */\n public static spawnSync(\n filename: string,\n args: string[],\n options?: IExecutableSpawnSyncOptions\n ): child_process.SpawnSyncReturns<string> {\n if (!options) {\n options = {};\n }\n\n const context: IExecutableContext = Executable._getExecutableContext(options);\n\n const resolvedPath: string | undefined = Executable._tryResolve(filename, options, context);\n if (!resolvedPath) {\n throw new Error(`The executable file was not found: \"${filename}\"`);\n }\n\n const spawnOptions: child_process.SpawnSyncOptionsWithStringEncoding = {\n cwd: context.currentWorkingDirectory,\n env: context.environmentMap.toObject(),\n input: options.input,\n stdio: options.stdio as child_process.StdioOptions,\n timeout: options.timeoutMs,\n maxBuffer: options.maxBuffer,\n\n // Contrary to what the NodeJS typings imply, we must explicitly specify \"utf8\" here\n // if we want the result to be SpawnSyncReturns<string> instead of SpawnSyncReturns<Buffer>.\n encoding: 'utf8',\n\n // NOTE: This is always false, because Rushell will be recommended instead of relying on the OS shell.\n shell: false\n };\n\n const normalizedCommandLine: ICommandLineOptions = Executable._buildCommandLineFixup(\n resolvedPath,\n args,\n context\n );\n\n return child_process.spawnSync(normalizedCommandLine.path, normalizedCommandLine.args, spawnOptions);\n }\n\n /**\n * Start a child process.\n *\n * @remarks\n * This function is similar to child_process.spawn(). The main differences are:\n *\n * - It does not invoke the OS shell unless the executable file is a shell script.\n * - Command-line arguments containing special characters are more accurately passed\n * through to the child process.\n * - If the filename is missing a path, then the shell's default PATH will be searched.\n * - If the filename is missing a file extension, then Windows default file extensions\n * will be searched.\n *\n * This command is asynchronous, but it does not return a `Promise`. Instead it returns\n * a Node.js `ChildProcess` supporting event notifications.\n *\n * @param filename - The name of the executable file. This string must not contain any\n * command-line arguments. If the name contains any path delimiters, then the shell's\n * default PATH will not be searched.\n * @param args - The command-line arguments to be passed to the process.\n * @param options - Additional options\n * @returns the same data type as returned by the NodeJS child_process.spawnSync() API\n */\n public static spawn(\n filename: string,\n args: string[],\n options?: IExecutableSpawnOptions\n ): child_process.ChildProcess {\n if (!options) {\n options = {};\n }\n\n const context: IExecutableContext = Executable._getExecutableContext(options);\n\n const resolvedPath: string | undefined = Executable._tryResolve(filename, options, context);\n if (!resolvedPath) {\n throw new Error(`The executable file was not found: \"${filename}\"`);\n }\n\n const spawnOptions: child_process.SpawnOptions = {\n cwd: context.currentWorkingDirectory,\n env: context.environmentMap.toObject(),\n stdio: options.stdio as child_process.StdioOptions,\n\n // NOTE: This is always false, because Rushell will be recommended instead of relying on the OS shell.\n shell: false\n };\n\n const normalizedCommandLine: ICommandLineOptions = Executable._buildCommandLineFixup(\n resolvedPath,\n args,\n context\n );\n\n return child_process.spawn(normalizedCommandLine.path, normalizedCommandLine.args, spawnOptions);\n }\n\n /** {@inheritDoc Executable.(waitForExitAsync:3)} */\n public static async waitForExitAsync(\n childProcess: child_process.ChildProcess,\n options: IWaitForExitWithStringOptions\n ): Promise<IWaitForExitResult<string>>;\n\n /** {@inheritDoc Executable.(waitForExitAsync:3)} */\n public static async waitForExitAsync(\n childProcess: child_process.ChildProcess,\n options: IWaitForExitWithBufferOptions\n ): Promise<IWaitForExitResult<Buffer>>;\n\n /**\n * Wait for a child process to exit and return the result.\n *\n * @param childProcess - The child process to wait for.\n * @param options - Options for waiting for the process to exit.\n */\n public static async waitForExitAsync(\n childProcess: child_process.ChildProcess,\n options?: IWaitForExitOptions\n ): Promise<IWaitForExitResult<never>>;\n\n public static async waitForExitAsync<T extends Buffer | string | never = never>(\n childProcess: child_process.ChildProcess,\n options: IWaitForExitOptions = {}\n ): Promise<IWaitForExitResult<T>> {\n const { throwOnNonZeroExitCode, throwOnSignal, encoding } = options;\n if (encoding && (!childProcess.stdout || !childProcess.stderr)) {\n throw new Error(\n 'An encoding was specified, but stdout and/or stderr on the child process are not defined'\n );\n }\n\n const collectedStdout: T[] = [];\n const collectedStderr: T[] = [];\n const useBufferEncoding: boolean = encoding === 'buffer';\n\n function normalizeChunk<TChunk extends Buffer | string>(chunk: Buffer | string): TChunk {\n if (typeof chunk === 'string') {\n return (useBufferEncoding ? Buffer.from(chunk) : chunk) as TChunk;\n } else {\n return (useBufferEncoding ? chunk : chunk.toString(encoding as BufferEncoding)) as TChunk;\n }\n }\n\n type ISignalAndExitCode = Pick<IWaitForExitResult<T>, 'exitCode' | 'signal'>;\n\n let errorThrown: Error | undefined = undefined;\n const { exitCode, signal } = await new Promise<ISignalAndExitCode>(\n (resolve: (result: ISignalAndExitCode) => void, reject: (error: Error) => void) => {\n if (encoding) {\n childProcess.stdout!.on('data', (chunk: Buffer | string) => {\n collectedStdout.push(normalizeChunk(chunk));\n });\n childProcess.stderr!.on('data', (chunk: Buffer | string) => {\n collectedStderr.push(normalizeChunk(chunk));\n });\n }\n childProcess.on('error', (error: Error) => {\n // Wait to call reject() until any output is collected\n errorThrown = error;\n });\n childProcess.on('close', (closeExitCode: number | null, closeSignal: NodeJS.Signals | null) => {\n if (errorThrown) {\n reject(errorThrown);\n }\n if (closeSignal && throwOnSignal) {\n reject(new Error(`Process terminated by ${closeSignal}`));\n } else if (closeExitCode !== 0 && throwOnNonZeroExitCode) {\n reject(new Error(`Process exited with code ${closeExitCode}`));\n } else {\n resolve({ exitCode: closeExitCode, signal: closeSignal });\n }\n });\n }\n );\n\n let stdout: T | undefined;\n let stderr: T | undefined;\n if (encoding === 'buffer') {\n stdout = Buffer.concat(collectedStdout as Buffer[]) as T;\n stderr = Buffer.concat(collectedStderr as Buffer[]) as T;\n } else if (encoding !== undefined) {\n stdout = collectedStdout.join('') as T;\n stderr = collectedStderr.join('') as T;\n }\n\n const result: IWaitForExitResult<T> = {\n stdout: stdout as T,\n stderr: stderr as T,\n exitCode,\n signal\n };\n\n return result;\n }\n\n /**\n * Get the list of processes currently running on the system, keyed by the process ID.\n *\n * @remarks The underlying implementation depends on the operating system:\n * - On Windows, this uses the `wmic.exe` utility.\n * - On Unix, this uses the `ps` utility.\n */\n public static async getProcessInfoByIdAsync(): Promise<Map<number, IProcessInfo>> {\n const { path: command, args } = getProcessListProcessOptions();\n const process: child_process.ChildProcess = Executable.spawn(command, args, {\n stdio: ['ignore', 'pipe', 'ignore']\n });\n if (process.stdout === null) {\n throw new InternalError('Child process did not provide stdout');\n }\n const [processInfoByIdMap] = await Promise.all([\n parseProcessListOutputAsync(process.stdout),\n // Don't collect output in the result since we process it directly\n Executable.waitForExitAsync(process, { throwOnNonZeroExitCode: true, throwOnSignal: true })\n ]);\n return processInfoByIdMap;\n }\n\n /**\n * {@inheritDoc Executable.getProcessInfoByIdAsync}\n */\n public static getProcessInfoById(): Map<number, IProcessInfo> {\n const { path: command, args } = getProcessListProcessOptions();\n const processOutput: child_process.SpawnSyncReturns<string> = Executable.spawnSync(command, args);\n if (processOutput.error) {\n throw new Error(`Unable to list processes: ${command} failed with error ${processOutput.error}`);\n }\n if (processOutput.status !== 0) {\n throw new Error(`Unable to list processes: ${command} exited with code ${processOutput.status}`);\n }\n return parseProcessListOutput(processOutput.output);\n }\n\n /**\n * Get the list of processes currently running on the system, keyed by the process name. All processes\n * with the same name will be grouped.\n *\n * @remarks The underlying implementation depends on the operating system:\n * - On Windows, this uses the `wmic.exe` utility.\n * - On Unix, this uses the `ps` utility.\n */\n public static async getProcessInfoByNameAsync(): Promise<Map<string, IProcessInfo[]>> {\n const processInfoById: Map<number, IProcessInfo> = await Executable.getProcessInfoByIdAsync();\n return convertToProcessInfoByNameMap(processInfoById);\n }\n\n /**\n * {@inheritDoc Executable.getProcessInfoByNameAsync}\n */\n public static getProcessInfoByName(): Map<string, IProcessInfo[]> {\n const processInfoByIdMap: Map<number, IProcessInfo> = Executable.getProcessInfoById();\n return convertToProcessInfoByNameMap(processInfoByIdMap);\n }\n\n // PROBLEM: Given an \"args\" array of strings that may contain special characters (e.g. spaces,\n // backslashes, quotes), ensure that these strings pass through to the child process's ARGV array\n // without anything getting corrupted along the way.\n //\n // On Unix you just pass the array to spawnSync(). But on Windows, this is a very complex problem:\n // - The Win32 CreateProcess() API expects the args to be encoded as a single text string\n // - The decoding of this string is up to the application (not the OS), and there are 3 different\n // algorithms in common usage: the cmd.exe shell, the Microsoft CRT library init code, and\n // the Win32 CommandLineToArgvW()\n // - The encodings are counterintuitive and have lots of special cases\n // - NodeJS spawnSync() tries do the encoding without knowing which decoder will be used\n //\n // See these articles for a full analysis:\n // http://www.windowsinspired.com/understanding-the-command-line-string-and-arguments-received-by-a-windows-program/\n // http://www.windowsinspired.com/how-a-windows-programs-splits-its-command-line-into-individual-arguments/\n private static _buildCommandLineFixup(\n resolvedPath: string,\n args: string[],\n context: IExecutableContext\n ): ICommandLineOptions {\n const fileExtension: string = path.extname(resolvedPath);\n\n if (OS_PLATFORM === 'win32') {\n // Do we need a custom handler for this file type?\n switch (fileExtension.toUpperCase()) {\n case '.EXE':\n case '.COM':\n // okay to execute directly\n break;\n case '.BAT':\n case '.CMD': {\n Executable._validateArgsForWindowsShell(args);\n\n // These file types must be invoked via the Windows shell\n let shellPath: string | undefined = context.environmentMap.get('COMSPEC');\n if (!shellPath || !Executable._canExecute(shellPath, context)) {\n shellPath = Executable.tryResolve('cmd.exe');\n }\n if (!shellPath) {\n throw new Error(\n `Unable to execute \"${path.basename(resolvedPath)}\" ` +\n `because CMD.exe was not found in the PATH`\n );\n }\n\n const shellArgs: string[] = [];\n // /D: Disable execution of AutoRun commands when starting the new shell context\n shellArgs.push('/d');\n // /S: Disable Cmd.exe's parsing of double-quote characters inside the command-line\n shellArgs.push('/s');\n // /C: Execute the following command and then exit immediately\n shellArgs.push('/c');\n\n // If the path contains special charactrers (e.g. spaces), escape them so that\n // they don't get interpreted by the shell\n shellArgs.push(Executable._getEscapedForWindowsShell(resolvedPath));\n shellArgs.push(...args);\n\n return { path: shellPath, args: shellArgs };\n }\n default:\n throw new Error(\n `Cannot execute \"${path.basename(resolvedPath)}\" because the file type is not supported`\n );\n }\n }\n\n return {\n path: resolvedPath,\n args: args\n };\n }\n\n /**\n * Given a filename, this determines the absolute path of the executable file that would\n * be executed by a shell:\n *\n * - If the filename is missing a path, then the shell's default PATH will be searched.\n * - If the filename is missing a file extension, then Windows default file extensions\n * will be searched.\n *\n * @remarks\n *\n * @param filename - The name of the executable file. This string must not contain any\n * command-line arguments. If the name contains any path delimiters, then the shell's\n * default PATH will not be searched.\n * @param options - optional other parameters\n * @returns the absolute path of the executable, or undefined if it was not found\n */\n public static tryResolve(filename: string, options?: IExecutableResolveOptions): string | undefined {\n return Executable._tryResolve(filename, options || {}, Executable._getExecutableContext(options));\n }\n\n private static _tryResolve(\n filename: string,\n options: IExecutableResolveOptions,\n context: IExecutableContext\n ): string | undefined {\n // NOTE: Since \"filename\" cannot contain command-line arguments, the \"/\" here\n // must be interpreted as a path delimiter\n const hasPathSeparators: boolean =\n filename.indexOf('/') >= 0 || (OS_PLATFORM === 'win32' && filename.indexOf('\\\\') >= 0);\n\n // Are there any path separators?\n if (hasPathSeparators) {\n // If so, then don't search the PATH. Just resolve relative to the current working directory\n const resolvedPath: string = path.resolve(context.currentWorkingDirectory, filename);\n return Executable._tryResolveFileExtension(resolvedPath, context);\n } else {\n // Otherwise if it's a bare name, then try everything in the shell PATH\n const pathsToSearch: string[] = Executable._getSearchFolders(context);\n\n for (const pathToSearch of pathsToSearch) {\n const resolvedPath: string = path.join(pathToSearch, filename);\n const result: string | undefined = Executable._tryResolveFileExtension(resolvedPath, context);\n if (result) {\n return result;\n }\n }\n\n // No match was found\n return undefined;\n }\n }\n\n private static _tryResolveFileExtension(\n resolvedPath: string,\n context: IExecutableContext\n ): string | undefined {\n if (Executable._canExecute(resolvedPath, context)) {\n return resolvedPath;\n }\n\n // Try the default file extensions\n for (const shellExtension of context.windowsExecutableExtensions) {\n const resolvedNameWithExtension: string = resolvedPath + shellExtension;\n\n if (Executable._canExecute(resolvedNameWithExtension, context)) {\n return resolvedNameWithExtension;\n }\n }\n\n return undefined;\n }\n\n private static _buildEnvironmentMap(options: IExecutableResolveOptions): EnvironmentMap {\n const environmentMap: EnvironmentMap = new EnvironmentMap();\n if (options.environment !== undefined && options.environmentMap !== undefined) {\n throw new Error(\n 'IExecutableResolveOptions.environment and IExecutableResolveOptions.environmentMap' +\n ' cannot both be specified'\n );\n }\n if (options.environment !== undefined) {\n environmentMap.mergeFromObject(options.environment);\n } else if (options.environmentMap !== undefined) {\n environmentMap.mergeFrom(options.environmentMap);\n } else {\n environmentMap.mergeFromObject(process.env);\n }\n return environmentMap;\n }\n\n /**\n * This is used when searching the shell PATH for an executable, to determine\n * whether a match should be skipped or not. If it returns true, this does not\n * guarantee that the file can be successfully executed.\n */\n private static _canExecute(filePath: string, context: IExecutableContext): boolean {\n if (!FileSystem.exists(filePath)) {\n return false;\n }\n\n if (OS_PLATFORM === 'win32') {\n // NOTE: For Windows, we don't validate that the file extension appears in PATHEXT.\n // That environment variable determines which extensions can be appended if the\n // extension is missing, but it does not affect whether a file may be executed or not.\n // Windows does have a (seldom used) ACL that can be used to deny execution permissions\n // for a file, but NodeJS doesn't expose that API, so we don't bother checking it.\n\n // However, Windows *does* require that the file has some kind of file extension\n if (path.extname(filePath) === '') {\n return false;\n }\n } else {\n // For Unix, check whether any of the POSIX execute bits are set\n try {\n // eslint-disable-next-line no-bitwise\n if ((FileSystem.getPosixModeBits(filePath) & PosixModeBits.AllExecute) === 0) {\n return false; // not executable\n }\n } catch (error) {\n // If we have trouble accessing the file, ignore the error and consider it \"not executable\"\n // since that's what a shell would do\n }\n }\n\n return true;\n }\n\n /**\n * Returns the list of folders where we will search for an executable,\n * based on the PATH environment variable.\n */\n private static _getSearchFolders(context: IExecutableContext): string[] {\n const pathList: string = context.environmentMap.get('PATH') || '';\n\n const folders: string[] = [];\n\n // Avoid processing duplicates\n const seenPaths: Set<string> = new Set<string>();\n\n // NOTE: Cmd.exe on Windows always searches the current working directory first.\n // PowerShell and Unix shells do NOT do that, because it's a security concern.\n // We follow their behavior.\n\n for (const splitPath of pathList.split(path.delimiter)) {\n const trimmedPath: string = splitPath.trim();\n if (trimmedPath !== '') {\n if (!seenPaths.has(trimmedPath)) {\n // Fun fact: If you put relative paths in your PATH environment variable,\n // all shells will dynamically match them against the current working directory.\n // This is a terrible design, and in practice nobody does that, but it is supported...\n // so we allow it here.\n const resolvedPath: string = path.resolve(context.currentWorkingDirectory, trimmedPath);\n\n if (!seenPaths.has(resolvedPath)) {\n if (FileSystem.exists(resolvedPath)) {\n folders.push(resolvedPath);\n }\n\n seenPaths.add(resolvedPath);\n }\n\n seenPaths.add(trimmedPath);\n }\n }\n }\n\n return folders;\n }\n\n private static _getExecutableContext(options: IExecutableResolveOptions | undefined): IExecutableContext {\n if (!options) {\n options = {};\n }\n\n const environment: EnvironmentMap = Executable._buildEnvironmentMap(options);\n\n let currentWorkingDirectory: string;\n if (options.currentWorkingDirectory) {\n currentWorkingDirectory = path.resolve(options.currentWorkingDirectory);\n } else {\n currentWorkingDirectory = process.cwd();\n }\n\n const windowsExecutableExtensions: string[] = [];\n\n if (OS_PLATFORM === 'win32') {\n const pathExtVariable: string = environment.get('PATHEXT') || '';\n for (const splitValue of pathExtVariable.split(';')) {\n const trimmed: string = splitValue.trim().toLowerCase();\n // Ignore malformed extensions\n if (/^\\.[a-z0-9\\.]*[a-z0-9]$/i.test(trimmed)) {\n // Don't add the same extension twice\n if (windowsExecutableExtensions.indexOf(trimmed) < 0) {\n windowsExecutableExtensions.push(trimmed);\n }\n }\n }\n }\n\n return {\n environmentMap: environment,\n currentWorkingDirectory,\n windowsExecutableExtensions\n };\n }\n\n /**\n * Given an input string containing special symbol characters, this inserts the \"^\" escape\n * character to ensure the symbols are interpreted literally by the Windows shell.\n */\n private static _getEscapedForWindowsShell(text: string): string {\n const escapableCharRegExp: RegExp = /[%\\^&|<> ]/g;\n return text.replace(escapableCharRegExp, (value) => '^' + value);\n }\n\n /**\n * Checks for characters that are unsafe to pass to a Windows batch file\n * due to the way that cmd.exe implements escaping.\n */\n private static _validateArgsForWindowsShell(args: string[]): void {\n const specialCharRegExp: RegExp = /[%\\^&|<>\\r\\n]/g;\n\n for (const arg of args) {\n const match: RegExpMatchArray | null = arg.match(specialCharRegExp);\n if (match) {\n // NOTE: It is possible to escape some of these characters by prefixing them\n // with a caret (^), which allows these characters to be successfully passed\n // through to the batch file %1 variables. But they will be expanded again\n // whenever they are used. For example, NPM's binary wrapper batch files\n // use \"%*\" to pass their arguments to Node.exe, which causes them to be expanded\n // again. Unfortunately the Cmd.exe batch language provides native escaping\n // function (that could be used to insert the carets again).\n //\n // We could work around that by adding double carets, but in general there\n // is no way to predict how many times the variable will get expanded.\n // Thus, there is no generally reliable way to pass these characters.\n throw new Error(\n `The command line argument ${JSON.stringify(arg)} contains a` +\n ` special character ${JSON.stringify(match[0])} that cannot be escaped for the Windows shell`\n );\n }\n }\n }\n}\n"]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"FileError.d.ts","sourceRoot":"","sources":["../src/FileError.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,KAAK,iBAAiB,EAAQ,MAAM,QAAQ,CAAC;AAGtD;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;OAE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C/E,CAAC,CAAC;AAiIL,mBAAQ,CAAC,aAAa,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type { IProblemPattern } from '@rushstack/problem-matcher';\nimport { type FileLocationStyle, Path } from './Path';\nimport { TypeUuid } from './TypeUuid';\n\n/**\n * Provides options for the creation of a FileError.\n *\n * @public\n */\nexport interface IFileErrorOptions {\n /**\n * The absolute path to the file that contains the error.\n */\n absolutePath: string;\n\n /**\n * The root folder for the project that the error is in relation to.\n */\n projectFolder: string;\n\n /**\n * The line number of the error in the target file. Minimum value is 1.\n */\n line?: number;\n\n /**\n * The column number of the error in the target file. Minimum value is 1.\n */\n column?: number;\n}\n\n/**\n * Provides options for the output message of a file error.\n *\n * @public\n */\nexport interface IFileErrorFormattingOptions {\n /**\n * The format for the error message. If no format is provided, format 'Unix' is used by default.\n */\n format?: FileLocationStyle;\n}\n\nconst uuidFileError: string = '37a4c772-2dc8-4c66-89ae-262f8cc1f0c1';\n\nconst baseFolderEnvVar: string = 'RUSHSTACK_FILE_ERROR_BASE_FOLDER';\n\nconst unixProblemMatcherPattern: IProblemPattern = {\n regexp: '^\\\\[[^\\\\]]+\\\\]\\\\s+(Error|Warning):\\\\s+([^:]+):(\\\\d+):(\\\\d+)\\\\s+-\\\\s+(?:\\\\(([^)]+)\\\\)\\\\s+)?(.*)$',\n severity: 1,\n file: 2,\n line: 3,\n column: 4,\n code: 5,\n message: 6\n};\n\nconst vsProblemMatcherPattern: IProblemPattern = {\n regexp:\n '^\\\\[[^\\\\]]+\\\\]\\\\s+(Error|Warning):\\\\s+([^\\\\(]+)\\\\((\\\\d+),(\\\\d+)\\\\)\\\\s+-\\\\s+(?:\\\\(([^)]+)\\\\)\\\\s+)?(.*)$',\n severity: 1,\n file: 2,\n line: 3,\n column: 4,\n code: 5,\n message: 6\n};\n\n/**\n * An `Error` subclass that should be thrown to report an unexpected state that specifically references\n * a location in a file.\n *\n * @remarks The file path provided to the FileError constructor is expected to exist on disk. FileError\n * should not be used for reporting errors that are not in reference to an existing file.\n *\n * @public\n */\nexport class FileError extends Error {\n /** @internal */\n public static _sanitizedEnvironmentVariable: string | undefined;\n /** @internal */\n public static _environmentVariableIsAbsolutePath: boolean = false;\n\n private static _environmentVariableBasePathFnMap: ReadonlyMap<\n string | undefined,\n (fileError: FileError) => string | undefined\n > = new Map([\n [undefined, (fileError: FileError) => fileError.projectFolder],\n ['{PROJECT_FOLDER}', (fileError: FileError) => fileError.projectFolder],\n ['{ABSOLUTE_PATH}', (fileError: FileError) => undefined as string | undefined]\n ]);\n\n /** {@inheritdoc IFileErrorOptions.absolutePath} */\n public readonly absolutePath: string;\n /** {@inheritdoc IFileErrorOptions.projectFolder} */\n public readonly projectFolder: string;\n /** {@inheritdoc IFileErrorOptions.line} */\n public readonly line: number | undefined;\n /** {@inheritdoc IFileErrorOptions.column} */\n public readonly column: number | undefined;\n\n /**\n * Constructs a new instance of the {@link FileError} class.\n *\n * @param message - A message describing the error.\n * @param options - Options for the error.\n */\n public constructor(message: string, options: IFileErrorOptions) {\n super(message);\n\n this.absolutePath = options.absolutePath;\n this.projectFolder = options.projectFolder;\n this.line = options.line;\n this.column = options.column;\n\n // Manually set the prototype, as we can no longer extend built-in classes like Error, Array, Map, etc.\n // https://github.com/microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n //\n // Note: the prototype must also be set on any classes which extend this one\n (this as any).__proto__ = FileError.prototype; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n\n /**\n * Get the Unix-formatted the error message.\n *\n * @override\n */\n public toString(): string {\n // Default to formatting in 'Unix' format, for consistency.\n return this.getFormattedErrorMessage();\n }\n\n /**\n * Get the formatted error message.\n *\n * @param options - Options for the error message format.\n */\n public getFormattedErrorMessage(options?: IFileErrorFormattingOptions): string {\n return Path.formatFileLocation({\n format: options?.format || 'Unix',\n baseFolder: this._evaluateBaseFolder(),\n pathToFormat: this.absolutePath,\n message: this.message,\n line: this.line,\n column: this.column\n });\n }\n\n /**\n * Get the problem matcher pattern for parsing error messages.\n *\n * @param options - Options for the error message format.\n * @returns The problem matcher pattern.\n */\n public static getProblemMatcher(options?: Pick<IFileErrorFormattingOptions, 'format'>): IProblemPattern {\n const format: FileLocationStyle = options?.format || 'Unix';\n switch (format) {\n case 'Unix':\n return unixProblemMatcherPattern;\n case 'VisualStudio':\n return vsProblemMatcherPattern;\n default:\n throw new Error(`The FileError format \"${format}\" is not supported for problem matchers.`);\n }\n }\n\n private _evaluateBaseFolder(): string | undefined {\n // Cache the sanitized environment variable. This means that we don't support changing\n // the environment variable mid-execution. This is a reasonable tradeoff for the benefit\n // of being able to cache absolute paths, since that is only able to be determined after\n // running the regex, which is expensive. Since this would be a common execution path for\n // tools like Rush, we should optimize for that.\n if (!FileError._sanitizedEnvironmentVariable && process.env[baseFolderEnvVar]) {\n // Strip leading and trailing quotes, if present.\n FileError._sanitizedEnvironmentVariable = process.env[baseFolderEnvVar]!.replace(/^(\"|')|(\"|')$/g, '');\n }\n\n if (FileError._environmentVariableIsAbsolutePath) {\n return FileError._sanitizedEnvironmentVariable;\n }\n\n // undefined environment variable has a mapping to the project folder\n const baseFolderFn: ((fileError: FileError) => string | undefined) | undefined =\n FileError._environmentVariableBasePathFnMap.get(FileError._sanitizedEnvironmentVariable);\n if (baseFolderFn) {\n return baseFolderFn(this);\n }\n\n const baseFolderTokenRegex: RegExp = /{([^}]+)}/g;\n const result: RegExpExecArray | null = baseFolderTokenRegex.exec(\n FileError._sanitizedEnvironmentVariable!\n );\n if (!result) {\n // No tokens, assume absolute path\n FileError._environmentVariableIsAbsolutePath = true;\n return FileError._sanitizedEnvironmentVariable;\n } else if (result.index !== 0) {\n // Currently only support the token being first in the string.\n throw new Error(\n `The ${baseFolderEnvVar} environment variable contains text before the token \"${result[0]}\".`\n );\n } else if (result[0].length !== FileError._sanitizedEnvironmentVariable!.length) {\n // Currently only support the token being the entire string.\n throw new Error(\n `The ${baseFolderEnvVar} environment variable contains text after the token \"${result[0]}\".`\n );\n } else {\n throw new Error(\n `The ${baseFolderEnvVar} environment variable contains a token \"${result[0]}\", which is not ` +\n 'supported.'\n );\n }\n }\n\n public static [Symbol.hasInstance](instance: object): boolean {\n return TypeUuid.isInstanceOf(instance, uuidFileError);\n }\n}\n\nTypeUuid.registerClass(FileError, uuidFileError);\n"]} | ||
| {"version":3,"file":"FileError.js","sourceRoot":"","sources":["../src/FileError.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAI3D,iCAAsD;AACtD,yCAAsC;AAyCtC,MAAM,aAAa,GAAW,sCAAsC,CAAC;AAErE,MAAM,gBAAgB,GAAW,kCAAkC,CAAC;AAEpE,MAAM,yBAAyB,GAAoB;IACjD,MAAM,EAAE,iGAAiG;IACzG,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;CACX,CAAC;AAEF,MAAM,uBAAuB,GAAoB;IAC/C,MAAM,EACJ,wGAAwG;IAC1G,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;CACX,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAa,SAAU,SAAQ,KAAK;IAwBlC;;;;;OAKG;IACH,YAAmB,OAAe,EAAE,OAA0B;QAC5D,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;QACzC,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,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AC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,QAAgB;QACjD,OAAO,mBAAQ,CAAC,YAAY,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;;AA3IH,8BA4IC;AAzIC,gBAAgB;AACF,4CAAkC,GAAY,KAAK,CAAC;AAEnD,2CAAiC,GAG5C,IAAI,GAAG,CAAC;IACV,CAAC,SAAS,EAAE,CAAC,SAAoB,EAAE,EAAE,CAAC,SAAS,CAAC,aAAa,CAAC;IAC9D,CAAC,kBAAkB,EAAE,CAAC,SAAoB,EAAE,EAAE,CAAC,SAAS,CAAC,aAAa,CAAC;IACvE,CAAC,iBAAiB,EAAE,CAAC,SAAoB,EAAE,EAAE,CAAC,SAA+B,CAAC;CAC/E,CAAC,CAAC;AAiIL,mBAAQ,CAAC,aAAa,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type { IProblemPattern } from '@rushstack/problem-matcher';\n\nimport { type FileLocationStyle, Path } from './Path';\nimport { TypeUuid } from './TypeUuid';\n\n/**\n * Provides options for the creation of a FileError.\n *\n * @public\n */\nexport interface IFileErrorOptions {\n /**\n * The absolute path to the file that contains the error.\n */\n absolutePath: string;\n\n /**\n * The root folder for the project that the error is in relation to.\n */\n projectFolder: string;\n\n /**\n * The line number of the error in the target file. Minimum value is 1.\n */\n line?: number;\n\n /**\n * The column number of the error in the target file. Minimum value is 1.\n */\n column?: number;\n}\n\n/**\n * Provides options for the output message of a file error.\n *\n * @public\n */\nexport interface IFileErrorFormattingOptions {\n /**\n * The format for the error message. If no format is provided, format 'Unix' is used by default.\n */\n format?: FileLocationStyle;\n}\n\nconst uuidFileError: string = '37a4c772-2dc8-4c66-89ae-262f8cc1f0c1';\n\nconst baseFolderEnvVar: string = 'RUSHSTACK_FILE_ERROR_BASE_FOLDER';\n\nconst unixProblemMatcherPattern: IProblemPattern = {\n regexp: '^\\\\[[^\\\\]]+\\\\]\\\\s+(Error|Warning):\\\\s+([^:]+):(\\\\d+):(\\\\d+)\\\\s+-\\\\s+(?:\\\\(([^)]+)\\\\)\\\\s+)?(.*)$',\n severity: 1,\n file: 2,\n line: 3,\n column: 4,\n code: 5,\n message: 6\n};\n\nconst vsProblemMatcherPattern: IProblemPattern = {\n regexp:\n '^\\\\[[^\\\\]]+\\\\]\\\\s+(Error|Warning):\\\\s+([^\\\\(]+)\\\\((\\\\d+),(\\\\d+)\\\\)\\\\s+-\\\\s+(?:\\\\(([^)]+)\\\\)\\\\s+)?(.*)$',\n severity: 1,\n file: 2,\n line: 3,\n column: 4,\n code: 5,\n message: 6\n};\n\n/**\n * An `Error` subclass that should be thrown to report an unexpected state that specifically references\n * a location in a file.\n *\n * @remarks The file path provided to the FileError constructor is expected to exist on disk. FileError\n * should not be used for reporting errors that are not in reference to an existing file.\n *\n * @public\n */\nexport class FileError extends Error {\n /** @internal */\n public static _sanitizedEnvironmentVariable: string | undefined;\n /** @internal */\n public static _environmentVariableIsAbsolutePath: boolean = false;\n\n private static _environmentVariableBasePathFnMap: ReadonlyMap<\n string | undefined,\n (fileError: FileError) => string | undefined\n > = new Map([\n [undefined, (fileError: FileError) => fileError.projectFolder],\n ['{PROJECT_FOLDER}', (fileError: FileError) => fileError.projectFolder],\n ['{ABSOLUTE_PATH}', (fileError: FileError) => undefined as string | undefined]\n ]);\n\n /** {@inheritdoc IFileErrorOptions.absolutePath} */\n public readonly absolutePath: string;\n /** {@inheritdoc IFileErrorOptions.projectFolder} */\n public readonly projectFolder: string;\n /** {@inheritdoc IFileErrorOptions.line} */\n public readonly line: number | undefined;\n /** {@inheritdoc IFileErrorOptions.column} */\n public readonly column: number | undefined;\n\n /**\n * Constructs a new instance of the {@link FileError} class.\n *\n * @param message - A message describing the error.\n * @param options - Options for the error.\n */\n public constructor(message: string, options: IFileErrorOptions) {\n super(message);\n\n this.absolutePath = options.absolutePath;\n this.projectFolder = options.projectFolder;\n this.line = options.line;\n this.column = options.column;\n\n // Manually set the prototype, as we can no longer extend built-in classes like Error, Array, Map, etc.\n // https://github.com/microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n //\n // Note: the prototype must also be set on any classes which extend this one\n (this as any).__proto__ = FileError.prototype; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n\n /**\n * Get the Unix-formatted the error message.\n *\n * @override\n */\n public toString(): string {\n // Default to formatting in 'Unix' format, for consistency.\n return this.getFormattedErrorMessage();\n }\n\n /**\n * Get the formatted error message.\n *\n * @param options - Options for the error message format.\n */\n public getFormattedErrorMessage(options?: IFileErrorFormattingOptions): string {\n return Path.formatFileLocation({\n format: options?.format || 'Unix',\n baseFolder: this._evaluateBaseFolder(),\n pathToFormat: this.absolutePath,\n message: this.message,\n line: this.line,\n column: this.column\n });\n }\n\n /**\n * Get the problem matcher pattern for parsing error messages.\n *\n * @param options - Options for the error message format.\n * @returns The problem matcher pattern.\n */\n public static getProblemMatcher(options?: Pick<IFileErrorFormattingOptions, 'format'>): IProblemPattern {\n const format: FileLocationStyle = options?.format || 'Unix';\n switch (format) {\n case 'Unix':\n return unixProblemMatcherPattern;\n case 'VisualStudio':\n return vsProblemMatcherPattern;\n default:\n throw new Error(`The FileError format \"${format}\" is not supported for problem matchers.`);\n }\n }\n\n private _evaluateBaseFolder(): string | undefined {\n // Cache the sanitized environment variable. This means that we don't support changing\n // the environment variable mid-execution. This is a reasonable tradeoff for the benefit\n // of being able to cache absolute paths, since that is only able to be determined after\n // running the regex, which is expensive. Since this would be a common execution path for\n // tools like Rush, we should optimize for that.\n if (!FileError._sanitizedEnvironmentVariable && process.env[baseFolderEnvVar]) {\n // Strip leading and trailing quotes, if present.\n FileError._sanitizedEnvironmentVariable = process.env[baseFolderEnvVar]!.replace(/^(\"|')|(\"|')$/g, '');\n }\n\n if (FileError._environmentVariableIsAbsolutePath) {\n return FileError._sanitizedEnvironmentVariable;\n }\n\n // undefined environment variable has a mapping to the project folder\n const baseFolderFn: ((fileError: FileError) => string | undefined) | undefined =\n FileError._environmentVariableBasePathFnMap.get(FileError._sanitizedEnvironmentVariable);\n if (baseFolderFn) {\n return baseFolderFn(this);\n }\n\n const baseFolderTokenRegex: RegExp = /{([^}]+)}/g;\n const result: RegExpExecArray | null = baseFolderTokenRegex.exec(\n FileError._sanitizedEnvironmentVariable!\n );\n if (!result) {\n // No tokens, assume absolute path\n FileError._environmentVariableIsAbsolutePath = true;\n return FileError._sanitizedEnvironmentVariable;\n } else if (result.index !== 0) {\n // Currently only support the token being first in the string.\n throw new Error(\n `The ${baseFolderEnvVar} environment variable contains text before the token \"${result[0]}\".`\n );\n } else if (result[0].length !== FileError._sanitizedEnvironmentVariable!.length) {\n // Currently only support the token being the entire string.\n throw new Error(\n `The ${baseFolderEnvVar} environment variable contains text after the token \"${result[0]}\".`\n );\n } else {\n throw new Error(\n `The ${baseFolderEnvVar} environment variable contains a token \"${result[0]}\", which is not ` +\n 'supported.'\n );\n }\n }\n\n public static [Symbol.hasInstance](instance: object): boolean {\n return TypeUuid.isInstanceOf(instance, uuidFileError);\n }\n}\n\nTypeUuid.registerClass(FileError, uuidFileError);\n"]} |
@@ -1,2 +0,2 @@ | ||
| import * as fs from 'fs'; | ||
| import * as fs from 'node:fs'; | ||
| import { type NewlineKind, Encoding } from './Text'; | ||
@@ -3,0 +3,0 @@ import { PosixModeBits } from './PosixModeBits'; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"FileSystem.d.ts","sourceRoot":"","sources":["../src/FileSystem.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AAIzB,OAAO,EAAQ,KAAK,WAAW,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GAAG,EAAE,CAAC,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gB,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO;IAIrD;;OAEG;WACW,mBAAmB,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO;IAIxD;;;OAGG;WACW,yBAAyB,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO;IAI9D;;OAEG;WACW,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,IAAI,MAAM,CAAC,cAAc;IAW5E,OAAO,CAAC,MAAM,CAAC,WAAW;mBAqCL,gBAAgB;IAwCrC,OAAO,CAAC,MAAM,CAAC,cAAc;mBASR,mBAAmB;IASxC,OAAO,CAAC,MAAM,CAAC,mBAAmB;CAoBnC"} |
@@ -39,5 +39,5 @@ "use strict"; | ||
| exports.FileSystem = exports.AlreadyExistsBehavior = void 0; | ||
| const nodeJsPath = __importStar(require("path")); | ||
| const fs = __importStar(require("fs")); | ||
| const fsPromises = __importStar(require("fs/promises")); | ||
| const nodeJsPath = __importStar(require("node:path")); | ||
| const fs = __importStar(require("node:fs")); | ||
| const fsPromises = __importStar(require("node:fs/promises")); | ||
| const fsx = __importStar(require("fs-extra")); | ||
@@ -44,0 +44,0 @@ const Text_1 = require("./Text"); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Import.d.ts","sourceRoot":"","sources":["../src/Import.ts"],"names":[],"mappings":"AAeA;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;IAEvB;;;;;;;;;;;;;;;OAeG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAE/B;;;;;;;;;;;;;;;;OAgBG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,MAAM,CAAC;CAC5C;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA2B,SAAQ,qBAAqB;IACvE;;;;;;;OAOG;IACH,gBAAgB,CAAC,EAAE,CA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;;;;;;;;;;;;OAqEG;WAEW,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,GAAG,GAAG;IAK7E;;;;;;;;;;;;;;;;;;;;;;;OAuBG;WACW,aAAa,CAAC,OAAO,EAAE,2BAA2B,GAAG,MAAM;IA4CzE;;OAEG;WACiB,kBAAkB,CAAC,OAAO,EAAE,gCAAgC,GAAG,OAAO,CAAC,MAAM,CAAC;IAwFlG;;;;;;;;;;;;;;;;;;;OAmBG;WACW,cAAc,CAAC,OAAO,EAAE,4BAA4B,GAAG,MAAM;IA6C3E;;OAEG;WACiB,mBAAmB,CAAC,OAAO,EAAE,iCAAiC,GAAG,OAAO,CAAC,MAAM,CAAC;IA8EpG,OAAO,CAAC,MAAM,CAAC,eAAe;CAa/B"} |
+2
-2
@@ -39,6 +39,6 @@ "use strict"; | ||
| exports.Import = void 0; | ||
| const path = __importStar(require("path")); | ||
| const path = __importStar(require("node:path")); | ||
| const nodeModule = require("module"); | ||
| const importLazy = require("import-lazy"); | ||
| const Resolve = __importStar(require("resolve")); | ||
| const nodeModule = require("module"); | ||
| const PackageJsonLookup_1 = require("./PackageJsonLookup"); | ||
@@ -45,0 +45,0 @@ const FileSystem_1 = require("./FileSystem"); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Import.js","sourceRoot":"","sources":["../src/Import.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,2CAA6B;AAC7B,0CAA2C;AAC3C,iDAAmC;AACnC,qCAAsC;AAEtC,2DAAwD;AACxD,6CAA0C;AAE1C,+CAA4C;AA2I5C;;;GAGG;AACH,MAAa,MAAM;IAET,MAAM,KAAK,eAAe;QAChC,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC;YAC7B,MAAM,CAAC,gBAAgB,GAAG,IAAI,GAAG,CAAS,UAAU,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AAC;YAC9F,OAAO;gBACL,eAAe,EAAE,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC;gBAC9C,WAAW,EAAE,WAAW,CAAC,IAAI;aAC9B,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;CACF;AApZD,wBAoZC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'path';\nimport importLazy = require('import-lazy');\nimport * as Resolve from 'resolve';\nimport nodeModule = require('module');\n\nimport { PackageJsonLookup } from './PackageJsonLookup';\nimport { FileSystem } from './FileSystem';\nimport type { IPackageJson } from './IPackageJson';\nimport { PackageName } from './PackageName';\n\ntype RealpathFnType = Parameters<typeof Resolve.default>[1]['realpath'];\n\n/**\n * Common options shared by {@link IImportResolveModuleOptions} and {@link IImportResolvePackageOptions}\n * @public\n */\nexport interface IImportResolveOptions {\n /**\n * The path from which {@link IImportResolveModuleOptions.modulePath} or\n * {@link IImportResolvePackageOptions.packageName} should be resolved.\n */\n baseFolderPath: string;\n\n /**\n * If true, if the package name matches a Node.js system module, then the return\n * value will be the package name without any path.\n *\n * @remarks\n * This will take precedence over an installed NPM package of the same name.\n *\n * Example:\n * ```ts\n * // Returns the string \"fs\" indicating the Node.js system module\n * Import.resolveModulePath({\n * resolvePath: \"fs\",\n * basePath: process.cwd()\n * })\n * ```\n */\n includeSystemModules?: boolean;\n\n /**\n * If true, then resolvePath is allowed to refer to the package.json of the active project.\n *\n * @remarks\n * This will take precedence over any installed dependency with the same name.\n * Note that this requires an additional PackageJsonLookup calculation.\n *\n * Example:\n * ```ts\n * // Returns an absolute path to the current package\n * Import.resolveModulePath({\n * resolvePath: \"current-project\",\n * basePath: process.cwd(),\n * allowSelfReference: true\n * })\n * ```\n */\n allowSelfReference?: boolean;\n\n /**\n * A function used to resolve the realpath of a provided file path.\n *\n * @remarks\n * This is used to resolve symlinks and other non-standard file paths. By default, this uses the\n * {@link FileSystem.getRealPath} function. However, it can be overridden to use a custom implementation\n * which may be faster, more accurate, or provide support for additional non-standard file paths.\n */\n getRealPath?: (filePath: string) => string;\n}\n\n/**\n * Common options shared by {@link IImportResolveModuleAsyncOptions} and {@link IImportResolvePackageAsyncOptions}\n * @public\n */\nexport interface IImportResolveAsyncOptions extends IImportResolveOptions {\n /**\n * A function used to resolve the realpath of a provided file path.\n *\n * @remarks\n * This is used to resolve symlinks and other non-standard file paths. By default, this uses the\n * {@link FileSystem.getRealPath} function. However, it can be overridden to use a custom implementation\n * which may be faster, more accurate, or provide support for additional non-standard file paths.\n */\n getRealPathAsync?: (filePath: string) => Promise<string>;\n}\n\n/**\n * Options for {@link Import.resolveModule}\n * @public\n */\nexport interface IImportResolveModuleOptions extends IImportResolveOptions {\n /**\n * The module identifier to resolve. For example \"\\@rushstack/node-core-library\" or\n * \"\\@rushstack/node-core-library/lib/index.js\"\n */\n modulePath: string;\n}\n\n/**\n * Options for {@link Import.resolveModuleAsync}\n * @public\n */\nexport interface IImportResolveModuleAsyncOptions extends IImportResolveAsyncOptions {\n /**\n * The module identifier to resolve. For example \"\\@rushstack/node-core-library\" or\n * \"\\@rushstack/node-core-library/lib/index.js\"\n */\n modulePath: string;\n}\n\n/**\n * Options for {@link Import.resolvePackage}\n * @public\n */\nexport interface IImportResolvePackageOptions extends IImportResolveOptions {\n /**\n * The package name to resolve. For example \"\\@rushstack/node-core-library\"\n */\n packageName: string;\n\n /**\n * If true, then the module path will be resolved using Node.js's built-in resolution algorithm.\n *\n * @remarks\n * This allows reusing Node's built-in resolver cache.\n * This implies `allowSelfReference: true`. The passed `getRealPath` will only be used on `baseFolderPath`.\n */\n useNodeJSResolver?: boolean;\n}\n\n/**\n * Options for {@link Import.resolvePackageAsync}\n * @public\n */\nexport interface IImportResolvePackageAsyncOptions extends IImportResolveAsyncOptions {\n /**\n * The package name to resolve. For example \"\\@rushstack/node-core-library\"\n */\n packageName: string;\n}\n\ninterface IPackageDescriptor {\n packageRootPath: string;\n packageName: string;\n}\n\n/**\n * Helpers for resolving and importing Node.js modules.\n * @public\n */\nexport class Import {\n private static __builtInModules: Set<string> | undefined;\n private static get _builtInModules(): Set<string> {\n if (!Import.__builtInModules) {\n Import.__builtInModules = new Set<string>(nodeModule.builtinModules);\n }\n\n return Import.__builtInModules;\n }\n\n /**\n * Provides a way to improve process startup times by lazy-loading imported modules.\n *\n * @remarks\n * This is a more structured wrapper for the {@link https://www.npmjs.com/package/import-lazy|import-lazy}\n * package. It enables you to replace an import like this:\n *\n * ```ts\n * import * as example from 'example'; // <-- 100ms load time\n *\n * if (condition) {\n * example.doSomething();\n * }\n * ```\n *\n * ...with a pattern like this:\n *\n * ```ts\n * const example: typeof import('example') = Import.lazy('example', require);\n *\n * if (condition) {\n * example.doSomething(); // <-- 100ms load time occurs here, only if needed\n * }\n * ```\n *\n * The implementation relies on JavaScript's `Proxy` feature to intercept access to object members. Thus\n * it will only work correctly with certain types of module exports. If a particular export isn't well behaved,\n * you may need to find (or introduce) some other module in your dependency graph to apply the optimization to.\n *\n * Usage guidelines:\n *\n * - Always specify types using `typeof` as shown above.\n *\n * - Never apply lazy-loading in a way that would convert the module's type to `any`. Losing type safety\n * seriously impacts the maintainability of the code base.\n *\n * - In cases where the non-runtime types are needed, import them separately using the `Types` suffix:\n *\n * ```ts\n * const example: typeof import('example') = Import.lazy('example', require);\n * import type * as exampleTypes from 'example';\n * ```\n *\n * - If the imported module confusingly has the same name as its export, then use the Module suffix:\n *\n * ```ts\n * const exampleModule: typeof import('../../logic/Example') = Import.lazy(\n * '../../logic/Example', require);\n * import type * as exampleTypes from '../../logic/Example';\n * ```\n *\n * - If the exports cause a lot of awkwardness (e.g. too many expressions need to have `exampleModule.` inserted\n * into them), or if some exports cannot be proxied (e.g. `Import.lazy('example', require)` returns a function\n * signature), then do not lazy-load that module. Instead, apply lazy-loading to some other module which is\n * better behaved.\n *\n * - It's recommended to sort imports in a standard ordering:\n *\n * ```ts\n * // 1. external imports\n * import * as path from 'path';\n * import { Import, JsonFile, JsonObject } from '@rushstack/node-core-library';\n *\n * // 2. local imports\n * import { LocalFile } from './path/LocalFile';\n *\n * // 3. lazy-imports (which are technically variables, not imports)\n * const semver: typeof import('semver') = Import.lazy('semver', require);\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public static lazy(moduleName: string, require: (id: string) => unknown): any {\n const importLazyLocal: (moduleName: string) => unknown = importLazy(require);\n return importLazyLocal(moduleName);\n }\n\n /**\n * This resolves a module path using similar logic as the Node.js `require.resolve()` API,\n * but supporting extra features such as specifying the base folder.\n *\n * @remarks\n * A module path is a text string that might appear in a statement such as\n * `import { X } from \"____\";` or `const x = require(\"___\");`. The implementation is based\n * on the popular `resolve` NPM package.\n *\n * Suppose `example` is an NPM package whose entry point is `lib/index.js`:\n * ```ts\n * // Returns \"/path/to/project/node_modules/example/lib/index.js\"\n * Import.resolveModule({ modulePath: 'example' });\n *\n * // Returns \"/path/to/project/node_modules/example/lib/other.js\"\n * Import.resolveModule({ modulePath: 'example/lib/other' });\n * ```\n * If you need to determine the containing package folder\n * (`/path/to/project/node_modules/example`), use {@link Import.resolvePackage} instead.\n *\n * @returns the absolute path of the resolved module.\n * If {@link IImportResolveOptions.includeSystemModules} is specified\n * and a system module is found, then its name is returned without any file path.\n */\n public static resolveModule(options: IImportResolveModuleOptions): string {\n const { modulePath, baseFolderPath, includeSystemModules, allowSelfReference, getRealPath } = options;\n\n if (path.isAbsolute(modulePath)) {\n return modulePath;\n }\n\n const normalizedRootPath: string = (getRealPath || FileSystem.getRealPath)(baseFolderPath);\n\n if (modulePath.startsWith('.')) {\n // This looks like a conventional relative path\n return path.resolve(normalizedRootPath, modulePath);\n }\n\n // Built-in modules do not have a scope, so if there is a slash, then we need to check\n // against the first path segment\n const slashIndex: number = modulePath.indexOf('/');\n const moduleName: string = slashIndex === -1 ? modulePath : modulePath.slice(0, slashIndex);\n if (!includeSystemModules && Import._builtInModules.has(moduleName)) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\".`);\n }\n\n if (allowSelfReference === true) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (\n ownPackage &&\n (modulePath === ownPackage.packageName || modulePath.startsWith(`${ownPackage.packageName}/`))\n ) {\n const packagePath: string = modulePath.slice(ownPackage.packageName.length + 1);\n return path.resolve(ownPackage.packageRootPath, packagePath);\n }\n }\n\n try {\n return Resolve.sync(modulePath, {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpathSync: getRealPath\n });\n } catch (e: unknown) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\": ${e}`);\n }\n }\n\n /**\n * Async version of {@link Import.resolveModule}.\n */\n public static async resolveModuleAsync(options: IImportResolveModuleAsyncOptions): Promise<string> {\n const {\n modulePath,\n baseFolderPath,\n includeSystemModules,\n allowSelfReference,\n getRealPath,\n getRealPathAsync\n } = options;\n\n if (path.isAbsolute(modulePath)) {\n return modulePath;\n }\n\n const normalizedRootPath: string = await (getRealPathAsync || getRealPath || FileSystem.getRealPathAsync)(\n baseFolderPath\n );\n\n if (modulePath.startsWith('.')) {\n // This looks like a conventional relative path\n return path.resolve(normalizedRootPath, modulePath);\n }\n\n // Built-in modules do not have a scope, so if there is a slash, then we need to check\n // against the first path segment\n const slashIndex: number = modulePath.indexOf('/');\n const moduleName: string = slashIndex === -1 ? modulePath : modulePath.slice(0, slashIndex);\n if (!includeSystemModules && Import._builtInModules.has(moduleName)) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\".`);\n }\n\n if (allowSelfReference === true) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (\n ownPackage &&\n (modulePath === ownPackage.packageName || modulePath.startsWith(`${ownPackage.packageName}/`))\n ) {\n const packagePath: string = modulePath.slice(ownPackage.packageName.length + 1);\n return path.resolve(ownPackage.packageRootPath, packagePath);\n }\n }\n\n try {\n const resolvePromise: Promise<string> = new Promise(\n (resolve: (resolvedPath: string) => void, reject: (error: Error) => void) => {\n const realPathFn: RealpathFnType =\n getRealPathAsync || getRealPath\n ? (filePath: string, callback: (error: Error | null, resolvedPath?: string) => void) => {\n if (getRealPathAsync) {\n getRealPathAsync(filePath)\n .then((resolvedPath) => callback(null, resolvedPath))\n .catch((error) => callback(error));\n } else {\n try {\n const resolvedPath: string = getRealPath!(filePath);\n callback(null, resolvedPath);\n } catch (error: unknown) {\n callback(error as Error);\n }\n }\n }\n : undefined;\n\n Resolve.default(\n modulePath,\n {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpath: realPathFn\n },\n (error: Error | null, resolvedPath?: string) => {\n if (error) {\n reject(error);\n } else {\n // Resolve docs state that either an error will be returned, or the resolved path.\n // In this case, the resolved path should always be populated.\n resolve(resolvedPath!);\n }\n }\n );\n }\n );\n return await resolvePromise;\n } catch (e: unknown) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\": ${e}`);\n }\n }\n\n /**\n * Performs module resolution to determine the folder where a package is installed.\n *\n * @remarks\n * Suppose `example` is an NPM package whose entry point is `lib/index.js`:\n * ```ts\n * // Returns \"/path/to/project/node_modules/example\"\n * Import.resolvePackage({ packageName: 'example' });\n * ```\n *\n * If you need to resolve a module path, use {@link Import.resolveModule} instead:\n * ```ts\n * // Returns \"/path/to/project/node_modules/example/lib/index.js\"\n * Import.resolveModule({ modulePath: 'example' });\n * ```\n *\n * @returns the absolute path of the package folder.\n * If {@link IImportResolveOptions.includeSystemModules} is specified\n * and a system module is found, then its name is returned without any file path.\n */\n public static resolvePackage(options: IImportResolvePackageOptions): string {\n const {\n packageName,\n includeSystemModules,\n baseFolderPath,\n allowSelfReference,\n getRealPath,\n useNodeJSResolver\n } = options;\n\n if (includeSystemModules && Import._builtInModules.has(packageName)) {\n return packageName;\n }\n\n const normalizedRootPath: string = (getRealPath || FileSystem.getRealPath)(baseFolderPath);\n\n if (allowSelfReference) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (ownPackage && ownPackage.packageName === packageName) {\n return ownPackage.packageRootPath;\n }\n }\n\n PackageName.parse(packageName); // Ensure the package name is valid and doesn't contain a path\n\n try {\n const resolvedPath: string = useNodeJSResolver\n ? require.resolve(`${packageName}/package.json`, {\n paths: [normalizedRootPath]\n })\n : // Append `/package.json` to ensure `resolve.sync` doesn't attempt to return a system package, and to avoid\n // having to mess with the `packageFilter` option.\n Resolve.sync(`${packageName}/package.json`, {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpathSync: getRealPath\n });\n\n const packagePath: string = path.dirname(resolvedPath);\n return packagePath;\n } catch (e: unknown) {\n throw new Error(`Cannot find package \"${packageName}\" from \"${baseFolderPath}\": ${e}.`);\n }\n }\n\n /**\n * Async version of {@link Import.resolvePackage}.\n */\n public static async resolvePackageAsync(options: IImportResolvePackageAsyncOptions): Promise<string> {\n const {\n packageName,\n includeSystemModules,\n baseFolderPath,\n allowSelfReference,\n getRealPath,\n getRealPathAsync\n } = options;\n\n if (includeSystemModules && Import._builtInModules.has(packageName)) {\n return packageName;\n }\n\n const normalizedRootPath: string = await (getRealPathAsync || getRealPath || FileSystem.getRealPathAsync)(\n baseFolderPath\n );\n\n if (allowSelfReference) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (ownPackage && ownPackage.packageName === packageName) {\n return ownPackage.packageRootPath;\n }\n }\n\n PackageName.parse(packageName); // Ensure the package name is valid and doesn't contain a path\n\n try {\n const resolvePromise: Promise<string> = new Promise(\n (resolve: (resolvedPath: string) => void, reject: (error: Error) => void) => {\n const realPathFn: RealpathFnType =\n getRealPathAsync || getRealPath\n ? (filePath: string, callback: (error: Error | null, resolvedPath?: string) => void) => {\n if (getRealPathAsync) {\n getRealPathAsync(filePath)\n .then((resolvedPath) => callback(null, resolvedPath))\n .catch((error) => callback(error));\n } else {\n try {\n const resolvedPath: string = getRealPath!(filePath);\n callback(null, resolvedPath);\n } catch (error: unknown) {\n callback(error as Error);\n }\n }\n }\n : undefined;\n\n Resolve.default(\n // Append `/package.json` to ensure `resolve` doesn't attempt to return a system package, and to avoid\n // having to mess with the `packageFilter` option.\n `${packageName}/package.json`,\n {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpath: realPathFn\n },\n (error: Error | null, resolvedPath?: string) => {\n if (error) {\n reject(error);\n } else {\n // Resolve docs state that either an error will be returned, or the resolved path.\n // In this case, the resolved path should always be populated.\n resolve(resolvedPath!);\n }\n }\n );\n }\n );\n const resolvedPath: string = await resolvePromise;\n\n const packagePath: string = path.dirname(resolvedPath);\n return packagePath;\n } catch (e: unknown) {\n throw new Error(`Cannot find package \"${packageName}\" from \"${baseFolderPath}\": ${e}`);\n }\n }\n\n private static _getPackageName(rootPath: string): IPackageDescriptor | undefined {\n const packageJsonPath: string | undefined =\n PackageJsonLookup.instance.tryGetPackageJsonFilePathFor(rootPath);\n if (packageJsonPath) {\n const packageJson: IPackageJson = PackageJsonLookup.instance.loadPackageJson(packageJsonPath);\n return {\n packageRootPath: path.dirname(packageJsonPath),\n packageName: packageJson.name\n };\n } else {\n return undefined;\n }\n }\n}\n"]} | ||
| {"version":3,"file":"Import.js","sourceRoot":"","sources":["../src/Import.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,gDAAkC;AAClC,qCAAsC;AAEtC,0CAA2C;AAC3C,iDAAmC;AAEnC,2DAAwD;AACxD,6CAA0C;AAE1C,+CAA4C;AA2I5C;;;GAGG;AACH,MAAa,MAAM;IAET,MAAM,KAAK,eAAe;QAChC,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC;YAC7B,MAAM,CAAC,gBAAgB,GAAG,IAAI,GAAG,CAAS,UAAU,CAAC,cAAc,CAAC,CAAC;QACvE,CAAC;QAED,OAAO,MAAM,CAAC,gBA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Ae,CAAC;gBAC9C,WAAW,EAAE,WAAW,CAAC,IAAI;aAC9B,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;CACF;AApZD,wBAoZC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'node:path';\nimport nodeModule = require('module');\n\nimport importLazy = require('import-lazy');\nimport * as Resolve from 'resolve';\n\nimport { PackageJsonLookup } from './PackageJsonLookup';\nimport { FileSystem } from './FileSystem';\nimport type { IPackageJson } from './IPackageJson';\nimport { PackageName } from './PackageName';\n\ntype RealpathFnType = Parameters<typeof Resolve.default>[1]['realpath'];\n\n/**\n * Common options shared by {@link IImportResolveModuleOptions} and {@link IImportResolvePackageOptions}\n * @public\n */\nexport interface IImportResolveOptions {\n /**\n * The path from which {@link IImportResolveModuleOptions.modulePath} or\n * {@link IImportResolvePackageOptions.packageName} should be resolved.\n */\n baseFolderPath: string;\n\n /**\n * If true, if the package name matches a Node.js system module, then the return\n * value will be the package name without any path.\n *\n * @remarks\n * This will take precedence over an installed NPM package of the same name.\n *\n * Example:\n * ```ts\n * // Returns the string \"fs\" indicating the Node.js system module\n * Import.resolveModulePath({\n * resolvePath: \"fs\",\n * basePath: process.cwd()\n * })\n * ```\n */\n includeSystemModules?: boolean;\n\n /**\n * If true, then resolvePath is allowed to refer to the package.json of the active project.\n *\n * @remarks\n * This will take precedence over any installed dependency with the same name.\n * Note that this requires an additional PackageJsonLookup calculation.\n *\n * Example:\n * ```ts\n * // Returns an absolute path to the current package\n * Import.resolveModulePath({\n * resolvePath: \"current-project\",\n * basePath: process.cwd(),\n * allowSelfReference: true\n * })\n * ```\n */\n allowSelfReference?: boolean;\n\n /**\n * A function used to resolve the realpath of a provided file path.\n *\n * @remarks\n * This is used to resolve symlinks and other non-standard file paths. By default, this uses the\n * {@link FileSystem.getRealPath} function. However, it can be overridden to use a custom implementation\n * which may be faster, more accurate, or provide support for additional non-standard file paths.\n */\n getRealPath?: (filePath: string) => string;\n}\n\n/**\n * Common options shared by {@link IImportResolveModuleAsyncOptions} and {@link IImportResolvePackageAsyncOptions}\n * @public\n */\nexport interface IImportResolveAsyncOptions extends IImportResolveOptions {\n /**\n * A function used to resolve the realpath of a provided file path.\n *\n * @remarks\n * This is used to resolve symlinks and other non-standard file paths. By default, this uses the\n * {@link FileSystem.getRealPath} function. However, it can be overridden to use a custom implementation\n * which may be faster, more accurate, or provide support for additional non-standard file paths.\n */\n getRealPathAsync?: (filePath: string) => Promise<string>;\n}\n\n/**\n * Options for {@link Import.resolveModule}\n * @public\n */\nexport interface IImportResolveModuleOptions extends IImportResolveOptions {\n /**\n * The module identifier to resolve. For example \"\\@rushstack/node-core-library\" or\n * \"\\@rushstack/node-core-library/lib/index.js\"\n */\n modulePath: string;\n}\n\n/**\n * Options for {@link Import.resolveModuleAsync}\n * @public\n */\nexport interface IImportResolveModuleAsyncOptions extends IImportResolveAsyncOptions {\n /**\n * The module identifier to resolve. For example \"\\@rushstack/node-core-library\" or\n * \"\\@rushstack/node-core-library/lib/index.js\"\n */\n modulePath: string;\n}\n\n/**\n * Options for {@link Import.resolvePackage}\n * @public\n */\nexport interface IImportResolvePackageOptions extends IImportResolveOptions {\n /**\n * The package name to resolve. For example \"\\@rushstack/node-core-library\"\n */\n packageName: string;\n\n /**\n * If true, then the module path will be resolved using Node.js's built-in resolution algorithm.\n *\n * @remarks\n * This allows reusing Node's built-in resolver cache.\n * This implies `allowSelfReference: true`. The passed `getRealPath` will only be used on `baseFolderPath`.\n */\n useNodeJSResolver?: boolean;\n}\n\n/**\n * Options for {@link Import.resolvePackageAsync}\n * @public\n */\nexport interface IImportResolvePackageAsyncOptions extends IImportResolveAsyncOptions {\n /**\n * The package name to resolve. For example \"\\@rushstack/node-core-library\"\n */\n packageName: string;\n}\n\ninterface IPackageDescriptor {\n packageRootPath: string;\n packageName: string;\n}\n\n/**\n * Helpers for resolving and importing Node.js modules.\n * @public\n */\nexport class Import {\n private static __builtInModules: Set<string> | undefined;\n private static get _builtInModules(): Set<string> {\n if (!Import.__builtInModules) {\n Import.__builtInModules = new Set<string>(nodeModule.builtinModules);\n }\n\n return Import.__builtInModules;\n }\n\n /**\n * Provides a way to improve process startup times by lazy-loading imported modules.\n *\n * @remarks\n * This is a more structured wrapper for the {@link https://www.npmjs.com/package/import-lazy|import-lazy}\n * package. It enables you to replace an import like this:\n *\n * ```ts\n * import * as example from 'example'; // <-- 100ms load time\n *\n * if (condition) {\n * example.doSomething();\n * }\n * ```\n *\n * ...with a pattern like this:\n *\n * ```ts\n * const example: typeof import('example') = Import.lazy('example', require);\n *\n * if (condition) {\n * example.doSomething(); // <-- 100ms load time occurs here, only if needed\n * }\n * ```\n *\n * The implementation relies on JavaScript's `Proxy` feature to intercept access to object members. Thus\n * it will only work correctly with certain types of module exports. If a particular export isn't well behaved,\n * you may need to find (or introduce) some other module in your dependency graph to apply the optimization to.\n *\n * Usage guidelines:\n *\n * - Always specify types using `typeof` as shown above.\n *\n * - Never apply lazy-loading in a way that would convert the module's type to `any`. Losing type safety\n * seriously impacts the maintainability of the code base.\n *\n * - In cases where the non-runtime types are needed, import them separately using the `Types` suffix:\n *\n * ```ts\n * const example: typeof import('example') = Import.lazy('example', require);\n * import type * as exampleTypes from 'example';\n * ```\n *\n * - If the imported module confusingly has the same name as its export, then use the Module suffix:\n *\n * ```ts\n * const exampleModule: typeof import('../../logic/Example') = Import.lazy(\n * '../../logic/Example', require);\n * import type * as exampleTypes from '../../logic/Example';\n * ```\n *\n * - If the exports cause a lot of awkwardness (e.g. too many expressions need to have `exampleModule.` inserted\n * into them), or if some exports cannot be proxied (e.g. `Import.lazy('example', require)` returns a function\n * signature), then do not lazy-load that module. Instead, apply lazy-loading to some other module which is\n * better behaved.\n *\n * - It's recommended to sort imports in a standard ordering:\n *\n * ```ts\n * // 1. external imports\n * import * as path from 'path';\n * import { Import, JsonFile, JsonObject } from '@rushstack/node-core-library';\n *\n * // 2. local imports\n * import { LocalFile } from './path/LocalFile';\n *\n * // 3. lazy-imports (which are technically variables, not imports)\n * const semver: typeof import('semver') = Import.lazy('semver', require);\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public static lazy(moduleName: string, require: (id: string) => unknown): any {\n const importLazyLocal: (moduleName: string) => unknown = importLazy(require);\n return importLazyLocal(moduleName);\n }\n\n /**\n * This resolves a module path using similar logic as the Node.js `require.resolve()` API,\n * but supporting extra features such as specifying the base folder.\n *\n * @remarks\n * A module path is a text string that might appear in a statement such as\n * `import { X } from \"____\";` or `const x = require(\"___\");`. The implementation is based\n * on the popular `resolve` NPM package.\n *\n * Suppose `example` is an NPM package whose entry point is `lib/index.js`:\n * ```ts\n * // Returns \"/path/to/project/node_modules/example/lib/index.js\"\n * Import.resolveModule({ modulePath: 'example' });\n *\n * // Returns \"/path/to/project/node_modules/example/lib/other.js\"\n * Import.resolveModule({ modulePath: 'example/lib/other' });\n * ```\n * If you need to determine the containing package folder\n * (`/path/to/project/node_modules/example`), use {@link Import.resolvePackage} instead.\n *\n * @returns the absolute path of the resolved module.\n * If {@link IImportResolveOptions.includeSystemModules} is specified\n * and a system module is found, then its name is returned without any file path.\n */\n public static resolveModule(options: IImportResolveModuleOptions): string {\n const { modulePath, baseFolderPath, includeSystemModules, allowSelfReference, getRealPath } = options;\n\n if (path.isAbsolute(modulePath)) {\n return modulePath;\n }\n\n const normalizedRootPath: string = (getRealPath || FileSystem.getRealPath)(baseFolderPath);\n\n if (modulePath.startsWith('.')) {\n // This looks like a conventional relative path\n return path.resolve(normalizedRootPath, modulePath);\n }\n\n // Built-in modules do not have a scope, so if there is a slash, then we need to check\n // against the first path segment\n const slashIndex: number = modulePath.indexOf('/');\n const moduleName: string = slashIndex === -1 ? modulePath : modulePath.slice(0, slashIndex);\n if (!includeSystemModules && Import._builtInModules.has(moduleName)) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\".`);\n }\n\n if (allowSelfReference === true) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (\n ownPackage &&\n (modulePath === ownPackage.packageName || modulePath.startsWith(`${ownPackage.packageName}/`))\n ) {\n const packagePath: string = modulePath.slice(ownPackage.packageName.length + 1);\n return path.resolve(ownPackage.packageRootPath, packagePath);\n }\n }\n\n try {\n return Resolve.sync(modulePath, {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpathSync: getRealPath\n });\n } catch (e: unknown) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\": ${e}`);\n }\n }\n\n /**\n * Async version of {@link Import.resolveModule}.\n */\n public static async resolveModuleAsync(options: IImportResolveModuleAsyncOptions): Promise<string> {\n const {\n modulePath,\n baseFolderPath,\n includeSystemModules,\n allowSelfReference,\n getRealPath,\n getRealPathAsync\n } = options;\n\n if (path.isAbsolute(modulePath)) {\n return modulePath;\n }\n\n const normalizedRootPath: string = await (getRealPathAsync || getRealPath || FileSystem.getRealPathAsync)(\n baseFolderPath\n );\n\n if (modulePath.startsWith('.')) {\n // This looks like a conventional relative path\n return path.resolve(normalizedRootPath, modulePath);\n }\n\n // Built-in modules do not have a scope, so if there is a slash, then we need to check\n // against the first path segment\n const slashIndex: number = modulePath.indexOf('/');\n const moduleName: string = slashIndex === -1 ? modulePath : modulePath.slice(0, slashIndex);\n if (!includeSystemModules && Import._builtInModules.has(moduleName)) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\".`);\n }\n\n if (allowSelfReference === true) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (\n ownPackage &&\n (modulePath === ownPackage.packageName || modulePath.startsWith(`${ownPackage.packageName}/`))\n ) {\n const packagePath: string = modulePath.slice(ownPackage.packageName.length + 1);\n return path.resolve(ownPackage.packageRootPath, packagePath);\n }\n }\n\n try {\n const resolvePromise: Promise<string> = new Promise(\n (resolve: (resolvedPath: string) => void, reject: (error: Error) => void) => {\n const realPathFn: RealpathFnType =\n getRealPathAsync || getRealPath\n ? (filePath: string, callback: (error: Error | null, resolvedPath?: string) => void) => {\n if (getRealPathAsync) {\n getRealPathAsync(filePath)\n .then((resolvedPath) => callback(null, resolvedPath))\n .catch((error) => callback(error));\n } else {\n try {\n const resolvedPath: string = getRealPath!(filePath);\n callback(null, resolvedPath);\n } catch (error: unknown) {\n callback(error as Error);\n }\n }\n }\n : undefined;\n\n Resolve.default(\n modulePath,\n {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpath: realPathFn\n },\n (error: Error | null, resolvedPath?: string) => {\n if (error) {\n reject(error);\n } else {\n // Resolve docs state that either an error will be returned, or the resolved path.\n // In this case, the resolved path should always be populated.\n resolve(resolvedPath!);\n }\n }\n );\n }\n );\n return await resolvePromise;\n } catch (e: unknown) {\n throw new Error(`Cannot find module \"${modulePath}\" from \"${options.baseFolderPath}\": ${e}`);\n }\n }\n\n /**\n * Performs module resolution to determine the folder where a package is installed.\n *\n * @remarks\n * Suppose `example` is an NPM package whose entry point is `lib/index.js`:\n * ```ts\n * // Returns \"/path/to/project/node_modules/example\"\n * Import.resolvePackage({ packageName: 'example' });\n * ```\n *\n * If you need to resolve a module path, use {@link Import.resolveModule} instead:\n * ```ts\n * // Returns \"/path/to/project/node_modules/example/lib/index.js\"\n * Import.resolveModule({ modulePath: 'example' });\n * ```\n *\n * @returns the absolute path of the package folder.\n * If {@link IImportResolveOptions.includeSystemModules} is specified\n * and a system module is found, then its name is returned without any file path.\n */\n public static resolvePackage(options: IImportResolvePackageOptions): string {\n const {\n packageName,\n includeSystemModules,\n baseFolderPath,\n allowSelfReference,\n getRealPath,\n useNodeJSResolver\n } = options;\n\n if (includeSystemModules && Import._builtInModules.has(packageName)) {\n return packageName;\n }\n\n const normalizedRootPath: string = (getRealPath || FileSystem.getRealPath)(baseFolderPath);\n\n if (allowSelfReference) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (ownPackage && ownPackage.packageName === packageName) {\n return ownPackage.packageRootPath;\n }\n }\n\n PackageName.parse(packageName); // Ensure the package name is valid and doesn't contain a path\n\n try {\n const resolvedPath: string = useNodeJSResolver\n ? require.resolve(`${packageName}/package.json`, {\n paths: [normalizedRootPath]\n })\n : // Append `/package.json` to ensure `resolve.sync` doesn't attempt to return a system package, and to avoid\n // having to mess with the `packageFilter` option.\n Resolve.sync(`${packageName}/package.json`, {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpathSync: getRealPath\n });\n\n const packagePath: string = path.dirname(resolvedPath);\n return packagePath;\n } catch (e: unknown) {\n throw new Error(`Cannot find package \"${packageName}\" from \"${baseFolderPath}\": ${e}.`);\n }\n }\n\n /**\n * Async version of {@link Import.resolvePackage}.\n */\n public static async resolvePackageAsync(options: IImportResolvePackageAsyncOptions): Promise<string> {\n const {\n packageName,\n includeSystemModules,\n baseFolderPath,\n allowSelfReference,\n getRealPath,\n getRealPathAsync\n } = options;\n\n if (includeSystemModules && Import._builtInModules.has(packageName)) {\n return packageName;\n }\n\n const normalizedRootPath: string = await (getRealPathAsync || getRealPath || FileSystem.getRealPathAsync)(\n baseFolderPath\n );\n\n if (allowSelfReference) {\n const ownPackage: IPackageDescriptor | undefined = Import._getPackageName(normalizedRootPath);\n if (ownPackage && ownPackage.packageName === packageName) {\n return ownPackage.packageRootPath;\n }\n }\n\n PackageName.parse(packageName); // Ensure the package name is valid and doesn't contain a path\n\n try {\n const resolvePromise: Promise<string> = new Promise(\n (resolve: (resolvedPath: string) => void, reject: (error: Error) => void) => {\n const realPathFn: RealpathFnType =\n getRealPathAsync || getRealPath\n ? (filePath: string, callback: (error: Error | null, resolvedPath?: string) => void) => {\n if (getRealPathAsync) {\n getRealPathAsync(filePath)\n .then((resolvedPath) => callback(null, resolvedPath))\n .catch((error) => callback(error));\n } else {\n try {\n const resolvedPath: string = getRealPath!(filePath);\n callback(null, resolvedPath);\n } catch (error: unknown) {\n callback(error as Error);\n }\n }\n }\n : undefined;\n\n Resolve.default(\n // Append `/package.json` to ensure `resolve` doesn't attempt to return a system package, and to avoid\n // having to mess with the `packageFilter` option.\n `${packageName}/package.json`,\n {\n basedir: normalizedRootPath,\n preserveSymlinks: false,\n realpath: realPathFn\n },\n (error: Error | null, resolvedPath?: string) => {\n if (error) {\n reject(error);\n } else {\n // Resolve docs state that either an error will be returned, or the resolved path.\n // In this case, the resolved path should always be populated.\n resolve(resolvedPath!);\n }\n }\n );\n }\n );\n const resolvedPath: string = await resolvePromise;\n\n const packagePath: string = path.dirname(resolvedPath);\n return packagePath;\n } catch (e: unknown) {\n throw new Error(`Cannot find package \"${packageName}\" from \"${baseFolderPath}\": ${e}`);\n }\n }\n\n private static _getPackageName(rootPath: string): IPackageDescriptor | undefined {\n const packageJsonPath: string | undefined =\n PackageJsonLookup.instance.tryGetPackageJsonFilePathFor(rootPath);\n if (packageJsonPath) {\n const packageJson: IPackageJson = PackageJsonLookup.instance.loadPackageJson(packageJsonPath);\n return {\n packageRootPath: path.dirname(packageJsonPath),\n packageName: packageJson.name\n };\n } else {\n return undefined;\n }\n }\n}\n"]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"JsonFile.d.ts","sourceRoot":"","sources":["../src/JsonFile.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,UAAU,EAAE,oBAAoB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EAAQ,KAAK,WAAW,EAAE,MAAM,QAAQ,CAAC;AAGhD;;;;;;;;GAQG;AAEH,MAAM,MAAM,UAAU,GAAG,GAAG,CAAC;AAE7B;;;;;;;;;;;;;;GAcG;AAEH,MAAM,MAAM,QAAQ,GAAG,IAAI,CAAC;AAE5B;;;;GAIG;AACH,oBAAY,UAAU;IACpB;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,WAAW;IAEjB;;;;;;;;;;;;;;;OAeG;IACH,gBAAgB,qBAAqB;IAErC;;;;;;;;;;;;;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AA8B,GACtC,MAAM;IAsDT;;;;;;OAMG;WACW,IAAI,CAChB,UAAU,EAAE,UAAU,EACtB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,oBAAyB,GACjC,OAAO;IA+CV;;OAEG;WACiB,SAAS,CAC3B,UAAU,EAAE,UAAU,EACtB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,OAAO,CAAC;IA+CnB;;;OAGG;WACW,0BAA0B,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI;IAKtE,OAAO,CAAC,MAAM,CAAC,2BAA2B;IAuB1C,OAAO,CAAC,MAAM,CAAC,cAAc;IA2B7B,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAmBvC,OAAO,CAAC,MAAM,CAAC,qBAAqB;CAoBrC"} |
+1
-1
@@ -39,3 +39,3 @@ "use strict"; | ||
| exports.JsonFile = exports.JsonSyntax = void 0; | ||
| const os = __importStar(require("os")); | ||
| const os = __importStar(require("node:os")); | ||
| const jju = __importStar(require("jju")); | ||
@@ -42,0 +42,0 @@ const Text_1 = require("./Text"); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"JsonFile.js","sourceRoot":"","sources":["../src/JsonFile.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,uCAAyB;AACzB,yCAA2B;AAG3B,iCAAgD;AAChD,6CAA0C;AAgC1C;;;;GAIG;AACH,IAAY,UAsDX;AAtDD,WAAY,UAAU;IACpB;;;;;;;;;;;;;;;;;OAiBG;IACH,+BAAiB,CAAA;IAEjB;;;;;;;;;;;;;;;OAeG;IACH,mDAAqC,CAAA;IAErC;;;;;;;;;;;;;OAaG;IACH,6BAAe,CAAA;AACjB,CAAC,EAtDW,UAAU,0BAAV,UAAU,QAsDrB;AAmGD,MAAM,gBAAgB,GAAW,MAAM,CAAC;AAExC;;;GAGG;AACH,MAAa,QAAQ;I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MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'os';\nimport * as jju from 'jju';\n\nimport type { JsonSchema, IJsonSchemaErrorInfo, IJsonSchemaValidateOptions } from './JsonSchema';\nimport { Text, type NewlineKind } from './Text';\nimport { FileSystem } from './FileSystem';\n\n/**\n * Represents a JSON-serializable object whose type has not been determined yet.\n *\n * @remarks\n *\n * This type is similar to `any`, except that it communicates that the object is serializable JSON.\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JsonObject = any;\n\n/**\n * The Rush Stack lint rules discourage usage of `null`. However, JSON parsers always return JavaScript's\n * `null` to keep the two syntaxes consistent. When creating interfaces that describe JSON structures,\n * use `JsonNull` to avoid triggering the lint rule. Do not use `JsonNull` for any other purpose.\n *\n * @remarks\n * If you are designing a new JSON file format, it's a good idea to avoid `null` entirely. In most cases\n * there are better representations that convey more information about an item that is unknown, omitted, or disabled.\n *\n * To understand why `null` is deprecated, please see the `@rushstack/eslint-plugin` documentation here:\n *\n * {@link https://www.npmjs.com/package/@rushstack/eslint-plugin#rushstackno-null}\n *\n * @public\n */\n// eslint-disable-next-line @rushstack/no-new-null\nexport type JsonNull = null;\n\n/**\n * Specifies the variant of JSON syntax to be used.\n *\n * @public\n */\nexport enum JsonSyntax {\n /**\n * Specifies the exact RFC 8259 format as implemented by the `JSON.parse()` system API.\n * This format was designed for machine generated inputs such as an HTTP payload.\n * It is not a recommend choice for human-authored files, because it does not support\n * code comments.\n *\n * @remarks\n *\n * A well-known quote from Douglas Crockford, the inventor of JSON:\n *\n * \"I removed comments from JSON because I saw people were using them to hold parsing directives,\n * a practice which would have destroyed interoperability. I know that the lack of comments makes\n * some people sad, but it shouldn't. Suppose you are using JSON to keep configuration files,\n * which you would like to annotate. Go ahead and insert all the comments you like.\n * Then pipe it through JSMin before handing it to your JSON parser.\"\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8259 | RFC 8259}\n */\n Strict = 'strict',\n\n /**\n * `JsonSyntax.JsonWithComments` is the recommended format for human-authored config files.\n * It is a minimal extension to `JsonSyntax.Strict` adding support for code comments\n * using `//` and `/*`.\n *\n * @remarks\n *\n * VS Code calls this format `jsonc`, but it should not be confused with unrelated file formats\n * and libraries that also use the name \"JSONC\".\n *\n * To fix VS Code syntax highlighting, add this setting:\n * `\"files.associations\": { \"*.json\": \"jsonc\" }`\n *\n * To fix GitHub syntax highlighting, add this to your `.gitattributes`:\n * `*.json linguist-language=JSON-with-Comments`\n */\n JsonWithComments = 'jsonWithComments',\n\n /**\n * JSON5 is a project that proposes a JSON-like format supplemented with ECMAScript 5.1\n * notations for objects, numbers, comments, and more.\n *\n * @remarks\n * Files using this format should use the `.json5` file extension instead of `.json`.\n *\n * JSON5 has substantial differences from JSON: object keys may be unquoted, trailing commas\n * are allowed, and strings may span multiple lines. Whereas {@link JsonSyntax.JsonWithComments} can\n * be cheaply converted to standard JSON by stripping comments, parsing JSON5 requires a\n * nontrivial algorithm that may not be easily available in some contexts or programming languages.\n *\n * @see {@link https://json5.org/ | JSON5 project website}\n */\n Json5 = 'json5'\n}\n\n/**\n * Options for {@link JsonFile.parseString}, {@link JsonFile.load}, and {@link JsonFile.loadAsync}.\n *\n * @public\n */\nexport interface IJsonFileParseOptions {\n /**\n * Specifies the variant of JSON syntax to be used.\n *\n * @defaultValue\n * {@link JsonSyntax.Json5}\n *\n * NOTE: This default will be changed to `JsonSyntax.JsonWithComments` in a future release.\n */\n jsonSyntax?: JsonSyntax;\n}\n\n/**\n * Options for {@link JsonFile.loadAndValidate} and {@link JsonFile.loadAndValidateAsync}\n *\n * @public\n */\nexport interface IJsonFileLoadAndValidateOptions extends IJsonFileParseOptions, IJsonSchemaValidateOptions {}\n\n/**\n * Options for {@link JsonFile.stringify}\n *\n * @public\n */\nexport interface IJsonFileStringifyOptions extends IJsonFileParseOptions {\n /**\n * If provided, the specified newline type will be used instead of the default `\\r\\n`.\n */\n newlineConversion?: NewlineKind;\n\n /**\n * By default, {@link JsonFile.stringify} validates that the object does not contain any\n * keys whose value is `undefined`. To disable this validation, set\n * {@link IJsonFileStringifyOptions.ignoreUndefinedValues} to `true`\n * which causes such keys to be silently discarded, consistent with the system `JSON.stringify()`.\n *\n * @remarks\n *\n * The JSON file format can represent `null` values ({@link JsonNull}) but not `undefined` values.\n * In ECMAScript code however, we generally avoid `null` and always represent empty states\n * as `undefined`, because it is the default value of missing/uninitialized variables.\n * (In practice, distinguishing \"null\" versus \"uninitialized\" has more drawbacks than benefits.)\n * This poses a problem when serializing ECMAScript objects that contain `undefined` members.\n * As a safeguard, {@link JsonFile} will report an error if any `undefined` values are encountered\n * during serialization. Set {@link IJsonFileStringifyOptions.ignoreUndefinedValues} to `true`\n * to disable this safeguard.\n */\n ignoreUndefinedValues?: boolean;\n\n /**\n * If true, then the \"jju\" library will be used to improve the text formatting.\n * Note that this is slightly slower than the native JSON.stringify() implementation.\n */\n prettyFormatting?: boolean;\n\n /**\n * If specified, this header will be prepended to the start of the file. The header must consist\n * of lines prefixed by \"//\" characters.\n * @remarks\n * When used with {@link IJsonFileSaveOptions.updateExistingFile}\n * or {@link JsonFile.updateString}, the header will ONLY be added for a newly created file.\n */\n headerComment?: string;\n}\n\n/**\n * Options for {@link JsonFile.save} and {@link JsonFile.saveAsync}.\n *\n * @public\n */\nexport interface IJsonFileSaveOptions extends IJsonFileStringifyOptions {\n /**\n * If there is an existing file, and the contents have not changed, then\n * don't write anything; this preserves the old timestamp.\n */\n onlyIfChanged?: boolean;\n\n /**\n * Creates the folder recursively using FileSystem.ensureFolder()\n * Defaults to false.\n */\n ensureFolderExists?: boolean;\n\n /**\n * If true, use the \"jju\" library to preserve the existing JSON formatting: The file will be loaded\n * from the target filename, the new content will be merged in (preserving whitespace and comments),\n * and then the file will be overwritten with the merged contents. If the target file does not exist,\n * then the file is saved normally.\n */\n updateExistingFile?: boolean;\n}\n\nconst DEFAULT_ENCODING: 'utf8' = 'utf8';\n\n/**\n * Utilities for reading/writing JSON files.\n * @public\n */\nexport class JsonFile {\n /**\n * @internal\n */\n public static _formatPathForError: (path: string) => string = (path: string) => path;\n\n /**\n * Loads a JSON file.\n */\n public static load(jsonFilename: string, options?: IJsonFileParseOptions): JsonObject {\n try {\n const contents: string = FileSystem.readFile(jsonFilename);\n const parseOptions: jju.ParseOptions = JsonFile._buildJjuParseOptions(options);\n return jju.parse(contents, parseOptions);\n } catch (error) {\n if (FileSystem.isNotExistError(error as Error)) {\n throw error;\n } else {\n throw new Error(\n `Error reading \"${JsonFile._formatPathForError(jsonFilename)}\":` +\n os.EOL +\n ` ${(error as Error).message}`\n );\n }\n }\n }\n\n /**\n * An async version of {@link JsonFile.load}.\n */\n public static async loadAsync(jsonFilename: string, options?: IJsonFileParseOptions): Promise<JsonObject> {\n try {\n const contents: string = await FileSystem.readFileAsync(jsonFilename);\n const parseOptions: jju.ParseOptions = JsonFile._buildJjuParseOptions(options);\n return jju.parse(contents, parseOptions);\n } catch (error) {\n if (FileSystem.isNotExistError(error as Error)) {\n throw error;\n } else {\n throw new Error(\n `Error reading \"${JsonFile._formatPathForError(jsonFilename)}\":` +\n os.EOL +\n ` ${(error as Error).message}`\n );\n }\n }\n }\n\n /**\n * Parses a JSON file's contents.\n */\n public static parseString(jsonContents: string, options?: IJsonFileParseOptions): JsonObject {\n const parseOptions: jju.ParseOptions = JsonFile._buildJjuParseOptions(options);\n return jju.parse(jsonContents, parseOptions);\n }\n\n /**\n * Loads a JSON file and validate its schema.\n */\n public static loadAndValidate(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n options?: IJsonFileLoadAndValidateOptions\n ): JsonObject {\n const jsonObject: JsonObject = JsonFile.load(jsonFilename, options);\n jsonSchema.validateObject(jsonObject, jsonFilename, options);\n\n return jsonObject;\n }\n\n /**\n * An async version of {@link JsonFile.loadAndValidate}.\n */\n public static async loadAndValidateAsync(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n options?: IJsonFileLoadAndValidateOptions\n ): Promise<JsonObject> {\n const jsonObject: JsonObject = await JsonFile.loadAsync(jsonFilename, options);\n jsonSchema.validateObject(jsonObject, jsonFilename, options);\n\n return jsonObject;\n }\n\n /**\n * Loads a JSON file and validate its schema, reporting errors using a callback\n * @remarks\n * See JsonSchema.validateObjectWithCallback() for more info.\n */\n public static loadAndValidateWithCallback(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void,\n options?: IJsonFileLoadAndValidateOptions\n ): JsonObject {\n const jsonObject: JsonObject = JsonFile.load(jsonFilename, options);\n jsonSchema.validateObjectWithCallback(jsonObject, errorCallback);\n\n return jsonObject;\n }\n\n /**\n * An async version of {@link JsonFile.loadAndValidateWithCallback}.\n */\n public static async loadAndValidateWithCallbackAsync(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void,\n options?: IJsonFileLoadAndValidateOptions\n ): Promise<JsonObject> {\n const jsonObject: JsonObject = await JsonFile.loadAsync(jsonFilename, options);\n jsonSchema.validateObjectWithCallback(jsonObject, errorCallback);\n\n return jsonObject;\n }\n\n /**\n * Serializes the specified JSON object to a string buffer.\n * @param jsonObject - the object to be serialized\n * @param options - other settings that control serialization\n * @returns a JSON string, with newlines, and indented with two spaces\n */\n public static stringify(jsonObject: JsonObject, options?: IJsonFileStringifyOptions): string {\n return JsonFile.updateString('', jsonObject, options);\n }\n\n /**\n * Serializes the specified JSON object to a string buffer.\n * @param previousJson - the previous JSON string, which will be updated\n * @param newJsonObject - the object to be serialized\n * @param options - other settings that control serialization\n * @returns a JSON string, with newlines, and indented with two spaces\n */\n public static updateString(\n previousJson: string,\n newJsonObject: JsonObject,\n options: IJsonFileStringifyOptions = {}\n ): string {\n if (!options.ignoreUndefinedValues) {\n // Standard handling of `undefined` in JSON stringification is to discard the key.\n JsonFile.validateNoUndefinedMembers(newJsonObject);\n }\n\n let explicitMode: 'json5' | 'json' | 'cjson' | undefined = undefined;\n switch (options.jsonSyntax) {\n case JsonSyntax.Strict:\n explicitMode = 'json';\n break;\n case JsonSyntax.JsonWithComments:\n explicitMode = 'cjson';\n break;\n case JsonSyntax.Json5:\n explicitMode = 'json5';\n break;\n }\n\n let stringified: string;\n\n if (previousJson !== '') {\n // NOTE: We don't use mode=json here because comments aren't allowed by strict JSON\n stringified = jju.update(previousJson, newJsonObject, {\n mode: explicitMode ?? JsonSyntax.Json5,\n indent: 2\n });\n } else if (options.prettyFormatting) {\n stringified = jju.stringify(newJsonObject, {\n mode: explicitMode ?? 'json',\n indent: 2\n });\n\n if (options.headerComment !== undefined) {\n stringified = JsonFile._formatJsonHeaderComment(options.headerComment) + stringified;\n }\n } else {\n stringified = JSON.stringify(newJsonObject, undefined, 2);\n\n if (options.headerComment !== undefined) {\n stringified = JsonFile._formatJsonHeaderComment(options.headerComment) + stringified;\n }\n }\n\n // Add the trailing newline\n stringified = Text.ensureTrailingNewline(stringified);\n\n if (options.newlineConversion) {\n stringified = Text.convertTo(stringified, options.newlineConversion);\n }\n\n return stringified;\n }\n\n /**\n * Saves the file to disk. Returns false if nothing was written due to options.onlyIfChanged.\n * @param jsonObject - the object to be saved\n * @param jsonFilename - the file path to write\n * @param options - other settings that control how the file is saved\n * @returns false if ISaveJsonFileOptions.onlyIfChanged didn't save anything; true otherwise\n */\n public static save(\n jsonObject: JsonObject,\n jsonFilename: string,\n options: IJsonFileSaveOptions = {}\n ): boolean {\n // Do we need to read the previous file contents?\n let oldBuffer: Buffer | undefined = undefined;\n if (options.updateExistingFile || options.onlyIfChanged) {\n try {\n oldBuffer = FileSystem.readFileToBuffer(jsonFilename);\n } catch (error) {\n if (!FileSystem.isNotExistError(error as Error)) {\n throw error;\n }\n }\n }\n\n let jsonToUpdate: string = '';\n if (options.updateExistingFile && oldBuffer) {\n jsonToUpdate = oldBuffer.toString(DEFAULT_ENCODING);\n }\n\n const newJson: string = JsonFile.updateString(jsonToUpdate, jsonObject, options);\n\n const newBuffer: Buffer = Buffer.from(newJson, DEFAULT_ENCODING);\n\n if (options.onlyIfChanged) {\n // Has the file changed?\n if (oldBuffer && Buffer.compare(newBuffer, oldBuffer) === 0) {\n // Nothing has changed, so don't touch the file\n return false;\n }\n }\n\n FileSystem.writeFile(jsonFilename, newBuffer, {\n ensureFolderExists: options.ensureFolderExists\n });\n\n // TEST CODE: Used to verify that onlyIfChanged isn't broken by a hidden transformation during saving.\n /*\n const oldBuffer2: Buffer = FileSystem.readFileToBuffer(jsonFilename);\n if (Buffer.compare(buffer, oldBuffer2) !== 0) {\n console.log('new:' + buffer.toString('hex'));\n console.log('old:' + oldBuffer2.toString('hex'));\n\n throw new Error('onlyIfChanged logic is broken');\n }\n */\n return true;\n }\n\n /**\n * An async version of {@link JsonFile.save}.\n */\n public static async saveAsync(\n jsonObject: JsonObject,\n jsonFilename: string,\n options: IJsonFileSaveOptions = {}\n ): Promise<boolean> {\n // Do we need to read the previous file contents?\n let oldBuffer: Buffer | undefined = undefined;\n if (options.updateExistingFile || options.onlyIfChanged) {\n try {\n oldBuffer = await FileSystem.readFileToBufferAsync(jsonFilename);\n } catch (error) {\n if (!FileSystem.isNotExistError(error as Error)) {\n throw error;\n }\n }\n }\n\n let jsonToUpdate: string = '';\n if (options.updateExistingFile && oldBuffer) {\n jsonToUpdate = oldBuffer.toString(DEFAULT_ENCODING);\n }\n\n const newJson: string = JsonFile.updateString(jsonToUpdate, jsonObject, options);\n\n const newBuffer: Buffer = Buffer.from(newJson, DEFAULT_ENCODING);\n\n if (options.onlyIfChanged) {\n // Has the file changed?\n if (oldBuffer && Buffer.compare(newBuffer, oldBuffer) === 0) {\n // Nothing has changed, so don't touch the file\n return false;\n }\n }\n\n await FileSystem.writeFileAsync(jsonFilename, newBuffer, {\n ensureFolderExists: options.ensureFolderExists\n });\n\n // TEST CODE: Used to verify that onlyIfChanged isn't broken by a hidden transformation during saving.\n /*\n const oldBuffer2: Buffer = await FileSystem.readFileToBufferAsync(jsonFilename);\n if (Buffer.compare(buffer, oldBuffer2) !== 0) {\n console.log('new:' + buffer.toString('hex'));\n console.log('old:' + oldBuffer2.toString('hex'));\n\n throw new Error('onlyIfChanged logic is broken');\n }\n */\n return true;\n }\n\n /**\n * Used to validate a data structure before writing. Reports an error if there\n * are any undefined members.\n */\n public static validateNoUndefinedMembers(jsonObject: JsonObject): void {\n return JsonFile._validateNoUndefinedMembers(jsonObject, []);\n }\n\n // Private implementation of validateNoUndefinedMembers()\n private static _validateNoUndefinedMembers(jsonObject: JsonObject, keyPath: string[]): void {\n if (!jsonObject) {\n return;\n }\n if (typeof jsonObject === 'object') {\n for (const key of Object.keys(jsonObject)) {\n keyPath.push(key);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value: any = jsonObject[key];\n if (value === undefined) {\n const fullPath: string = JsonFile._formatKeyPath(keyPath);\n throw new Error(`The value for ${fullPath} is \"undefined\" and cannot be serialized as JSON`);\n }\n\n JsonFile._validateNoUndefinedMembers(value, keyPath);\n keyPath.pop();\n }\n }\n }\n\n // Given this input: ['items', '4', 'syntax', 'parameters', 'string \"with\" symbols\", 'type']\n // Return this string: items[4].syntax.parameters[\"string \\\"with\\\" symbols\"].type\n private static _formatKeyPath(keyPath: string[]): string {\n let result: string = '';\n\n for (const key of keyPath) {\n if (/^[0-9]+$/.test(key)) {\n // It's an integer, so display like this: parent[123]\n result += `[${key}]`;\n } else if (/^[a-z_][a-z_0-9]*$/i.test(key)) {\n // It's an alphanumeric identifier, so display like this: parent.name\n if (result) {\n result += '.';\n }\n result += `${key}`;\n } else {\n // It's a freeform string, so display like this: parent[\"A path: \\\"C:\\\\file\\\"\"]\n\n // Convert this: A path: \"C:\\file\"\n // To this: A path: \\\"C:\\\\file\\\"\n const escapedKey: string = key\n .replace(/[\\\\]/g, '\\\\\\\\') // escape backslashes\n .replace(/[\"]/g, '\\\\'); // escape quotes\n result += `[\"${escapedKey}\"]`;\n }\n }\n return result;\n }\n\n private static _formatJsonHeaderComment(headerComment: string): string {\n if (headerComment === '') {\n return '';\n }\n const lines: string[] = headerComment.split('\\n');\n const result: string[] = [];\n for (const line of lines) {\n if (!/^\\s*$/.test(line) && !/^\\s*\\/\\//.test(line)) {\n throw new Error(\n 'The headerComment lines must be blank or start with the \"//\" prefix.\\n' +\n 'Invalid line' +\n JSON.stringify(line)\n );\n }\n result.push(Text.replaceAll(line, '\\r', ''));\n }\n return lines.join('\\n') + '\\n';\n }\n\n private static _buildJjuParseOptions(options: IJsonFileParseOptions = {}): jju.ParseOptions {\n const parseOptions: jju.ParseOptions = {\n reserved_keys: 'replace'\n };\n\n switch (options.jsonSyntax) {\n case JsonSyntax.Strict:\n parseOptions.mode = 'json';\n break;\n case JsonSyntax.JsonWithComments:\n parseOptions.mode = 'cjson';\n break;\n case JsonSyntax.Json5:\n default:\n parseOptions.mode = 'json5';\n break;\n }\n\n return parseOptions;\n }\n}\n"]} | ||
| {"version":3,"file":"JsonFile.js","sourceRoot":"","sources":["../src/JsonFile.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,4CAA8B;AAE9B,yCAA2B;AAG3B,iCAAgD;AAChD,6CAA0C;AAgC1C;;;;GAIG;AACH,IAAY,UAsDX;AAtDD,WAAY,UAAU;IACpB;;;;;;;;;;;;;;;;;OAiBG;IACH,+BAAiB,CAAA;IAEjB;;;;;;;;;;;;;;;OAeG;IACH,mDAAqC,CAAA;IAErC;;;;;;;;;;;;;OAaG;IACH,6BAAe,CAAA;AACjB,CAAC,EAtDW,UAAU,0BAAV,UAAU,QAsDrB;AAmGD,MAAM,gBAAgB,GAAW,MAAM,CAAC;AAExC;;;GAGG;AACH,MAAa,QAAQ;IAMnB;;OAEG;IACI,MAAM,CAAC,IAAI,CAAC,YAAoB,EAAE,OAA+B;QACtE,IAAI,CAAC;YACH,MAAM,QAAQ,GAAW,uBAAU,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC3D,MAAM,YAAY,GAAqB,QAAQ,CAAC,qBAA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;YACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClD,MAAM,IAAI,KAAK,CACb,wEAAwE;oBACtE,cAAc;oBACd,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CACvB,CAAC;YACJ,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,WAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjC,CAAC;IAEO,MAAM,CAAC,qBAAqB,CAAC,UAAiC,EAAE;QACtE,MAAM,YAAY,GAAqB;YACrC,aAAa,EAAE,SAAS;SACzB,CAAC;QAEF,QAAQ,OAAO,CAAC,UAAU,EAAE,CAAC;YAC3B,KAAK,UAAU,CAAC,MAAM;gBACpB,YAAY,CAAC,IAAI,GAAG,MAAM,CAAC;gBAC3B,MAAM;YACR,KAAK,UAAU,CAAC,gBAAgB;gBAC9B,YAAY,CAAC,IAAI,GAAG,OAAO,CAAC;gBAC5B,MAAM;YACR,KAAK,UAAU,CAAC,KAAK,CAAC;YACtB;gBACE,YAAY,CAAC,IAAI,GAAG,OAAO,CAAC;gBAC5B,MAAM;QACV,CAAC;QAED,OAAO,YAAY,CAAC;IACtB,CAAC;;AAhZH,4BAiZC;AAhZC;;GAEG;AACW,4BAAmB,GAA6B,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'node:os';\n\nimport * as jju from 'jju';\n\nimport type { JsonSchema, IJsonSchemaErrorInfo, IJsonSchemaValidateOptions } from './JsonSchema';\nimport { Text, type NewlineKind } from './Text';\nimport { FileSystem } from './FileSystem';\n\n/**\n * Represents a JSON-serializable object whose type has not been determined yet.\n *\n * @remarks\n *\n * This type is similar to `any`, except that it communicates that the object is serializable JSON.\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JsonObject = any;\n\n/**\n * The Rush Stack lint rules discourage usage of `null`. However, JSON parsers always return JavaScript's\n * `null` to keep the two syntaxes consistent. When creating interfaces that describe JSON structures,\n * use `JsonNull` to avoid triggering the lint rule. Do not use `JsonNull` for any other purpose.\n *\n * @remarks\n * If you are designing a new JSON file format, it's a good idea to avoid `null` entirely. In most cases\n * there are better representations that convey more information about an item that is unknown, omitted, or disabled.\n *\n * To understand why `null` is deprecated, please see the `@rushstack/eslint-plugin` documentation here:\n *\n * {@link https://www.npmjs.com/package/@rushstack/eslint-plugin#rushstackno-null}\n *\n * @public\n */\n// eslint-disable-next-line @rushstack/no-new-null\nexport type JsonNull = null;\n\n/**\n * Specifies the variant of JSON syntax to be used.\n *\n * @public\n */\nexport enum JsonSyntax {\n /**\n * Specifies the exact RFC 8259 format as implemented by the `JSON.parse()` system API.\n * This format was designed for machine generated inputs such as an HTTP payload.\n * It is not a recommend choice for human-authored files, because it does not support\n * code comments.\n *\n * @remarks\n *\n * A well-known quote from Douglas Crockford, the inventor of JSON:\n *\n * \"I removed comments from JSON because I saw people were using them to hold parsing directives,\n * a practice which would have destroyed interoperability. I know that the lack of comments makes\n * some people sad, but it shouldn't. Suppose you are using JSON to keep configuration files,\n * which you would like to annotate. Go ahead and insert all the comments you like.\n * Then pipe it through JSMin before handing it to your JSON parser.\"\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8259 | RFC 8259}\n */\n Strict = 'strict',\n\n /**\n * `JsonSyntax.JsonWithComments` is the recommended format for human-authored config files.\n * It is a minimal extension to `JsonSyntax.Strict` adding support for code comments\n * using `//` and `/*`.\n *\n * @remarks\n *\n * VS Code calls this format `jsonc`, but it should not be confused with unrelated file formats\n * and libraries that also use the name \"JSONC\".\n *\n * To fix VS Code syntax highlighting, add this setting:\n * `\"files.associations\": { \"*.json\": \"jsonc\" }`\n *\n * To fix GitHub syntax highlighting, add this to your `.gitattributes`:\n * `*.json linguist-language=JSON-with-Comments`\n */\n JsonWithComments = 'jsonWithComments',\n\n /**\n * JSON5 is a project that proposes a JSON-like format supplemented with ECMAScript 5.1\n * notations for objects, numbers, comments, and more.\n *\n * @remarks\n * Files using this format should use the `.json5` file extension instead of `.json`.\n *\n * JSON5 has substantial differences from JSON: object keys may be unquoted, trailing commas\n * are allowed, and strings may span multiple lines. Whereas {@link JsonSyntax.JsonWithComments} can\n * be cheaply converted to standard JSON by stripping comments, parsing JSON5 requires a\n * nontrivial algorithm that may not be easily available in some contexts or programming languages.\n *\n * @see {@link https://json5.org/ | JSON5 project website}\n */\n Json5 = 'json5'\n}\n\n/**\n * Options for {@link JsonFile.parseString}, {@link JsonFile.load}, and {@link JsonFile.loadAsync}.\n *\n * @public\n */\nexport interface IJsonFileParseOptions {\n /**\n * Specifies the variant of JSON syntax to be used.\n *\n * @defaultValue\n * {@link JsonSyntax.Json5}\n *\n * NOTE: This default will be changed to `JsonSyntax.JsonWithComments` in a future release.\n */\n jsonSyntax?: JsonSyntax;\n}\n\n/**\n * Options for {@link JsonFile.loadAndValidate} and {@link JsonFile.loadAndValidateAsync}\n *\n * @public\n */\nexport interface IJsonFileLoadAndValidateOptions extends IJsonFileParseOptions, IJsonSchemaValidateOptions {}\n\n/**\n * Options for {@link JsonFile.stringify}\n *\n * @public\n */\nexport interface IJsonFileStringifyOptions extends IJsonFileParseOptions {\n /**\n * If provided, the specified newline type will be used instead of the default `\\r\\n`.\n */\n newlineConversion?: NewlineKind;\n\n /**\n * By default, {@link JsonFile.stringify} validates that the object does not contain any\n * keys whose value is `undefined`. To disable this validation, set\n * {@link IJsonFileStringifyOptions.ignoreUndefinedValues} to `true`\n * which causes such keys to be silently discarded, consistent with the system `JSON.stringify()`.\n *\n * @remarks\n *\n * The JSON file format can represent `null` values ({@link JsonNull}) but not `undefined` values.\n * In ECMAScript code however, we generally avoid `null` and always represent empty states\n * as `undefined`, because it is the default value of missing/uninitialized variables.\n * (In practice, distinguishing \"null\" versus \"uninitialized\" has more drawbacks than benefits.)\n * This poses a problem when serializing ECMAScript objects that contain `undefined` members.\n * As a safeguard, {@link JsonFile} will report an error if any `undefined` values are encountered\n * during serialization. Set {@link IJsonFileStringifyOptions.ignoreUndefinedValues} to `true`\n * to disable this safeguard.\n */\n ignoreUndefinedValues?: boolean;\n\n /**\n * If true, then the \"jju\" library will be used to improve the text formatting.\n * Note that this is slightly slower than the native JSON.stringify() implementation.\n */\n prettyFormatting?: boolean;\n\n /**\n * If specified, this header will be prepended to the start of the file. The header must consist\n * of lines prefixed by \"//\" characters.\n * @remarks\n * When used with {@link IJsonFileSaveOptions.updateExistingFile}\n * or {@link JsonFile.updateString}, the header will ONLY be added for a newly created file.\n */\n headerComment?: string;\n}\n\n/**\n * Options for {@link JsonFile.save} and {@link JsonFile.saveAsync}.\n *\n * @public\n */\nexport interface IJsonFileSaveOptions extends IJsonFileStringifyOptions {\n /**\n * If there is an existing file, and the contents have not changed, then\n * don't write anything; this preserves the old timestamp.\n */\n onlyIfChanged?: boolean;\n\n /**\n * Creates the folder recursively using FileSystem.ensureFolder()\n * Defaults to false.\n */\n ensureFolderExists?: boolean;\n\n /**\n * If true, use the \"jju\" library to preserve the existing JSON formatting: The file will be loaded\n * from the target filename, the new content will be merged in (preserving whitespace and comments),\n * and then the file will be overwritten with the merged contents. If the target file does not exist,\n * then the file is saved normally.\n */\n updateExistingFile?: boolean;\n}\n\nconst DEFAULT_ENCODING: 'utf8' = 'utf8';\n\n/**\n * Utilities for reading/writing JSON files.\n * @public\n */\nexport class JsonFile {\n /**\n * @internal\n */\n public static _formatPathForError: (path: string) => string = (path: string) => path;\n\n /**\n * Loads a JSON file.\n */\n public static load(jsonFilename: string, options?: IJsonFileParseOptions): JsonObject {\n try {\n const contents: string = FileSystem.readFile(jsonFilename);\n const parseOptions: jju.ParseOptions = JsonFile._buildJjuParseOptions(options);\n return jju.parse(contents, parseOptions);\n } catch (error) {\n if (FileSystem.isNotExistError(error as Error)) {\n throw error;\n } else {\n throw new Error(\n `Error reading \"${JsonFile._formatPathForError(jsonFilename)}\":` +\n os.EOL +\n ` ${(error as Error).message}`\n );\n }\n }\n }\n\n /**\n * An async version of {@link JsonFile.load}.\n */\n public static async loadAsync(jsonFilename: string, options?: IJsonFileParseOptions): Promise<JsonObject> {\n try {\n const contents: string = await FileSystem.readFileAsync(jsonFilename);\n const parseOptions: jju.ParseOptions = JsonFile._buildJjuParseOptions(options);\n return jju.parse(contents, parseOptions);\n } catch (error) {\n if (FileSystem.isNotExistError(error as Error)) {\n throw error;\n } else {\n throw new Error(\n `Error reading \"${JsonFile._formatPathForError(jsonFilename)}\":` +\n os.EOL +\n ` ${(error as Error).message}`\n );\n }\n }\n }\n\n /**\n * Parses a JSON file's contents.\n */\n public static parseString(jsonContents: string, options?: IJsonFileParseOptions): JsonObject {\n const parseOptions: jju.ParseOptions = JsonFile._buildJjuParseOptions(options);\n return jju.parse(jsonContents, parseOptions);\n }\n\n /**\n * Loads a JSON file and validate its schema.\n */\n public static loadAndValidate(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n options?: IJsonFileLoadAndValidateOptions\n ): JsonObject {\n const jsonObject: JsonObject = JsonFile.load(jsonFilename, options);\n jsonSchema.validateObject(jsonObject, jsonFilename, options);\n\n return jsonObject;\n }\n\n /**\n * An async version of {@link JsonFile.loadAndValidate}.\n */\n public static async loadAndValidateAsync(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n options?: IJsonFileLoadAndValidateOptions\n ): Promise<JsonObject> {\n const jsonObject: JsonObject = await JsonFile.loadAsync(jsonFilename, options);\n jsonSchema.validateObject(jsonObject, jsonFilename, options);\n\n return jsonObject;\n }\n\n /**\n * Loads a JSON file and validate its schema, reporting errors using a callback\n * @remarks\n * See JsonSchema.validateObjectWithCallback() for more info.\n */\n public static loadAndValidateWithCallback(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void,\n options?: IJsonFileLoadAndValidateOptions\n ): JsonObject {\n const jsonObject: JsonObject = JsonFile.load(jsonFilename, options);\n jsonSchema.validateObjectWithCallback(jsonObject, errorCallback);\n\n return jsonObject;\n }\n\n /**\n * An async version of {@link JsonFile.loadAndValidateWithCallback}.\n */\n public static async loadAndValidateWithCallbackAsync(\n jsonFilename: string,\n jsonSchema: JsonSchema,\n errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void,\n options?: IJsonFileLoadAndValidateOptions\n ): Promise<JsonObject> {\n const jsonObject: JsonObject = await JsonFile.loadAsync(jsonFilename, options);\n jsonSchema.validateObjectWithCallback(jsonObject, errorCallback);\n\n return jsonObject;\n }\n\n /**\n * Serializes the specified JSON object to a string buffer.\n * @param jsonObject - the object to be serialized\n * @param options - other settings that control serialization\n * @returns a JSON string, with newlines, and indented with two spaces\n */\n public static stringify(jsonObject: JsonObject, options?: IJsonFileStringifyOptions): string {\n return JsonFile.updateString('', jsonObject, options);\n }\n\n /**\n * Serializes the specified JSON object to a string buffer.\n * @param previousJson - the previous JSON string, which will be updated\n * @param newJsonObject - the object to be serialized\n * @param options - other settings that control serialization\n * @returns a JSON string, with newlines, and indented with two spaces\n */\n public static updateString(\n previousJson: string,\n newJsonObject: JsonObject,\n options: IJsonFileStringifyOptions = {}\n ): string {\n if (!options.ignoreUndefinedValues) {\n // Standard handling of `undefined` in JSON stringification is to discard the key.\n JsonFile.validateNoUndefinedMembers(newJsonObject);\n }\n\n let explicitMode: 'json5' | 'json' | 'cjson' | undefined = undefined;\n switch (options.jsonSyntax) {\n case JsonSyntax.Strict:\n explicitMode = 'json';\n break;\n case JsonSyntax.JsonWithComments:\n explicitMode = 'cjson';\n break;\n case JsonSyntax.Json5:\n explicitMode = 'json5';\n break;\n }\n\n let stringified: string;\n\n if (previousJson !== '') {\n // NOTE: We don't use mode=json here because comments aren't allowed by strict JSON\n stringified = jju.update(previousJson, newJsonObject, {\n mode: explicitMode ?? JsonSyntax.Json5,\n indent: 2\n });\n } else if (options.prettyFormatting) {\n stringified = jju.stringify(newJsonObject, {\n mode: explicitMode ?? 'json',\n indent: 2\n });\n\n if (options.headerComment !== undefined) {\n stringified = JsonFile._formatJsonHeaderComment(options.headerComment) + stringified;\n }\n } else {\n stringified = JSON.stringify(newJsonObject, undefined, 2);\n\n if (options.headerComment !== undefined) {\n stringified = JsonFile._formatJsonHeaderComment(options.headerComment) + stringified;\n }\n }\n\n // Add the trailing newline\n stringified = Text.ensureTrailingNewline(stringified);\n\n if (options.newlineConversion) {\n stringified = Text.convertTo(stringified, options.newlineConversion);\n }\n\n return stringified;\n }\n\n /**\n * Saves the file to disk. Returns false if nothing was written due to options.onlyIfChanged.\n * @param jsonObject - the object to be saved\n * @param jsonFilename - the file path to write\n * @param options - other settings that control how the file is saved\n * @returns false if ISaveJsonFileOptions.onlyIfChanged didn't save anything; true otherwise\n */\n public static save(\n jsonObject: JsonObject,\n jsonFilename: string,\n options: IJsonFileSaveOptions = {}\n ): boolean {\n // Do we need to read the previous file contents?\n let oldBuffer: Buffer | undefined = undefined;\n if (options.updateExistingFile || options.onlyIfChanged) {\n try {\n oldBuffer = FileSystem.readFileToBuffer(jsonFilename);\n } catch (error) {\n if (!FileSystem.isNotExistError(error as Error)) {\n throw error;\n }\n }\n }\n\n let jsonToUpdate: string = '';\n if (options.updateExistingFile && oldBuffer) {\n jsonToUpdate = oldBuffer.toString(DEFAULT_ENCODING);\n }\n\n const newJson: string = JsonFile.updateString(jsonToUpdate, jsonObject, options);\n\n const newBuffer: Buffer = Buffer.from(newJson, DEFAULT_ENCODING);\n\n if (options.onlyIfChanged) {\n // Has the file changed?\n if (oldBuffer && Buffer.compare(newBuffer, oldBuffer) === 0) {\n // Nothing has changed, so don't touch the file\n return false;\n }\n }\n\n FileSystem.writeFile(jsonFilename, newBuffer, {\n ensureFolderExists: options.ensureFolderExists\n });\n\n // TEST CODE: Used to verify that onlyIfChanged isn't broken by a hidden transformation during saving.\n /*\n const oldBuffer2: Buffer = FileSystem.readFileToBuffer(jsonFilename);\n if (Buffer.compare(buffer, oldBuffer2) !== 0) {\n console.log('new:' + buffer.toString('hex'));\n console.log('old:' + oldBuffer2.toString('hex'));\n\n throw new Error('onlyIfChanged logic is broken');\n }\n */\n return true;\n }\n\n /**\n * An async version of {@link JsonFile.save}.\n */\n public static async saveAsync(\n jsonObject: JsonObject,\n jsonFilename: string,\n options: IJsonFileSaveOptions = {}\n ): Promise<boolean> {\n // Do we need to read the previous file contents?\n let oldBuffer: Buffer | undefined = undefined;\n if (options.updateExistingFile || options.onlyIfChanged) {\n try {\n oldBuffer = await FileSystem.readFileToBufferAsync(jsonFilename);\n } catch (error) {\n if (!FileSystem.isNotExistError(error as Error)) {\n throw error;\n }\n }\n }\n\n let jsonToUpdate: string = '';\n if (options.updateExistingFile && oldBuffer) {\n jsonToUpdate = oldBuffer.toString(DEFAULT_ENCODING);\n }\n\n const newJson: string = JsonFile.updateString(jsonToUpdate, jsonObject, options);\n\n const newBuffer: Buffer = Buffer.from(newJson, DEFAULT_ENCODING);\n\n if (options.onlyIfChanged) {\n // Has the file changed?\n if (oldBuffer && Buffer.compare(newBuffer, oldBuffer) === 0) {\n // Nothing has changed, so don't touch the file\n return false;\n }\n }\n\n await FileSystem.writeFileAsync(jsonFilename, newBuffer, {\n ensureFolderExists: options.ensureFolderExists\n });\n\n // TEST CODE: Used to verify that onlyIfChanged isn't broken by a hidden transformation during saving.\n /*\n const oldBuffer2: Buffer = await FileSystem.readFileToBufferAsync(jsonFilename);\n if (Buffer.compare(buffer, oldBuffer2) !== 0) {\n console.log('new:' + buffer.toString('hex'));\n console.log('old:' + oldBuffer2.toString('hex'));\n\n throw new Error('onlyIfChanged logic is broken');\n }\n */\n return true;\n }\n\n /**\n * Used to validate a data structure before writing. Reports an error if there\n * are any undefined members.\n */\n public static validateNoUndefinedMembers(jsonObject: JsonObject): void {\n return JsonFile._validateNoUndefinedMembers(jsonObject, []);\n }\n\n // Private implementation of validateNoUndefinedMembers()\n private static _validateNoUndefinedMembers(jsonObject: JsonObject, keyPath: string[]): void {\n if (!jsonObject) {\n return;\n }\n if (typeof jsonObject === 'object') {\n for (const key of Object.keys(jsonObject)) {\n keyPath.push(key);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value: any = jsonObject[key];\n if (value === undefined) {\n const fullPath: string = JsonFile._formatKeyPath(keyPath);\n throw new Error(`The value for ${fullPath} is \"undefined\" and cannot be serialized as JSON`);\n }\n\n JsonFile._validateNoUndefinedMembers(value, keyPath);\n keyPath.pop();\n }\n }\n }\n\n // Given this input: ['items', '4', 'syntax', 'parameters', 'string \"with\" symbols\", 'type']\n // Return this string: items[4].syntax.parameters[\"string \\\"with\\\" symbols\"].type\n private static _formatKeyPath(keyPath: string[]): string {\n let result: string = '';\n\n for (const key of keyPath) {\n if (/^[0-9]+$/.test(key)) {\n // It's an integer, so display like this: parent[123]\n result += `[${key}]`;\n } else if (/^[a-z_][a-z_0-9]*$/i.test(key)) {\n // It's an alphanumeric identifier, so display like this: parent.name\n if (result) {\n result += '.';\n }\n result += `${key}`;\n } else {\n // It's a freeform string, so display like this: parent[\"A path: \\\"C:\\\\file\\\"\"]\n\n // Convert this: A path: \"C:\\file\"\n // To this: A path: \\\"C:\\\\file\\\"\n const escapedKey: string = key\n .replace(/[\\\\]/g, '\\\\\\\\') // escape backslashes\n .replace(/[\"]/g, '\\\\'); // escape quotes\n result += `[\"${escapedKey}\"]`;\n }\n }\n return result;\n }\n\n private static _formatJsonHeaderComment(headerComment: string): string {\n if (headerComment === '') {\n return '';\n }\n const lines: string[] = headerComment.split('\\n');\n const result: string[] = [];\n for (const line of lines) {\n if (!/^\\s*$/.test(line) && !/^\\s*\\/\\//.test(line)) {\n throw new Error(\n 'The headerComment lines must be blank or start with the \"//\" prefix.\\n' +\n 'Invalid line' +\n JSON.stringify(line)\n );\n }\n result.push(Text.replaceAll(line, '\\r', ''));\n }\n return lines.join('\\n') + '\\n';\n }\n\n private static _buildJjuParseOptions(options: IJsonFileParseOptions = {}): jju.ParseOptions {\n const parseOptions: jju.ParseOptions = {\n reserved_keys: 'replace'\n };\n\n switch (options.jsonSyntax) {\n case JsonSyntax.Strict:\n parseOptions.mode = 'json';\n break;\n case JsonSyntax.JsonWithComments:\n parseOptions.mode = 'cjson';\n break;\n case JsonSyntax.Json5:\n default:\n parseOptions.mode = 'json5';\n break;\n }\n\n return parseOptions;\n }\n}\n"]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"JsonSchema.d.ts","sourceRoot":"","sources":["../src/JsonSchema.ts"],"names":[],"mappings":"AAOA,OAAO,EAAY,KAAK,UAAU,EAAE,MAAM,YAAY,CAAC;AAavD;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG,UAAU,GAAG,UAAU,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,uBAAuB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IAChE;;OAEG;IACH,IAAI,EAAE,CAAC,SAAS,MAAM,GAAG,QAAQ,GAAG,CAAC,SAAS,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;IAExE;;;;OAIG;IACH,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,oCAAoC;IACnD;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA2B,SAAQ,oCAAoC;IACtF;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;;;OAWG;IACH,gBAAgB,CAAC,EAAE,UAAU,EAAE,CAAC;IA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;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG,sBAAsB,CAAC;AAoBlE;;;;;;;;GAQG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,iBAAiB,CAAoB;IAC7C,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,UAAU,CAA2C;IAC7D,OAAO,CAAC,aAAa,CAAqC;IAC1D,OAAO,CAAC,cAAc,CAA4C;IAClE,OAAO,CAAC,cAAc,CAEI;IAE1B,OAAO;IAEP;;;;;OAKG;WACW,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,0BAA0B,GAAG,UAAU;IAmB1F;;OAEG;WACW,gBAAgB,CAC5B,YAAY,EAAE,UAAU,EACxB,OAAO,CAAC,EAAE,4BAA4B,GACrC,UAAU;IAab,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAuCvC;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,mBAAmB;IAIlC;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,yBAAyB;IAiBxC;;;;;OAKG;IACH,IAAW,SAAS,IAAI,MAAM,CAc7B;IAED;;;;OAIG;IACI,cAAc,IAAI,IAAI;IA2D7B;;;;;;;OAOG;IACI,cAAc,CACnB,UAAU,EAAE,UAAU,EACtB,iBAAiB,EAAE,MAAM,EACzB,OAAO,CAAC,EAAE,0BAA0B,GACnC,IAAI;IAYP;;;OAGG;IACI,0BAA0B,CAC/B,UAAU,EAAE,UAAU,EACtB,aAAa,EAAE,CAAC,SAAS,EAAE,oBAAoB,KAAK,IAAI,EACxD,OAAO,CAAC,EAAE,oCAAoC,GAC7C,IAAI;IAsBP,OAAO,CAAC,aAAa;CAMtB"} |
@@ -42,9 +42,9 @@ "use strict"; | ||
| exports.JsonSchema = void 0; | ||
| const os = __importStar(require("os")); | ||
| const path = __importStar(require("path")); | ||
| const FileSystem_1 = require("./FileSystem"); | ||
| const JsonFile_1 = require("./JsonFile"); | ||
| const os = __importStar(require("node:os")); | ||
| const path = __importStar(require("node:path")); | ||
| const ajv_1 = __importDefault(require("ajv")); | ||
| const ajv_draft_04_1 = __importDefault(require("ajv-draft-04")); | ||
| const ajv_formats_1 = __importDefault(require("ajv-formats")); | ||
| const JsonFile_1 = require("./JsonFile"); | ||
| const FileSystem_1 = require("./FileSystem"); | ||
| const JSON_SCHEMA_URL_PREFIX_BY_JSON_SCHEMA_VERSION = new Map([ | ||
@@ -51,0 +51,0 @@ ['draft-04', 'http://json-schema.org/draft-04/schema'], |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"JsonSchema.js","sourceRoot":"","sources":["../src/JsonSchema.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,uCAAyB;AACzB,2CAA6B;AAE7B,6CAA0C;AAC1C,yCAAuD;AAEvD,8CAA+F;AAC/F,gEAAsC;AACtC,8DAAqC;AA4HrC,MAAM,6CAA6C,GAAmC,IAAI,GAAG,CAAC;IAC5F,CAAC,UAAU,EAAE,wCAAwC,CAAC;IACtD,CAAC,UAAU,EAAE,wCAAwC,CAAC;CACvD,CAAC,CAAC;AAEH;;GAEG;AACH,SAAS,uBAAuB,CAAC,EAAE,OAAO,EAAc;IACtD,IAAI,OAAO,EAAE,CAAC;QACZ,KAAK,MAAM,CAAC,iBAAiB,EAAE,SAAS,CAAC,IAAI,6CAA6C,EAAE,CAAC;YAC3F,IAAI,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;gBAClC,OAAO,iBAAiB,CAAC;YAC3B,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,MAAa,UAAU;IAUrB;QATQ,sBAAiB,GAAiB,EAAE,CAAC;QACrC,cAAS,GAAW,EAAE,CAAC;QACvB,eAAU,GAAiC,SAAS,CAAC;QACrD,kBAAa,GAA2B,SAAS,CAAC;QAClD,mBAAc,GAAkC,SAAS,CAA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aAA+B,CAAC,GAAG,IAAI,EAAE,CAAC;IACrG,CAAC;CACF;AA5QD,gCA4QC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { FileSystem } from './FileSystem';\nimport { JsonFile, type JsonObject } from './JsonFile';\n\nimport Ajv, { type Options as AjvOptions, type ErrorObject, type ValidateFunction } from 'ajv';\nimport AjvDraft04 from 'ajv-draft-04';\nimport addFormats from 'ajv-formats';\n\ninterface ISchemaWithId {\n // draft-04 uses \"id\"\n id: string | undefined;\n // draft-06 and higher uses \"$id\"\n $id: string | undefined;\n}\n\n/**\n * Specifies the version of json-schema to be validated against.\n * https://json-schema.org/specification\n * @public\n */\nexport type JsonSchemaVersion = 'draft-04' | 'draft-07';\n\n/**\n * A definition for a custom format to consider during validation.\n * @public\n */\nexport interface IJsonSchemaCustomFormat<T extends string | number> {\n /**\n * The base JSON type.\n */\n type: T extends string ? 'string' : T extends number ? 'number' : never;\n\n /**\n * A validation function for the format.\n * @param data - The raw field data to validate.\n * @returns whether the data is valid according to the format.\n */\n validate: (data: T) => boolean;\n}\n\n/**\n * Callback function arguments for {@link JsonSchema.validateObjectWithCallback}\n * @public\n */\nexport interface IJsonSchemaErrorInfo {\n /**\n * The ajv error list, formatted as an indented text string.\n */\n details: string;\n}\n\n/**\n * Options for {@link JsonSchema.validateObjectWithCallback}\n * @public\n */\nexport interface IJsonSchemaValidateObjectWithOptions {\n /**\n * If true, the root-level `$schema` property in a JSON object being validated will be ignored during validation.\n * If this is set to `true` and the schema requires a `$schema` property, validation will fail.\n */\n ignoreSchemaField?: boolean;\n}\n\n/**\n * Options for {@link JsonSchema.validateObject}\n * @public\n */\nexport interface IJsonSchemaValidateOptions extends IJsonSchemaValidateObjectWithOptions {\n /**\n * A custom header that will be used to report schema errors.\n * @remarks\n * If omitted, the default header is \"JSON validation failed:\". The error message starts with\n * the header, followed by the full input filename, followed by the ajv error list.\n * If you wish to customize all aspects of the error message, use JsonFile.loadAndValidateWithCallback()\n * or JsonSchema.validateObjectWithCallback().\n */\n customErrorHeader?: string;\n}\n\n/**\n * Options for {@link JsonSchema.fromFile} and {@link JsonSchema.fromLoadedObject}\n * @public\n */\nexport interface IJsonSchemaLoadOptions {\n /**\n * Other schemas that this schema references, e.g. via the \"$ref\" directive.\n * @remarks\n * The tree of dependent schemas may reference the same schema more than once.\n * However, if the same schema \"$id\" is used by two different JsonSchema instances,\n * an error will be reported. This means you cannot load the same filename twice\n * and use them both together, and you cannot have diamond dependencies on different\n * versions of the same schema. Although technically this would be possible to support,\n * it normally indicates an error or design problem.\n *\n * JsonSchema also does not allow circular references between schema dependencies.\n */\n dependentSchemas?: JsonSchema[];\n\n /**\n * The json-schema version to target for validation.\n *\n * @defaultValue draft-07\n *\n * @remarks\n * If the a version is not explicitly set, the schema object's `$schema` property\n * will be inspected to determine the version. If a `$schema` property is not found\n * or does not match an expected URL, the default version will be used.\n */\n schemaVersion?: JsonSchemaVersion;\n\n /**\n * Any custom formats to consider during validation. Some standard formats are supported\n * out-of-the-box (e.g. emails, uris), but additional formats can be defined here. You could\n * for example define generic numeric formats (e.g. uint8) or domain-specific formats.\n */\n customFormats?: Record<string, IJsonSchemaCustomFormat<string> | IJsonSchemaCustomFormat<number>>;\n}\n\n/**\n * Options for {@link JsonSchema.fromFile}\n * @public\n */\nexport type IJsonSchemaFromFileOptions = IJsonSchemaLoadOptions;\n\n/**\n * Options for {@link JsonSchema.fromLoadedObject}\n * @public\n */\nexport type IJsonSchemaFromObjectOptions = IJsonSchemaLoadOptions;\n\nconst JSON_SCHEMA_URL_PREFIX_BY_JSON_SCHEMA_VERSION: Map<JsonSchemaVersion, string> = new Map([\n ['draft-04', 'http://json-schema.org/draft-04/schema'],\n ['draft-07', 'http://json-schema.org/draft-07/schema']\n]);\n\n/**\n * Helper function to determine the json-schema version to target for validation.\n */\nfunction _inferJsonSchemaVersion({ $schema }: JsonObject): JsonSchemaVersion | undefined {\n if ($schema) {\n for (const [jsonSchemaVersion, urlPrefix] of JSON_SCHEMA_URL_PREFIX_BY_JSON_SCHEMA_VERSION) {\n if ($schema.startsWith(urlPrefix)) {\n return jsonSchemaVersion;\n }\n }\n }\n}\n\n/**\n * Represents a JSON schema that can be used to validate JSON data files loaded by the JsonFile class.\n * @remarks\n * The schema itself is normally loaded and compiled later, only if it is actually required to validate\n * an input. To avoid schema errors at runtime, it's recommended to create a unit test that calls\n * JsonSchema.ensureCompiled() for each of your schema objects.\n *\n * @public\n */\nexport class JsonSchema {\n private _dependentSchemas: JsonSchema[] = [];\n private _filename: string = '';\n private _validator: ValidateFunction | undefined = undefined;\n private _schemaObject: JsonObject | undefined = undefined;\n private _schemaVersion: JsonSchemaVersion | undefined = undefined;\n private _customFormats:\n | Record<string, IJsonSchemaCustomFormat<string> | IJsonSchemaCustomFormat<number>>\n | undefined = undefined;\n\n private constructor() {}\n\n /**\n * Registers a JsonSchema that will be loaded from a file on disk.\n * @remarks\n * NOTE: An error occurs if the file does not exist; however, the file itself is not loaded or validated\n * until it the schema is actually used.\n */\n public static fromFile(filename: string, options?: IJsonSchemaFromFileOptions): JsonSchema {\n // This is a quick and inexpensive test to avoid the catch the most common errors early.\n // Full validation will happen later in JsonSchema.compile().\n if (!FileSystem.exists(filename)) {\n throw new Error('Schema file not found: ' + filename);\n }\n\n const schema: JsonSchema = new JsonSchema();\n schema._filename = filename;\n\n if (options) {\n schema._dependentSchemas = options.dependentSchemas || [];\n schema._schemaVersion = options.schemaVersion;\n schema._customFormats = options.customFormats;\n }\n\n return schema;\n }\n\n /**\n * Registers a JsonSchema that will be loaded from an object.\n */\n public static fromLoadedObject(\n schemaObject: JsonObject,\n options?: IJsonSchemaFromObjectOptions\n ): JsonSchema {\n const schema: JsonSchema = new JsonSchema();\n schema._schemaObject = schemaObject;\n\n if (options) {\n schema._dependentSchemas = options.dependentSchemas || [];\n schema._schemaVersion = options.schemaVersion;\n schema._customFormats = options.customFormats;\n }\n\n return schema;\n }\n\n private static _collectDependentSchemas(\n collectedSchemas: JsonSchema[],\n dependentSchemas: JsonSchema[],\n seenObjects: Set<JsonSchema>,\n seenIds: Set<string>\n ): void {\n for (const dependentSchema of dependentSchemas) {\n // It's okay for the same schema to appear multiple times in the tree, but we only process it once\n if (seenObjects.has(dependentSchema)) {\n continue;\n }\n seenObjects.add(dependentSchema);\n\n const schemaId: string = dependentSchema._ensureLoaded();\n if (schemaId === '') {\n throw new Error(\n `This schema ${dependentSchema.shortName} cannot be referenced` +\n ' because is missing the \"id\" (draft-04) or \"$id\" field'\n );\n }\n if (seenIds.has(schemaId)) {\n throw new Error(\n `This schema ${dependentSchema.shortName} has the same \"id\" (draft-04) or \"$id\" as another schema in this set`\n );\n }\n\n seenIds.add(schemaId);\n\n collectedSchemas.push(dependentSchema);\n\n JsonSchema._collectDependentSchemas(\n collectedSchemas,\n dependentSchema._dependentSchemas,\n seenObjects,\n seenIds\n );\n }\n }\n\n /**\n * Used to nicely format the ZSchema error tree.\n */\n private static _formatErrorDetails(errorDetails: ErrorObject[]): string {\n return JsonSchema._formatErrorDetailsHelper(errorDetails, '', '');\n }\n\n /**\n * Used by _formatErrorDetails.\n */\n private static _formatErrorDetailsHelper(\n errorDetails: ErrorObject[],\n indent: string,\n buffer: string\n ): string {\n for (const errorDetail of errorDetails) {\n buffer += os.EOL + indent + `Error: #${errorDetail.instancePath}`;\n\n buffer += os.EOL + indent + ` ${errorDetail.message}`;\n if (errorDetail.params?.additionalProperty) {\n buffer += `: ${errorDetail.params?.additionalProperty}`;\n }\n }\n\n return buffer;\n }\n\n /**\n * Returns a short name for this schema, for use in error messages.\n * @remarks\n * If the schema was loaded from a file, then the base filename is used. Otherwise, the \"$id\"\n * field is used if available.\n */\n public get shortName(): string {\n if (!this._filename) {\n if (this._schemaObject) {\n const schemaWithId: ISchemaWithId = this._schemaObject as ISchemaWithId;\n if (schemaWithId.id) {\n return schemaWithId.id;\n } else if (schemaWithId.$id) {\n return schemaWithId.$id;\n }\n }\n return '(anonymous schema)';\n } else {\n return path.basename(this._filename);\n }\n }\n\n /**\n * If not already done, this loads the schema from disk and compiles it.\n * @remarks\n * Any dependencies will be compiled as well.\n */\n public ensureCompiled(): void {\n this._ensureLoaded();\n\n if (!this._validator) {\n const targetSchemaVersion: JsonSchemaVersion | undefined =\n this._schemaVersion ?? _inferJsonSchemaVersion(this._schemaObject);\n const validatorOptions: AjvOptions = {\n strictSchema: true,\n allowUnionTypes: true\n };\n\n let validator: Ajv;\n // Keep legacy support for older draft-04 schema\n switch (targetSchemaVersion) {\n case 'draft-04': {\n validator = new AjvDraft04(validatorOptions);\n break;\n }\n\n case 'draft-07':\n default: {\n validator = new Ajv(validatorOptions);\n break;\n }\n }\n\n // Enable json-schema format validation\n // https://ajv.js.org/packages/ajv-formats.html\n addFormats(validator);\n if (this._customFormats) {\n for (const [name, format] of Object.entries(this._customFormats)) {\n validator.addFormat(name, { ...format, async: false });\n }\n }\n\n const collectedSchemas: JsonSchema[] = [];\n const seenObjects: Set<JsonSchema> = new Set<JsonSchema>();\n const seenIds: Set<string> = new Set<string>();\n\n JsonSchema._collectDependentSchemas(collectedSchemas, this._dependentSchemas, seenObjects, seenIds);\n\n // Validate each schema in order. We specifically do not supply them all together, because we want\n // to make sure that circular references will fail to validate.\n for (const collectedSchema of collectedSchemas) {\n validator.validateSchema(collectedSchema._schemaObject) as boolean;\n if (validator.errors && validator.errors.length > 0) {\n throw new Error(\n `Failed to validate schema \"${collectedSchema.shortName}\":` +\n os.EOL +\n JsonSchema._formatErrorDetails(validator.errors)\n );\n }\n validator.addSchema(collectedSchema._schemaObject);\n }\n\n this._validator = validator.compile(this._schemaObject);\n }\n }\n\n /**\n * Validates the specified JSON object against this JSON schema. If the validation fails,\n * an exception will be thrown.\n * @param jsonObject - The JSON data to be validated\n * @param filenameForErrors - The filename that the JSON data was available, or an empty string\n * if not applicable\n * @param options - Other options that control the validation\n */\n public validateObject(\n jsonObject: JsonObject,\n filenameForErrors: string,\n options?: IJsonSchemaValidateOptions\n ): void {\n this.validateObjectWithCallback(\n jsonObject,\n (errorInfo: IJsonSchemaErrorInfo) => {\n const prefix: string = options?.customErrorHeader ?? 'JSON validation failed:';\n\n throw new Error(prefix + os.EOL + filenameForErrors + os.EOL + errorInfo.details);\n },\n options\n );\n }\n\n /**\n * Validates the specified JSON object against this JSON schema. If the validation fails,\n * a callback is called for each validation error.\n */\n public validateObjectWithCallback(\n jsonObject: JsonObject,\n errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void,\n options?: IJsonSchemaValidateObjectWithOptions\n ): void {\n this.ensureCompiled();\n\n if (options?.ignoreSchemaField) {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n $schema,\n ...remainder\n } = jsonObject;\n jsonObject = remainder;\n }\n\n if (this._validator && !this._validator(jsonObject)) {\n const errorDetails: string = JsonSchema._formatErrorDetails(this._validator.errors!);\n\n const args: IJsonSchemaErrorInfo = {\n details: errorDetails\n };\n errorCallback(args);\n }\n }\n\n private _ensureLoaded(): string {\n if (!this._schemaObject) {\n this._schemaObject = JsonFile.load(this._filename);\n }\n return (this._schemaObject as ISchemaWithId).id || (this._schemaObject as ISchemaWithId).$id || '';\n }\n}\n"]} | ||
| {"version":3,"file":"JsonSchema.js","sourceRoot":"","sources":["../src/JsonSchema.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,4CAA8B;AAC9B,gDAAkC;AAElC,8CAA+F;AAC/F,gEAAsC;AACtC,8DAAqC;AAErC,yCAAuD;AACvD,6CAA0C;AA4H1C,MAAM,6CAA6C,GAAmC,IAAI,GAAG,CAAC;IAC5F,CAAC,UAAU,EAAE,wCAAwC,CAAC;IACtD,CAAC,UAAU,EAAE,wCAAwC,CAAC;CACvD,CAAC,CAAC;AAEH;;GAEG;AACH,SAAS,uBAAuB,CAAC,EAAE,OAAO,E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C,EAAE,CAAC;YACpD,MAAM,YAAY,GAAW,UAAU,CAAC,mBAAmB,CAAC,IAAI,CAAC,UAAU,CAAC,MAAO,CAAC,CAAC;YAErF,MAAM,IAAI,GAAyB;gBACjC,OAAO,EAAE,YAAY;aACtB,CAAC;YACF,aAAa,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,CAAC,aAAa,GAAG,mBAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACrD,CAAC;QACD,OAAQ,IAAI,CAAC,aAA+B,CAAC,EAAE,IAAK,IAAI,CAAC,aAA+B,CAAC,GAAG,IAAI,EAAE,CAAC;IACrG,CAAC;CACF;AA5QD,gCA4QC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nimport Ajv, { type Options as AjvOptions, type ErrorObject, type ValidateFunction } from 'ajv';\nimport AjvDraft04 from 'ajv-draft-04';\nimport addFormats from 'ajv-formats';\n\nimport { JsonFile, type JsonObject } from './JsonFile';\nimport { FileSystem } from './FileSystem';\n\ninterface ISchemaWithId {\n // draft-04 uses \"id\"\n id: string | undefined;\n // draft-06 and higher uses \"$id\"\n $id: string | undefined;\n}\n\n/**\n * Specifies the version of json-schema to be validated against.\n * https://json-schema.org/specification\n * @public\n */\nexport type JsonSchemaVersion = 'draft-04' | 'draft-07';\n\n/**\n * A definition for a custom format to consider during validation.\n * @public\n */\nexport interface IJsonSchemaCustomFormat<T extends string | number> {\n /**\n * The base JSON type.\n */\n type: T extends string ? 'string' : T extends number ? 'number' : never;\n\n /**\n * A validation function for the format.\n * @param data - The raw field data to validate.\n * @returns whether the data is valid according to the format.\n */\n validate: (data: T) => boolean;\n}\n\n/**\n * Callback function arguments for {@link JsonSchema.validateObjectWithCallback}\n * @public\n */\nexport interface IJsonSchemaErrorInfo {\n /**\n * The ajv error list, formatted as an indented text string.\n */\n details: string;\n}\n\n/**\n * Options for {@link JsonSchema.validateObjectWithCallback}\n * @public\n */\nexport interface IJsonSchemaValidateObjectWithOptions {\n /**\n * If true, the root-level `$schema` property in a JSON object being validated will be ignored during validation.\n * If this is set to `true` and the schema requires a `$schema` property, validation will fail.\n */\n ignoreSchemaField?: boolean;\n}\n\n/**\n * Options for {@link JsonSchema.validateObject}\n * @public\n */\nexport interface IJsonSchemaValidateOptions extends IJsonSchemaValidateObjectWithOptions {\n /**\n * A custom header that will be used to report schema errors.\n * @remarks\n * If omitted, the default header is \"JSON validation failed:\". The error message starts with\n * the header, followed by the full input filename, followed by the ajv error list.\n * If you wish to customize all aspects of the error message, use JsonFile.loadAndValidateWithCallback()\n * or JsonSchema.validateObjectWithCallback().\n */\n customErrorHeader?: string;\n}\n\n/**\n * Options for {@link JsonSchema.fromFile} and {@link JsonSchema.fromLoadedObject}\n * @public\n */\nexport interface IJsonSchemaLoadOptions {\n /**\n * Other schemas that this schema references, e.g. via the \"$ref\" directive.\n * @remarks\n * The tree of dependent schemas may reference the same schema more than once.\n * However, if the same schema \"$id\" is used by two different JsonSchema instances,\n * an error will be reported. This means you cannot load the same filename twice\n * and use them both together, and you cannot have diamond dependencies on different\n * versions of the same schema. Although technically this would be possible to support,\n * it normally indicates an error or design problem.\n *\n * JsonSchema also does not allow circular references between schema dependencies.\n */\n dependentSchemas?: JsonSchema[];\n\n /**\n * The json-schema version to target for validation.\n *\n * @defaultValue draft-07\n *\n * @remarks\n * If the a version is not explicitly set, the schema object's `$schema` property\n * will be inspected to determine the version. If a `$schema` property is not found\n * or does not match an expected URL, the default version will be used.\n */\n schemaVersion?: JsonSchemaVersion;\n\n /**\n * Any custom formats to consider during validation. Some standard formats are supported\n * out-of-the-box (e.g. emails, uris), but additional formats can be defined here. You could\n * for example define generic numeric formats (e.g. uint8) or domain-specific formats.\n */\n customFormats?: Record<string, IJsonSchemaCustomFormat<string> | IJsonSchemaCustomFormat<number>>;\n}\n\n/**\n * Options for {@link JsonSchema.fromFile}\n * @public\n */\nexport type IJsonSchemaFromFileOptions = IJsonSchemaLoadOptions;\n\n/**\n * Options for {@link JsonSchema.fromLoadedObject}\n * @public\n */\nexport type IJsonSchemaFromObjectOptions = IJsonSchemaLoadOptions;\n\nconst JSON_SCHEMA_URL_PREFIX_BY_JSON_SCHEMA_VERSION: Map<JsonSchemaVersion, string> = new Map([\n ['draft-04', 'http://json-schema.org/draft-04/schema'],\n ['draft-07', 'http://json-schema.org/draft-07/schema']\n]);\n\n/**\n * Helper function to determine the json-schema version to target for validation.\n */\nfunction _inferJsonSchemaVersion({ $schema }: JsonObject): JsonSchemaVersion | undefined {\n if ($schema) {\n for (const [jsonSchemaVersion, urlPrefix] of JSON_SCHEMA_URL_PREFIX_BY_JSON_SCHEMA_VERSION) {\n if ($schema.startsWith(urlPrefix)) {\n return jsonSchemaVersion;\n }\n }\n }\n}\n\n/**\n * Represents a JSON schema that can be used to validate JSON data files loaded by the JsonFile class.\n * @remarks\n * The schema itself is normally loaded and compiled later, only if it is actually required to validate\n * an input. To avoid schema errors at runtime, it's recommended to create a unit test that calls\n * JsonSchema.ensureCompiled() for each of your schema objects.\n *\n * @public\n */\nexport class JsonSchema {\n private _dependentSchemas: JsonSchema[] = [];\n private _filename: string = '';\n private _validator: ValidateFunction | undefined = undefined;\n private _schemaObject: JsonObject | undefined = undefined;\n private _schemaVersion: JsonSchemaVersion | undefined = undefined;\n private _customFormats:\n | Record<string, IJsonSchemaCustomFormat<string> | IJsonSchemaCustomFormat<number>>\n | undefined = undefined;\n\n private constructor() {}\n\n /**\n * Registers a JsonSchema that will be loaded from a file on disk.\n * @remarks\n * NOTE: An error occurs if the file does not exist; however, the file itself is not loaded or validated\n * until it the schema is actually used.\n */\n public static fromFile(filename: string, options?: IJsonSchemaFromFileOptions): JsonSchema {\n // This is a quick and inexpensive test to avoid the catch the most common errors early.\n // Full validation will happen later in JsonSchema.compile().\n if (!FileSystem.exists(filename)) {\n throw new Error('Schema file not found: ' + filename);\n }\n\n const schema: JsonSchema = new JsonSchema();\n schema._filename = filename;\n\n if (options) {\n schema._dependentSchemas = options.dependentSchemas || [];\n schema._schemaVersion = options.schemaVersion;\n schema._customFormats = options.customFormats;\n }\n\n return schema;\n }\n\n /**\n * Registers a JsonSchema that will be loaded from an object.\n */\n public static fromLoadedObject(\n schemaObject: JsonObject,\n options?: IJsonSchemaFromObjectOptions\n ): JsonSchema {\n const schema: JsonSchema = new JsonSchema();\n schema._schemaObject = schemaObject;\n\n if (options) {\n schema._dependentSchemas = options.dependentSchemas || [];\n schema._schemaVersion = options.schemaVersion;\n schema._customFormats = options.customFormats;\n }\n\n return schema;\n }\n\n private static _collectDependentSchemas(\n collectedSchemas: JsonSchema[],\n dependentSchemas: JsonSchema[],\n seenObjects: Set<JsonSchema>,\n seenIds: Set<string>\n ): void {\n for (const dependentSchema of dependentSchemas) {\n // It's okay for the same schema to appear multiple times in the tree, but we only process it once\n if (seenObjects.has(dependentSchema)) {\n continue;\n }\n seenObjects.add(dependentSchema);\n\n const schemaId: string = dependentSchema._ensureLoaded();\n if (schemaId === '') {\n throw new Error(\n `This schema ${dependentSchema.shortName} cannot be referenced` +\n ' because is missing the \"id\" (draft-04) or \"$id\" field'\n );\n }\n if (seenIds.has(schemaId)) {\n throw new Error(\n `This schema ${dependentSchema.shortName} has the same \"id\" (draft-04) or \"$id\" as another schema in this set`\n );\n }\n\n seenIds.add(schemaId);\n\n collectedSchemas.push(dependentSchema);\n\n JsonSchema._collectDependentSchemas(\n collectedSchemas,\n dependentSchema._dependentSchemas,\n seenObjects,\n seenIds\n );\n }\n }\n\n /**\n * Used to nicely format the ZSchema error tree.\n */\n private static _formatErrorDetails(errorDetails: ErrorObject[]): string {\n return JsonSchema._formatErrorDetailsHelper(errorDetails, '', '');\n }\n\n /**\n * Used by _formatErrorDetails.\n */\n private static _formatErrorDetailsHelper(\n errorDetails: ErrorObject[],\n indent: string,\n buffer: string\n ): string {\n for (const errorDetail of errorDetails) {\n buffer += os.EOL + indent + `Error: #${errorDetail.instancePath}`;\n\n buffer += os.EOL + indent + ` ${errorDetail.message}`;\n if (errorDetail.params?.additionalProperty) {\n buffer += `: ${errorDetail.params?.additionalProperty}`;\n }\n }\n\n return buffer;\n }\n\n /**\n * Returns a short name for this schema, for use in error messages.\n * @remarks\n * If the schema was loaded from a file, then the base filename is used. Otherwise, the \"$id\"\n * field is used if available.\n */\n public get shortName(): string {\n if (!this._filename) {\n if (this._schemaObject) {\n const schemaWithId: ISchemaWithId = this._schemaObject as ISchemaWithId;\n if (schemaWithId.id) {\n return schemaWithId.id;\n } else if (schemaWithId.$id) {\n return schemaWithId.$id;\n }\n }\n return '(anonymous schema)';\n } else {\n return path.basename(this._filename);\n }\n }\n\n /**\n * If not already done, this loads the schema from disk and compiles it.\n * @remarks\n * Any dependencies will be compiled as well.\n */\n public ensureCompiled(): void {\n this._ensureLoaded();\n\n if (!this._validator) {\n const targetSchemaVersion: JsonSchemaVersion | undefined =\n this._schemaVersion ?? _inferJsonSchemaVersion(this._schemaObject);\n const validatorOptions: AjvOptions = {\n strictSchema: true,\n allowUnionTypes: true\n };\n\n let validator: Ajv;\n // Keep legacy support for older draft-04 schema\n switch (targetSchemaVersion) {\n case 'draft-04': {\n validator = new AjvDraft04(validatorOptions);\n break;\n }\n\n case 'draft-07':\n default: {\n validator = new Ajv(validatorOptions);\n break;\n }\n }\n\n // Enable json-schema format validation\n // https://ajv.js.org/packages/ajv-formats.html\n addFormats(validator);\n if (this._customFormats) {\n for (const [name, format] of Object.entries(this._customFormats)) {\n validator.addFormat(name, { ...format, async: false });\n }\n }\n\n const collectedSchemas: JsonSchema[] = [];\n const seenObjects: Set<JsonSchema> = new Set<JsonSchema>();\n const seenIds: Set<string> = new Set<string>();\n\n JsonSchema._collectDependentSchemas(collectedSchemas, this._dependentSchemas, seenObjects, seenIds);\n\n // Validate each schema in order. We specifically do not supply them all together, because we want\n // to make sure that circular references will fail to validate.\n for (const collectedSchema of collectedSchemas) {\n validator.validateSchema(collectedSchema._schemaObject) as boolean;\n if (validator.errors && validator.errors.length > 0) {\n throw new Error(\n `Failed to validate schema \"${collectedSchema.shortName}\":` +\n os.EOL +\n JsonSchema._formatErrorDetails(validator.errors)\n );\n }\n validator.addSchema(collectedSchema._schemaObject);\n }\n\n this._validator = validator.compile(this._schemaObject);\n }\n }\n\n /**\n * Validates the specified JSON object against this JSON schema. If the validation fails,\n * an exception will be thrown.\n * @param jsonObject - The JSON data to be validated\n * @param filenameForErrors - The filename that the JSON data was available, or an empty string\n * if not applicable\n * @param options - Other options that control the validation\n */\n public validateObject(\n jsonObject: JsonObject,\n filenameForErrors: string,\n options?: IJsonSchemaValidateOptions\n ): void {\n this.validateObjectWithCallback(\n jsonObject,\n (errorInfo: IJsonSchemaErrorInfo) => {\n const prefix: string = options?.customErrorHeader ?? 'JSON validation failed:';\n\n throw new Error(prefix + os.EOL + filenameForErrors + os.EOL + errorInfo.details);\n },\n options\n );\n }\n\n /**\n * Validates the specified JSON object against this JSON schema. If the validation fails,\n * a callback is called for each validation error.\n */\n public validateObjectWithCallback(\n jsonObject: JsonObject,\n errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void,\n options?: IJsonSchemaValidateObjectWithOptions\n ): void {\n this.ensureCompiled();\n\n if (options?.ignoreSchemaField) {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n $schema,\n ...remainder\n } = jsonObject;\n jsonObject = remainder;\n }\n\n if (this._validator && !this._validator(jsonObject)) {\n const errorDetails: string = JsonSchema._formatErrorDetails(this._validator.errors!);\n\n const args: IJsonSchemaErrorInfo = {\n details: errorDetails\n };\n errorCallback(args);\n }\n }\n\n private _ensureLoaded(): string {\n if (!this._schemaObject) {\n this._schemaObject = JsonFile.load(this._filename);\n }\n return (this._schemaObject as ISchemaWithId).id || (this._schemaObject as ISchemaWithId).$id || '';\n }\n}\n"]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;OAKG;IACI,OAAO,CAAC,UAAU,GAAE,OAAc,GAAG,IAAI;IAehD;;;OAGG;IACH,IAAW,iBAAiB,IAAI,OAAO,CAEtC;IAED;;OAEG;IACH,IAAW,QAAQ,IAAI,MAAM,CAE5B;IAED;;OAEG;IACH,IAAW,UAAU,IAAI,OAAO,CAE/B;CACF"} |
+2
-2
@@ -41,4 +41,4 @@ "use strict"; | ||
| exports.getProcessStartTime = getProcessStartTime; | ||
| const path = __importStar(require("path")); | ||
| const child_process = __importStar(require("child_process")); | ||
| const path = __importStar(require("node:path")); | ||
| const child_process = __importStar(require("node:child_process")); | ||
| const FileSystem_1 = require("./FileSystem"); | ||
@@ -45,0 +45,0 @@ const FileWriter_1 = require("./FileWriter"); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"LockFile.js","sourceRoot":"","sources":["../src/LockFile.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuB3D,0EAsCC;AAMD,kDAoEC;AArID,2CAA6B;AAC7B,6DAA+C;AAC/C,6CAA0C;AAC1C,6CAA0C;AAC1C,mCAAgC;AAEhC;;;;;;;GAOG;AACH,MAAM,oBAAoB,GAAW,EAAE,CAAC;AAExC;;;;GAIG;AACH,SAAgB,+BAA+B,CAAC,IAAY;IAC1D,oDAAoD;IACpD,2EAA2E;IAC3E,0DAA0D;IAC1D,oCAAoC;IACpC,6DAA6D;IAC7D,sFAAsF;IACtF,wBAAwB;IACxB,kEAAkE;IAClE,iHAAiH;IAEjH,oDAAoD;IACpD,IAAI,MAAM,GAAa,IAAI,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnD,IAAI,CAAC,GAAW,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IAClC,OACE,CAAC,IAAI,CAAC;QACN,gEAAgE;QAChE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,C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AC;IACxC,CAAC;;AA5WH,4BA6WC;AA5WgB,sBAAa,GAAwC,mBAAmB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'path';\nimport * as child_process from 'child_process';\nimport { FileSystem } from './FileSystem';\nimport { FileWriter } from './FileWriter';\nimport { Async } from './Async';\n\n/**\n * http://man7.org/linux/man-pages/man5/proc.5.html\n * (22) starttime %llu\n * The time the process started after system boot. In kernels before Linux 2.6, this value was\n * expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks (divide by\n * sysconf(_SC_CLK_TCK)).\n * The format for this field was %lu before Linux 2.6.\n */\nconst procStatStartTimePos: number = 22;\n\n/**\n * Parses the process start time from the contents of a linux /proc/[pid]/stat file.\n * @param stat - The contents of a linux /proc/[pid]/stat file.\n * @returns The process start time in jiffies, or undefined if stat has an unexpected format.\n */\nexport function getProcessStartTimeFromProcStat(stat: string): string | undefined {\n // Parse the value at position procStatStartTimePos.\n // We cannot just split stat on spaces, because value 2 may contain spaces.\n // For example, when running the following Shell commands:\n // > cp \"$(which bash)\" ./'bash 2)('\n // > ./'bash 2)(' -c 'OWNPID=$BASHPID;cat /proc/$OWNPID/stat'\n // 59389 (bash 2)() S 59358 59389 59358 34818 59389 4202496 329 0 0 0 0 0 0 0 20 0 1 0\n // > rm -rf ./'bash 2)('\n // The output shows a stat file such that value 2 contains spaces.\n // To still umambiguously parse such output we assume no values after the second ends with a right parenthesis...\n\n // trimRight to remove the trailing line terminator.\n let values: string[] = stat.trimRight().split(' ');\n let i: number = values.length - 1;\n while (\n i >= 0 &&\n // charAt returns an empty string if the index is out of bounds.\n values[i].charAt(values[i].length - 1) !== ')'\n ) {\n i -= 1;\n }\n // i is the index of the last part of the second value (but i need not be 1).\n if (i < 1) {\n // Format of stat has changed.\n return undefined;\n }\n const value2: string = values.slice(1, i + 1).join(' ');\n values = [values[0], value2].concat(values.slice(i + 1));\n if (values.length < procStatStartTimePos) {\n // Older version of linux, or non-standard configuration of linux.\n return undefined;\n }\n const startTimeJiffies: string = values[procStatStartTimePos - 1];\n // In theory, the representations of start time returned by `cat /proc/[pid]/stat` and `ps -o lstart` can change\n // while the system is running, but we assume this does not happen.\n // So the caller can safely use this value as part of a unique process id (on the machine, without comparing\n // across reboots).\n return startTimeJiffies;\n}\n\n/**\n * Helper function that is exported for unit tests only.\n * Returns undefined if the process doesn't exist with that pid.\n */\nexport function getProcessStartTime(pid: number): string | undefined {\n const pidString: string = pid.toString();\n if (pid < 0 || pidString.indexOf('e') >= 0 || pidString.indexOf('E') >= 0) {\n throw new Error(`\"pid\" is negative or too large`);\n }\n let args: string[];\n if (process.platform === 'darwin') {\n args = [`-p ${pidString}`, '-o lstart'];\n } else if (process.platform === 'linux') {\n args = ['-p', pidString, '-o', 'lstart'];\n } else {\n throw new Error(`Unsupported system: ${process.platform}`);\n }\n\n const psResult: child_process.SpawnSyncReturns<string> = child_process.spawnSync('ps', args, {\n encoding: 'utf8'\n });\n const psStdout: string = psResult.stdout;\n\n // If no process with PID pid exists then the exit code is non-zero on linux but stdout is not empty.\n // But if no process exists we do not want to fall back on /proc/*/stat to determine the process\n // start time, so we we additionally test for !psStdout. NOTE: !psStdout evaluates to true if\n // zero bytes are written to stdout.\n if (psResult.status !== 0 && !psStdout && process.platform === 'linux') {\n // Try to read /proc/[pid]/stat and get the value at position procStatStartTimePos.\n let stat: undefined | string;\n try {\n stat = FileSystem.readFile(`/proc/${pidString}/stat`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n // Either no process with PID pid exists, or this version/configuration of linux is non-standard.\n // We assume the former.\n return undefined;\n }\n if (stat !== undefined) {\n const startTimeJiffies: string | undefined = getProcessStartTimeFromProcStat(stat);\n if (startTimeJiffies === undefined) {\n throw new Error(\n `Could not retrieve the start time of process ${pidString} from the OS because the ` +\n `contents of /proc/${pidString}/stat have an unexpected format`\n );\n }\n return startTimeJiffies;\n }\n }\n\n // there was an error executing ps (zero bytes were written to stdout).\n if (!psStdout) {\n throw new Error(`Unexpected output from \"ps\" command`);\n }\n\n const psSplit: string[] = psStdout.split('\\n');\n\n // successfully able to run \"ps\", but no process was found\n if (psSplit[1] === '') {\n return undefined;\n }\n\n if (psSplit[1]) {\n const trimmed: string = psSplit[1].trim();\n if (trimmed.length > 10) {\n return trimmed;\n }\n }\n\n throw new Error(`Unexpected output from the \"ps\" command`);\n}\n\n// A set of locks that currently exist in the current process, to be used when\n// multiple locks are acquired in the same process.\nconst IN_PROC_LOCKS: Set<string> = new Set<string>();\n\n/**\n * The `LockFile` implements a file-based mutex for synchronizing access to a shared resource\n * between multiple Node.js processes. It is not recommended for synchronization solely within\n * a single Node.js process.\n * @remarks\n * The implementation works on Windows, Mac, and Linux without requiring any native helpers.\n * On non-Windows systems, the algorithm requires access to the `ps` shell command. On Linux,\n * it requires access the `/proc/${pidString}/stat` filesystem.\n * @public\n */\nexport class LockFile {\n private static _getStartTime: (pid: number) => string | undefined = getProcessStartTime;\n\n private _fileWriter: FileWriter | undefined;\n private _filePath: string;\n private _dirtyWhenAcquired: boolean;\n\n private constructor(fileWriter: FileWriter | undefined, filePath: string, dirtyWhenAcquired: boolean) {\n this._fileWriter = fileWriter;\n this._filePath = filePath;\n this._dirtyWhenAcquired = dirtyWhenAcquired;\n\n IN_PROC_LOCKS.add(filePath);\n }\n\n /**\n * Returns the path of the lockfile that will be created when a lock is successfully acquired.\n * @param resourceFolder - The folder where the lock file will be created\n * @param resourceName - An alphanumeric name that describes the resource being locked. This will become\n * the filename of the temporary file created to manage the lock.\n * @param pid - The PID for the current Node.js process (`process.pid`), which is used by the locking algorithm.\n */\n public static getLockFilePath(\n resourceFolder: string,\n resourceName: string,\n pid: number = process.pid\n ): string {\n if (!resourceName.match(/^[a-zA-Z0-9][a-zA-Z0-9-.]+[a-zA-Z0-9]$/)) {\n throw new Error(\n `The resource name \"${resourceName}\" is invalid.` +\n ` It must be an alphanumeric string with only \"-\" or \".\" It must start and end with an alphanumeric character.`\n );\n }\n\n switch (process.platform) {\n case 'win32': {\n return path.resolve(resourceFolder, `${resourceName}.lock`);\n }\n\n case 'linux':\n case 'darwin': {\n return path.resolve(resourceFolder, `${resourceName}#${pid}.lock`);\n }\n\n default: {\n throw new Error(`File locking not implemented for platform: \"${process.platform}\"`);\n }\n }\n }\n\n /**\n * Attempts to create a lockfile with the given filePath.\n * @param resourceFolder - The folder where the lock file will be created\n * @param resourceName - An alphanumeric name that describes the resource being locked. This will become\n * the filename of the temporary file created to manage the lock.\n * @returns If successful, returns a `LockFile` instance. If unable to get a lock, returns `undefined`.\n */\n public static tryAcquire(resourceFolder: string, resourceName: string): LockFile | undefined {\n FileSystem.ensureFolder(resourceFolder);\n const lockFilePath: string = LockFile.getLockFilePath(resourceFolder, resourceName);\n return LockFile._tryAcquireInner(resourceFolder, resourceName, lockFilePath);\n }\n\n /**\n * @deprecated Use {@link LockFile.acquireAsync} instead.\n */\n public static acquire(resourceFolder: string, resourceName: string, maxWaitMs?: number): Promise<LockFile> {\n return LockFile.acquireAsync(resourceFolder, resourceName, maxWaitMs);\n }\n\n /**\n * Attempts to create the lockfile. Will continue to loop at every 100ms until the lock becomes available\n * or the maxWaitMs is surpassed.\n *\n * @remarks\n * This function is subject to starvation, whereby it does not ensure that the process that has been\n * waiting the longest to acquire the lock will get it first. This means that a process could theoretically\n * wait for the lock forever, while other processes skipped it in line and acquired the lock first.\n *\n * @param resourceFolder - The folder where the lock file will be created\n * @param resourceName - An alphanumeric name that describes the resource being locked. This will become\n * the filename of the temporary file created to manage the lock.\n * @param maxWaitMs - The maximum number of milliseconds to wait for the lock before reporting an error\n */\n public static async acquireAsync(\n resourceFolder: string,\n resourceName: string,\n maxWaitMs?: number\n ): Promise<LockFile> {\n const interval: number = 100;\n const startTime: number = Date.now();\n const timeoutTime: number | undefined = maxWaitMs ? startTime + maxWaitMs : undefined;\n\n await FileSystem.ensureFolderAsync(resourceFolder);\n\n const lockFilePath: string = LockFile.getLockFilePath(resourceFolder, resourceName);\n\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!timeoutTime || Date.now() <= timeoutTime) {\n const lock: LockFile | undefined = LockFile._tryAcquireInner(\n resourceFolder,\n resourceName,\n lockFilePath\n );\n if (lock) {\n return lock;\n }\n\n await Async.sleepAsync(interval);\n }\n\n throw new Error(`Exceeded maximum wait time to acquire lock for resource \"${resourceName}\"`);\n }\n\n private static _tryAcquireInner(\n resourceFolder: string,\n resourceName: string,\n lockFilePath: string\n ): LockFile | undefined {\n if (!IN_PROC_LOCKS.has(lockFilePath)) {\n switch (process.platform) {\n case 'win32': {\n return LockFile._tryAcquireWindows(lockFilePath);\n }\n\n case 'linux':\n case 'darwin': {\n return LockFile._tryAcquireMacOrLinux(resourceFolder, resourceName, lockFilePath);\n }\n\n default: {\n throw new Error(`File locking not implemented for platform: \"${process.platform}\"`);\n }\n }\n }\n }\n\n /**\n * Attempts to acquire the lock on a Linux or OSX machine\n */\n private static _tryAcquireMacOrLinux(\n resourceFolder: string,\n resourceName: string,\n pidLockFilePath: string\n ): LockFile | undefined {\n let dirtyWhenAcquired: boolean = false;\n\n // get the current process' pid\n const pid: number = process.pid;\n const startTime: string | undefined = LockFile._getStartTime(pid);\n\n if (!startTime) {\n throw new Error(`Unable to calculate start time for current process.`);\n }\n\n let lockFileHandle: FileWriter | undefined;\n\n let lockFile: LockFile;\n\n try {\n // open in write mode since if this file exists, it cannot be from the current process\n // TODO: This will malfunction if the same process tries to acquire two locks on the same file.\n // We should ideally maintain a dictionary of normalized acquired filenames\n lockFileHandle = FileWriter.open(pidLockFilePath);\n lockFileHandle.write(startTime);\n const currentBirthTimeMs: number = lockFileHandle.getStatistics().birthtime.getTime();\n\n let smallestBirthTimeMs: number = currentBirthTimeMs;\n let smallestBirthTimePid: string = pid.toString();\n\n // now, scan the directory for all lockfiles\n const files: string[] = FileSystem.readFolderItemNames(resourceFolder);\n\n // look for anything ending with # then numbers and \".lock\"\n const lockFileRegExp: RegExp = /^(.+)#([0-9]+)\\.lock$/;\n\n let match: RegExpMatchArray | null;\n let otherPid: string;\n for (const fileInFolder of files) {\n if (\n (match = fileInFolder.match(lockFileRegExp)) &&\n match[1] === resourceName &&\n (otherPid = match[2]) !== pid.toString()\n ) {\n // we found at least one lockfile hanging around that isn't ours\n const fileInFolderPath: string = `${resourceFolder}/${fileInFolder}`;\n dirtyWhenAcquired = true;\n\n // console.log(`FOUND OTHER LOCKFILE: ${otherPid}`);\n\n const otherPidCurrentStartTime: string | undefined = LockFile._getStartTime(parseInt(otherPid, 10));\n\n let otherPidOldStartTime: string | undefined;\n let otherBirthtimeMs: number | undefined;\n try {\n otherPidOldStartTime = FileSystem.readFile(fileInFolderPath);\n // check the timestamp of the file\n otherBirthtimeMs = FileSystem.getStatistics(fileInFolderPath).birthtime.getTime();\n } catch (error) {\n if (FileSystem.isNotExistError(error)) {\n // the file is already deleted by other process, skip it\n continue;\n }\n }\n\n // if the otherPidOldStartTime is invalid, then we should look at the timestamp,\n // if this file was created after us, ignore it\n // if it was created within 1 second before us, then it could be good, so we\n // will conservatively fail\n // otherwise it is an old lock file and will be deleted\n if (otherPidOldStartTime === '' && otherBirthtimeMs !== undefined) {\n if (otherBirthtimeMs > currentBirthTimeMs) {\n // ignore this file, he will be unable to get the lock since this process\n // will hold it\n // console.log(`Ignoring lock for pid ${otherPid} because its lockfile is newer than ours.`);\n continue;\n } else if (\n otherBirthtimeMs - currentBirthTimeMs < 0 && // it was created before us AND\n otherBirthtimeMs - currentBirthTimeMs > -1000\n ) {\n // it was created less than a second before\n\n // conservatively be unable to keep the lock\n return undefined;\n }\n }\n\n // console.log(`Other pid ${otherPid} lockfile has start time: \"${otherPidOldStartTime}\"`);\n // console.log(`Other pid ${otherPid} actually has start time: \"${otherPidCurrentStartTime}\"`);\n\n // this means the process is no longer executing, delete the file\n if (!otherPidCurrentStartTime || otherPidOldStartTime !== otherPidCurrentStartTime) {\n // console.log(`Other pid ${otherPid} is no longer executing!`);\n FileSystem.deleteFile(fileInFolderPath);\n continue;\n }\n\n // console.log(`Pid ${otherPid} lockfile has birth time: ${otherBirthtimeMs}`);\n // console.log(`Pid ${pid} lockfile has birth time: ${currentBirthTimeMs}`);\n // this is a lockfile pointing at something valid\n if (otherBirthtimeMs !== undefined) {\n // the other lock file was created before the current earliest lock file\n // or the other lock file was created at the same exact time, but has earlier pid\n\n // note that it is acceptable to do a direct comparison of the PIDs in this case\n // since we are establishing a consistent order to apply to the lock files in all\n // execution instances.\n\n // it doesn't matter that the PIDs roll over, we've already\n // established that these processes all started at the same time, so we just\n // need to get all instances of the lock test to agree which one won.\n if (\n otherBirthtimeMs < smallestBirthTimeMs ||\n (otherBirthtimeMs === smallestBirthTimeMs && otherPid < smallestBirthTimePid)\n ) {\n smallestBirthTimeMs = otherBirthtimeMs;\n smallestBirthTimePid = otherPid;\n }\n }\n }\n }\n\n if (smallestBirthTimePid !== pid.toString()) {\n // we do not have the lock\n return undefined;\n }\n\n // we have the lock!\n lockFile = new LockFile(lockFileHandle, pidLockFilePath, dirtyWhenAcquired);\n lockFileHandle = undefined; // we have handed the descriptor off to the instance\n } finally {\n if (lockFileHandle) {\n // ensure our lock is closed\n lockFileHandle.close();\n FileSystem.deleteFile(pidLockFilePath);\n }\n }\n return lockFile;\n }\n\n /**\n * Attempts to acquire the lock using Windows\n * This algorithm is much simpler since we can rely on the operating system\n */\n private static _tryAcquireWindows(lockFilePath: string): LockFile | undefined {\n let dirtyWhenAcquired: boolean = false;\n\n let fileHandle: FileWriter | undefined;\n let lockFile: LockFile;\n\n try {\n if (FileSystem.exists(lockFilePath)) {\n dirtyWhenAcquired = true;\n\n // If the lockfile is held by an process with an exclusive lock, then removing it will\n // silently fail. OpenSync() below will then fail and we will be unable to create a lock.\n\n // Otherwise, the lockfile is sitting on disk, but nothing is holding it, implying that\n // the last process to hold it died.\n FileSystem.deleteFile(lockFilePath);\n }\n\n try {\n // Attempt to open an exclusive lockfile\n fileHandle = FileWriter.open(lockFilePath, { exclusive: true });\n } catch (error) {\n // we tried to delete the lock, but something else is holding it,\n // (probably an active process), therefore we are unable to create a lock\n return undefined;\n }\n\n // Ensure we can hand off the file descriptor to the lockfile\n lockFile = new LockFile(fileHandle, lockFilePath, dirtyWhenAcquired);\n fileHandle = undefined;\n } finally {\n if (fileHandle) {\n fileHandle.close();\n }\n }\n\n return lockFile;\n }\n\n /**\n * Unlocks a file and optionally removes it from disk.\n * This can only be called once.\n *\n * @param deleteFile - Whether to delete the lockfile from disk. Defaults to true.\n */\n public release(deleteFile: boolean = true): void {\n if (this.isReleased) {\n throw new Error(`The lock for file \"${path.basename(this._filePath)}\" has already been released.`);\n }\n\n IN_PROC_LOCKS.delete(this._filePath);\n\n this._fileWriter!.close();\n if (deleteFile) {\n FileSystem.deleteFile(this._filePath);\n }\n\n this._fileWriter = undefined;\n }\n\n /**\n * Returns the initial state of the lock.\n * This can be used to detect if the previous process was terminated before releasing the resource.\n */\n public get dirtyWhenAcquired(): boolean {\n return this._dirtyWhenAcquired;\n }\n\n /**\n * Returns the absolute path to the lockfile\n */\n public get filePath(): string {\n return this._filePath;\n }\n\n /**\n * Returns true if this lock is currently being held.\n */\n public get isReleased(): boolean {\n return this._fileWriter === undefined;\n }\n}\n"]} | ||
| {"version":3,"file":"LockFile.js","sourceRoot":"","sources":["../src/LockFile.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwB3D,0EAsCC;AAMD,kDAoEC;AAtID,gDAAkC;AAClC,kEAAoD;AAEpD,6CAA0C;AAC1C,6CAA0C;AAC1C,mCAAgC;AAEhC;;;;;;;GAOG;AACH,MAAM,oBAAoB,GAAW,EAAE,CAAC;AAExC;;;;GAIG;AACH,SAAgB,+BAA+B,CAAC,IAAY;IAC1D,oDAAoD;IACpD,2EAA2E;IAC3E,0DAA0D;IAC1D,oCAAoC;IACpC,6DAA6D;IAC7D,sFAAs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,CAAC;QACxC,CAAC;QAED,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC;IAC/B,CAAC;IAED;;;OAGG;IACH,IAAW,iBAAiB;QAC1B,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED;;OAEG;IACH,IAAW,QAAQ;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;OAEG;IACH,IAAW,UAAU;QACnB,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC;IACxC,CAAC;;AA5WH,4BA6WC;AA5WgB,sBAAa,GAAwC,mBAAmB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'node:path';\nimport * as child_process from 'node:child_process';\n\nimport { FileSystem } from './FileSystem';\nimport { FileWriter } from './FileWriter';\nimport { Async } from './Async';\n\n/**\n * http://man7.org/linux/man-pages/man5/proc.5.html\n * (22) starttime %llu\n * The time the process started after system boot. In kernels before Linux 2.6, this value was\n * expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks (divide by\n * sysconf(_SC_CLK_TCK)).\n * The format for this field was %lu before Linux 2.6.\n */\nconst procStatStartTimePos: number = 22;\n\n/**\n * Parses the process start time from the contents of a linux /proc/[pid]/stat file.\n * @param stat - The contents of a linux /proc/[pid]/stat file.\n * @returns The process start time in jiffies, or undefined if stat has an unexpected format.\n */\nexport function getProcessStartTimeFromProcStat(stat: string): string | undefined {\n // Parse the value at position procStatStartTimePos.\n // We cannot just split stat on spaces, because value 2 may contain spaces.\n // For example, when running the following Shell commands:\n // > cp \"$(which bash)\" ./'bash 2)('\n // > ./'bash 2)(' -c 'OWNPID=$BASHPID;cat /proc/$OWNPID/stat'\n // 59389 (bash 2)() S 59358 59389 59358 34818 59389 4202496 329 0 0 0 0 0 0 0 20 0 1 0\n // > rm -rf ./'bash 2)('\n // The output shows a stat file such that value 2 contains spaces.\n // To still umambiguously parse such output we assume no values after the second ends with a right parenthesis...\n\n // trimRight to remove the trailing line terminator.\n let values: string[] = stat.trimRight().split(' ');\n let i: number = values.length - 1;\n while (\n i >= 0 &&\n // charAt returns an empty string if the index is out of bounds.\n values[i].charAt(values[i].length - 1) !== ')'\n ) {\n i -= 1;\n }\n // i is the index of the last part of the second value (but i need not be 1).\n if (i < 1) {\n // Format of stat has changed.\n return undefined;\n }\n const value2: string = values.slice(1, i + 1).join(' ');\n values = [values[0], value2].concat(values.slice(i + 1));\n if (values.length < procStatStartTimePos) {\n // Older version of linux, or non-standard configuration of linux.\n return undefined;\n }\n const startTimeJiffies: string = values[procStatStartTimePos - 1];\n // In theory, the representations of start time returned by `cat /proc/[pid]/stat` and `ps -o lstart` can change\n // while the system is running, but we assume this does not happen.\n // So the caller can safely use this value as part of a unique process id (on the machine, without comparing\n // across reboots).\n return startTimeJiffies;\n}\n\n/**\n * Helper function that is exported for unit tests only.\n * Returns undefined if the process doesn't exist with that pid.\n */\nexport function getProcessStartTime(pid: number): string | undefined {\n const pidString: string = pid.toString();\n if (pid < 0 || pidString.indexOf('e') >= 0 || pidString.indexOf('E') >= 0) {\n throw new Error(`\"pid\" is negative or too large`);\n }\n let args: string[];\n if (process.platform === 'darwin') {\n args = [`-p ${pidString}`, '-o lstart'];\n } else if (process.platform === 'linux') {\n args = ['-p', pidString, '-o', 'lstart'];\n } else {\n throw new Error(`Unsupported system: ${process.platform}`);\n }\n\n const psResult: child_process.SpawnSyncReturns<string> = child_process.spawnSync('ps', args, {\n encoding: 'utf8'\n });\n const psStdout: string = psResult.stdout;\n\n // If no process with PID pid exists then the exit code is non-zero on linux but stdout is not empty.\n // But if no process exists we do not want to fall back on /proc/*/stat to determine the process\n // start time, so we we additionally test for !psStdout. NOTE: !psStdout evaluates to true if\n // zero bytes are written to stdout.\n if (psResult.status !== 0 && !psStdout && process.platform === 'linux') {\n // Try to read /proc/[pid]/stat and get the value at position procStatStartTimePos.\n let stat: undefined | string;\n try {\n stat = FileSystem.readFile(`/proc/${pidString}/stat`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n // Either no process with PID pid exists, or this version/configuration of linux is non-standard.\n // We assume the former.\n return undefined;\n }\n if (stat !== undefined) {\n const startTimeJiffies: string | undefined = getProcessStartTimeFromProcStat(stat);\n if (startTimeJiffies === undefined) {\n throw new Error(\n `Could not retrieve the start time of process ${pidString} from the OS because the ` +\n `contents of /proc/${pidString}/stat have an unexpected format`\n );\n }\n return startTimeJiffies;\n }\n }\n\n // there was an error executing ps (zero bytes were written to stdout).\n if (!psStdout) {\n throw new Error(`Unexpected output from \"ps\" command`);\n }\n\n const psSplit: string[] = psStdout.split('\\n');\n\n // successfully able to run \"ps\", but no process was found\n if (psSplit[1] === '') {\n return undefined;\n }\n\n if (psSplit[1]) {\n const trimmed: string = psSplit[1].trim();\n if (trimmed.length > 10) {\n return trimmed;\n }\n }\n\n throw new Error(`Unexpected output from the \"ps\" command`);\n}\n\n// A set of locks that currently exist in the current process, to be used when\n// multiple locks are acquired in the same process.\nconst IN_PROC_LOCKS: Set<string> = new Set<string>();\n\n/**\n * The `LockFile` implements a file-based mutex for synchronizing access to a shared resource\n * between multiple Node.js processes. It is not recommended for synchronization solely within\n * a single Node.js process.\n * @remarks\n * The implementation works on Windows, Mac, and Linux without requiring any native helpers.\n * On non-Windows systems, the algorithm requires access to the `ps` shell command. On Linux,\n * it requires access the `/proc/${pidString}/stat` filesystem.\n * @public\n */\nexport class LockFile {\n private static _getStartTime: (pid: number) => string | undefined = getProcessStartTime;\n\n private _fileWriter: FileWriter | undefined;\n private _filePath: string;\n private _dirtyWhenAcquired: boolean;\n\n private constructor(fileWriter: FileWriter | undefined, filePath: string, dirtyWhenAcquired: boolean) {\n this._fileWriter = fileWriter;\n this._filePath = filePath;\n this._dirtyWhenAcquired = dirtyWhenAcquired;\n\n IN_PROC_LOCKS.add(filePath);\n }\n\n /**\n * Returns the path of the lockfile that will be created when a lock is successfully acquired.\n * @param resourceFolder - The folder where the lock file will be created\n * @param resourceName - An alphanumeric name that describes the resource being locked. This will become\n * the filename of the temporary file created to manage the lock.\n * @param pid - The PID for the current Node.js process (`process.pid`), which is used by the locking algorithm.\n */\n public static getLockFilePath(\n resourceFolder: string,\n resourceName: string,\n pid: number = process.pid\n ): string {\n if (!resourceName.match(/^[a-zA-Z0-9][a-zA-Z0-9-.]+[a-zA-Z0-9]$/)) {\n throw new Error(\n `The resource name \"${resourceName}\" is invalid.` +\n ` It must be an alphanumeric string with only \"-\" or \".\" It must start and end with an alphanumeric character.`\n );\n }\n\n switch (process.platform) {\n case 'win32': {\n return path.resolve(resourceFolder, `${resourceName}.lock`);\n }\n\n case 'linux':\n case 'darwin': {\n return path.resolve(resourceFolder, `${resourceName}#${pid}.lock`);\n }\n\n default: {\n throw new Error(`File locking not implemented for platform: \"${process.platform}\"`);\n }\n }\n }\n\n /**\n * Attempts to create a lockfile with the given filePath.\n * @param resourceFolder - The folder where the lock file will be created\n * @param resourceName - An alphanumeric name that describes the resource being locked. This will become\n * the filename of the temporary file created to manage the lock.\n * @returns If successful, returns a `LockFile` instance. If unable to get a lock, returns `undefined`.\n */\n public static tryAcquire(resourceFolder: string, resourceName: string): LockFile | undefined {\n FileSystem.ensureFolder(resourceFolder);\n const lockFilePath: string = LockFile.getLockFilePath(resourceFolder, resourceName);\n return LockFile._tryAcquireInner(resourceFolder, resourceName, lockFilePath);\n }\n\n /**\n * @deprecated Use {@link LockFile.acquireAsync} instead.\n */\n public static acquire(resourceFolder: string, resourceName: string, maxWaitMs?: number): Promise<LockFile> {\n return LockFile.acquireAsync(resourceFolder, resourceName, maxWaitMs);\n }\n\n /**\n * Attempts to create the lockfile. Will continue to loop at every 100ms until the lock becomes available\n * or the maxWaitMs is surpassed.\n *\n * @remarks\n * This function is subject to starvation, whereby it does not ensure that the process that has been\n * waiting the longest to acquire the lock will get it first. This means that a process could theoretically\n * wait for the lock forever, while other processes skipped it in line and acquired the lock first.\n *\n * @param resourceFolder - The folder where the lock file will be created\n * @param resourceName - An alphanumeric name that describes the resource being locked. This will become\n * the filename of the temporary file created to manage the lock.\n * @param maxWaitMs - The maximum number of milliseconds to wait for the lock before reporting an error\n */\n public static async acquireAsync(\n resourceFolder: string,\n resourceName: string,\n maxWaitMs?: number\n ): Promise<LockFile> {\n const interval: number = 100;\n const startTime: number = Date.now();\n const timeoutTime: number | undefined = maxWaitMs ? startTime + maxWaitMs : undefined;\n\n await FileSystem.ensureFolderAsync(resourceFolder);\n\n const lockFilePath: string = LockFile.getLockFilePath(resourceFolder, resourceName);\n\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!timeoutTime || Date.now() <= timeoutTime) {\n const lock: LockFile | undefined = LockFile._tryAcquireInner(\n resourceFolder,\n resourceName,\n lockFilePath\n );\n if (lock) {\n return lock;\n }\n\n await Async.sleepAsync(interval);\n }\n\n throw new Error(`Exceeded maximum wait time to acquire lock for resource \"${resourceName}\"`);\n }\n\n private static _tryAcquireInner(\n resourceFolder: string,\n resourceName: string,\n lockFilePath: string\n ): LockFile | undefined {\n if (!IN_PROC_LOCKS.has(lockFilePath)) {\n switch (process.platform) {\n case 'win32': {\n return LockFile._tryAcquireWindows(lockFilePath);\n }\n\n case 'linux':\n case 'darwin': {\n return LockFile._tryAcquireMacOrLinux(resourceFolder, resourceName, lockFilePath);\n }\n\n default: {\n throw new Error(`File locking not implemented for platform: \"${process.platform}\"`);\n }\n }\n }\n }\n\n /**\n * Attempts to acquire the lock on a Linux or OSX machine\n */\n private static _tryAcquireMacOrLinux(\n resourceFolder: string,\n resourceName: string,\n pidLockFilePath: string\n ): LockFile | undefined {\n let dirtyWhenAcquired: boolean = false;\n\n // get the current process' pid\n const pid: number = process.pid;\n const startTime: string | undefined = LockFile._getStartTime(pid);\n\n if (!startTime) {\n throw new Error(`Unable to calculate start time for current process.`);\n }\n\n let lockFileHandle: FileWriter | undefined;\n\n let lockFile: LockFile;\n\n try {\n // open in write mode since if this file exists, it cannot be from the current process\n // TODO: This will malfunction if the same process tries to acquire two locks on the same file.\n // We should ideally maintain a dictionary of normalized acquired filenames\n lockFileHandle = FileWriter.open(pidLockFilePath);\n lockFileHandle.write(startTime);\n const currentBirthTimeMs: number = lockFileHandle.getStatistics().birthtime.getTime();\n\n let smallestBirthTimeMs: number = currentBirthTimeMs;\n let smallestBirthTimePid: string = pid.toString();\n\n // now, scan the directory for all lockfiles\n const files: string[] = FileSystem.readFolderItemNames(resourceFolder);\n\n // look for anything ending with # then numbers and \".lock\"\n const lockFileRegExp: RegExp = /^(.+)#([0-9]+)\\.lock$/;\n\n let match: RegExpMatchArray | null;\n let otherPid: string;\n for (const fileInFolder of files) {\n if (\n (match = fileInFolder.match(lockFileRegExp)) &&\n match[1] === resourceName &&\n (otherPid = match[2]) !== pid.toString()\n ) {\n // we found at least one lockfile hanging around that isn't ours\n const fileInFolderPath: string = `${resourceFolder}/${fileInFolder}`;\n dirtyWhenAcquired = true;\n\n // console.log(`FOUND OTHER LOCKFILE: ${otherPid}`);\n\n const otherPidCurrentStartTime: string | undefined = LockFile._getStartTime(parseInt(otherPid, 10));\n\n let otherPidOldStartTime: string | undefined;\n let otherBirthtimeMs: number | undefined;\n try {\n otherPidOldStartTime = FileSystem.readFile(fileInFolderPath);\n // check the timestamp of the file\n otherBirthtimeMs = FileSystem.getStatistics(fileInFolderPath).birthtime.getTime();\n } catch (error) {\n if (FileSystem.isNotExistError(error)) {\n // the file is already deleted by other process, skip it\n continue;\n }\n }\n\n // if the otherPidOldStartTime is invalid, then we should look at the timestamp,\n // if this file was created after us, ignore it\n // if it was created within 1 second before us, then it could be good, so we\n // will conservatively fail\n // otherwise it is an old lock file and will be deleted\n if (otherPidOldStartTime === '' && otherBirthtimeMs !== undefined) {\n if (otherBirthtimeMs > currentBirthTimeMs) {\n // ignore this file, he will be unable to get the lock since this process\n // will hold it\n // console.log(`Ignoring lock for pid ${otherPid} because its lockfile is newer than ours.`);\n continue;\n } else if (\n otherBirthtimeMs - currentBirthTimeMs < 0 && // it was created before us AND\n otherBirthtimeMs - currentBirthTimeMs > -1000\n ) {\n // it was created less than a second before\n\n // conservatively be unable to keep the lock\n return undefined;\n }\n }\n\n // console.log(`Other pid ${otherPid} lockfile has start time: \"${otherPidOldStartTime}\"`);\n // console.log(`Other pid ${otherPid} actually has start time: \"${otherPidCurrentStartTime}\"`);\n\n // this means the process is no longer executing, delete the file\n if (!otherPidCurrentStartTime || otherPidOldStartTime !== otherPidCurrentStartTime) {\n // console.log(`Other pid ${otherPid} is no longer executing!`);\n FileSystem.deleteFile(fileInFolderPath);\n continue;\n }\n\n // console.log(`Pid ${otherPid} lockfile has birth time: ${otherBirthtimeMs}`);\n // console.log(`Pid ${pid} lockfile has birth time: ${currentBirthTimeMs}`);\n // this is a lockfile pointing at something valid\n if (otherBirthtimeMs !== undefined) {\n // the other lock file was created before the current earliest lock file\n // or the other lock file was created at the same exact time, but has earlier pid\n\n // note that it is acceptable to do a direct comparison of the PIDs in this case\n // since we are establishing a consistent order to apply to the lock files in all\n // execution instances.\n\n // it doesn't matter that the PIDs roll over, we've already\n // established that these processes all started at the same time, so we just\n // need to get all instances of the lock test to agree which one won.\n if (\n otherBirthtimeMs < smallestBirthTimeMs ||\n (otherBirthtimeMs === smallestBirthTimeMs && otherPid < smallestBirthTimePid)\n ) {\n smallestBirthTimeMs = otherBirthtimeMs;\n smallestBirthTimePid = otherPid;\n }\n }\n }\n }\n\n if (smallestBirthTimePid !== pid.toString()) {\n // we do not have the lock\n return undefined;\n }\n\n // we have the lock!\n lockFile = new LockFile(lockFileHandle, pidLockFilePath, dirtyWhenAcquired);\n lockFileHandle = undefined; // we have handed the descriptor off to the instance\n } finally {\n if (lockFileHandle) {\n // ensure our lock is closed\n lockFileHandle.close();\n FileSystem.deleteFile(pidLockFilePath);\n }\n }\n return lockFile;\n }\n\n /**\n * Attempts to acquire the lock using Windows\n * This algorithm is much simpler since we can rely on the operating system\n */\n private static _tryAcquireWindows(lockFilePath: string): LockFile | undefined {\n let dirtyWhenAcquired: boolean = false;\n\n let fileHandle: FileWriter | undefined;\n let lockFile: LockFile;\n\n try {\n if (FileSystem.exists(lockFilePath)) {\n dirtyWhenAcquired = true;\n\n // If the lockfile is held by an process with an exclusive lock, then removing it will\n // silently fail. OpenSync() below will then fail and we will be unable to create a lock.\n\n // Otherwise, the lockfile is sitting on disk, but nothing is holding it, implying that\n // the last process to hold it died.\n FileSystem.deleteFile(lockFilePath);\n }\n\n try {\n // Attempt to open an exclusive lockfile\n fileHandle = FileWriter.open(lockFilePath, { exclusive: true });\n } catch (error) {\n // we tried to delete the lock, but something else is holding it,\n // (probably an active process), therefore we are unable to create a lock\n return undefined;\n }\n\n // Ensure we can hand off the file descriptor to the lockfile\n lockFile = new LockFile(fileHandle, lockFilePath, dirtyWhenAcquired);\n fileHandle = undefined;\n } finally {\n if (fileHandle) {\n fileHandle.close();\n }\n }\n\n return lockFile;\n }\n\n /**\n * Unlocks a file and optionally removes it from disk.\n * This can only be called once.\n *\n * @param deleteFile - Whether to delete the lockfile from disk. Defaults to true.\n */\n public release(deleteFile: boolean = true): void {\n if (this.isReleased) {\n throw new Error(`The lock for file \"${path.basename(this._filePath)}\" has already been released.`);\n }\n\n IN_PROC_LOCKS.delete(this._filePath);\n\n this._fileWriter!.close();\n if (deleteFile) {\n FileSystem.deleteFile(this._filePath);\n }\n\n this._fileWriter = undefined;\n }\n\n /**\n * Returns the initial state of the lock.\n * This can be used to detect if the previous process was terminated before releasing the resource.\n */\n public get dirtyWhenAcquired(): boolean {\n return this._dirtyWhenAcquired;\n }\n\n /**\n * Returns the absolute path to the lockfile\n */\n public get filePath(): string {\n return this._filePath;\n }\n\n /**\n * Returns true if this lock is currently being held.\n */\n public get isReleased(): boolean {\n return this._fileWriter === undefined;\n }\n}\n"]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"PackageJsonLookup.d.ts","sourceRoot":"","sources":["../src/PackageJsonLookup.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EA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| ||
| exports.PackageJsonLookup = void 0; | ||
| const path = __importStar(require("path")); | ||
| const path = __importStar(require("node:path")); | ||
| const JsonFile_1 = require("./JsonFile"); | ||
@@ -42,0 +42,0 @@ const Constants_1 = require("./Constants"); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"PackageJsonLookup.js","sourceRoot":"","sources":["../src/PackageJsonLookup.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,2CAA6B;AAC7B,yCAAsC;AAEtC,2CAA4C;AAC5C,6CAA0C;AA6C1C;;;;;GAKG;AACH,MAAa,iBAAiB;IAG5B;;;;;;;;;OASG;IACI,MAAM,KAAK,QAAQ;QACxB,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;YACjC,iBAAiB,CAAC,SAAS,GAAG,IAAI,iBAAiB,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,iBAAiB,CAAC,SAAS,CAAC;IACrC,CAAC;IAYD,YAAmB,UAAyC;QAVpD,qBAAgB,GAAY,KAAK,CAAC;QAWxC,IAAI,UAAU,EAAE,CAAC;YACf,IAAI,UAAU,CAAC,eAAe,EAAE,CAAC;gBAC/B,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC,eAAe,CAAC;YACrD,CAAC;QACH,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACI,MAAM,CAAC,kBAAkB,CAAC,eAAuB;QACtD,MAAM,WAAW,GACf,iBAAiB,CAAC,QAAQ,CAAC,qBAAqB,CAAC,eAAe,CAAC,CAAC;QAEpE,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;YAC9B,MAAM,IAAI,KAAK,CACb,kFAAkF;gBAChF,wBAAwB,eAAe,EAAE,CAC5C,CAAC;QACJ,CAAC;QAED,IAA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J,CAAC;IAED,gEAAgE;IACxD,uBAAuB,CAAC,wBAAgC;QAC9D,iFAAiF;QACjF,wBAAwB;QACxB,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,CAAC,EAAE,CAAC;YAC3D,OAAO,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QAChE,CAAC;QAED,iGAAiG;QACjG,MAAM,mBAAmB,GAAW,GAAG,wBAAwB,IAAI,yBAAa,CAAC,WAAW,EAAE,CAAC;QAC/F,MAAM,WAAW,GAA6B,IAAI,CAAC,qBAAqB,CACtE,mBAAmB,EACnB,IAAI,GAAG,CAAC,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CAAC,CAClD,CAAC;QACF,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;YACjF,OAAO,wBAAwB,CAAC;QAClC,CAAC;QAED,4BAA4B;QAC5B,MAAM,YAAY,GAAuB,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC;QAChF,IAAI,CAAC,YAAY,IAAI,YAAY,KAAK,wBAAwB,EAAE,CAAC;YAC/D,qEAAqE;YACrE,+BAA+B;YAC/B,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,EAAE,SAAS,CAAC,CAAC;YAClE,OAAO,SAAS,CAAC,CAAC,WAAW;QAC/B,CAAC;QAED,oDAAoD;QACpD,MAAM,YAAY,GAAuB,IAAI,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC;QACpF,oCAAoC;QACpC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;QAErE,OAAO,YAAY,CAAC;IACtB,CAAC;CACF;AA5VD,8CA4VC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'path';\nimport { JsonFile } from './JsonFile';\nimport type { IPackageJson, INodePackageJson } from './IPackageJson';\nimport { FileConstants } from './Constants';\nimport { FileSystem } from './FileSystem';\n\n/**\n * Constructor parameters for {@link PackageJsonLookup}\n *\n * @public\n */\nexport interface IPackageJsonLookupParameters {\n /**\n * Certain package.json fields such as \"contributors\" can be very large, and may\n * significantly increase the memory footprint for the PackageJsonLookup cache.\n * By default, PackageJsonLookup only loads a subset of standard commonly used\n * fields names. Set loadExtraFields=true to always return all fields.\n */\n loadExtraFields?: boolean;\n}\n\ntype TryLoadPackageJsonInternalErrorCode =\n | 'MISSING_NAME_FIELD'\n | 'FILE_NOT_FOUND'\n | 'MISSING_VERSION_FIELD'\n | 'OTHER_ERROR';\n\ninterface ITryLoadPackageJsonInternalSuccessResult {\n packageJson: IPackageJson;\n error?: never;\n}\n\ninterface ITryLoadPackageJsonInternalFailureResult {\n error: TryLoadPackageJsonInternalErrorCode;\n}\ninterface ITryLoadPackageJsonInternalKnownFailureResult extends ITryLoadPackageJsonInternalFailureResult {\n error: 'MISSING_NAME_FIELD' | 'FILE_NOT_FOUND';\n}\n\ninterface ITryLoadPackageJsonInternalUnknownFailureResult extends ITryLoadPackageJsonInternalFailureResult {\n error: 'OTHER_ERROR';\n errorObject: Error;\n}\n\ntype ITryLoadPackageJsonInternalResult =\n | ITryLoadPackageJsonInternalSuccessResult\n | ITryLoadPackageJsonInternalKnownFailureResult\n | ITryLoadPackageJsonInternalUnknownFailureResult;\n\n/**\n * This class provides methods for finding the nearest \"package.json\" for a folder\n * and retrieving the name of the package. The results are cached.\n *\n * @public\n */\nexport class PackageJsonLookup {\n private static _instance: PackageJsonLookup | undefined;\n\n /**\n * A singleton instance of `PackageJsonLookup`, which is useful for short-lived processes\n * that can reasonably assume that the file system will not be modified after the cache\n * is populated.\n *\n * @remarks\n * For long-running processes that need to clear the cache at appropriate times,\n * it is recommended to create your own instance of `PackageJsonLookup` instead\n * of relying on this instance.\n */\n public static get instance(): PackageJsonLookup {\n if (!PackageJsonLookup._instance) {\n PackageJsonLookup._instance = new PackageJsonLookup({ loadExtraFields: true });\n }\n\n return PackageJsonLookup._instance;\n }\n\n private _loadExtraFields: boolean = false;\n\n // Cached the return values for tryGetPackageFolder():\n // sourceFilePath --> packageJsonFolder\n private _packageFolderCache!: Map<string, string | undefined>;\n\n // Cached the return values for getPackageName():\n // packageJsonPath --> packageName\n private _packageJsonCache!: Map<string, IPackageJson>;\n\n public constructor(parameters?: IPackageJsonLookupParameters) {\n if (parameters) {\n if (parameters.loadExtraFields) {\n this._loadExtraFields = parameters.loadExtraFields;\n }\n }\n this.clearCache();\n }\n\n /**\n * A helper for loading the caller's own package.json file.\n *\n * @remarks\n *\n * This function provides a concise and efficient way for an NPM package to report metadata about itself.\n * For example, a tool might want to report its version.\n *\n * The `loadOwnPackageJson()` probes upwards from the caller's folder, expecting to find a package.json file,\n * which is assumed to be the caller's package. The result is cached, under the assumption that a tool's\n * own package.json (and intermediary folders) will never change during the lifetime of the process.\n *\n * @example\n * ```ts\n * // Report the version of our NPM package\n * const myPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname).version;\n * console.log(`Cool Tool - Version ${myPackageVersion}`);\n * ```\n *\n * @param dirnameOfCaller - The NodeJS `__dirname` macro for the caller.\n * @returns This function always returns a valid `IPackageJson` object. If any problems are encountered during\n * loading, an exception will be thrown instead.\n */\n public static loadOwnPackageJson(dirnameOfCaller: string): IPackageJson {\n const packageJson: IPackageJson | undefined =\n PackageJsonLookup.instance.tryLoadPackageJsonFor(dirnameOfCaller);\n\n if (packageJson === undefined) {\n throw new Error(\n `PackageJsonLookup.loadOwnPackageJson() failed to find the caller's package.json.` +\n ` The __dirname was: ${dirnameOfCaller}`\n );\n }\n\n if (packageJson.version !== undefined) {\n return packageJson as IPackageJson;\n }\n\n const errorPath: string =\n PackageJsonLookup.instance.tryGetPackageJsonFilePathFor(dirnameOfCaller) || 'package.json';\n throw new Error(\n `PackageJsonLookup.loadOwnPackageJson() failed because the \"version\" field is missing in` +\n ` ${errorPath}`\n );\n }\n\n /**\n * Clears the internal file cache.\n * @remarks\n * Call this method if changes have been made to the package.json files on disk.\n */\n public clearCache(): void {\n this._packageFolderCache = new Map<string, string | undefined>();\n this._packageJsonCache = new Map<string, IPackageJson>();\n }\n\n /**\n * Returns the absolute path of a folder containing a package.json file, by looking\n * upwards from the specified fileOrFolderPath. If no package.json can be found,\n * undefined is returned.\n *\n * @remarks\n * The fileOrFolderPath is not required to actually exist on disk.\n * The fileOrFolderPath itself can be the return value, if it is a folder containing\n * a package.json file.\n * Both positive and negative lookup results are cached.\n *\n * @param fileOrFolderPath - a relative or absolute path to a source file or folder\n * that may be part of a package\n * @returns an absolute path to a folder containing a package.json file\n */\n public tryGetPackageFolderFor(fileOrFolderPath: string): string | undefined {\n // Convert it to an absolute path\n const resolvedFileOrFolderPath: string = path.resolve(fileOrFolderPath);\n\n // Optimistically hope that the starting string is already in the cache,\n // in which case we can avoid disk access entirely.\n //\n // (Two lookups are required, because get() cannot distinguish the undefined value\n // versus a missing key.)\n if (this._packageFolderCache.has(resolvedFileOrFolderPath)) {\n return this._packageFolderCache.get(resolvedFileOrFolderPath);\n }\n\n // Now call the recursive part of the algorithm\n return this._tryGetPackageFolderFor(resolvedFileOrFolderPath);\n }\n\n /**\n * If the specified file or folder is part of a package, this returns the absolute path\n * to the associated package.json file.\n *\n * @remarks\n * The package folder is determined using the same algorithm\n * as {@link PackageJsonLookup.tryGetPackageFolderFor}.\n *\n * @param fileOrFolderPath - a relative or absolute path to a source file or folder\n * that may be part of a package\n * @returns an absolute path to * package.json file\n */\n public tryGetPackageJsonFilePathFor(fileOrFolderPath: string): string | undefined {\n const packageJsonFolder: string | undefined = this.tryGetPackageFolderFor(fileOrFolderPath);\n if (!packageJsonFolder) {\n return undefined;\n }\n return path.join(packageJsonFolder, FileConstants.PackageJson);\n }\n\n /**\n * If the specified file or folder is part of a package, this loads and returns the\n * associated package.json file.\n *\n * @remarks\n * The package folder is determined using the same algorithm\n * as {@link PackageJsonLookup.tryGetPackageFolderFor}.\n *\n * @param fileOrFolderPath - a relative or absolute path to a source file or folder\n * that may be part of a package\n * @returns an IPackageJson object, or undefined if the fileOrFolderPath does not\n * belong to a package\n */\n public tryLoadPackageJsonFor(fileOrFolderPath: string): IPackageJson | undefined {\n const packageJsonFilePath: string | undefined = this.tryGetPackageJsonFilePathFor(fileOrFolderPath);\n if (!packageJsonFilePath) {\n return undefined;\n }\n return this.loadPackageJson(packageJsonFilePath);\n }\n\n /**\n * This function is similar to {@link PackageJsonLookup.tryLoadPackageJsonFor}, except that it does not report\n * an error if the `version` field is missing from the package.json file.\n */\n public tryLoadNodePackageJsonFor(fileOrFolderPath: string): INodePackageJson | undefined {\n const packageJsonFilePath: string | undefined = this.tryGetPackageJsonFilePathFor(fileOrFolderPath);\n if (!packageJsonFilePath) {\n return undefined;\n }\n return this.loadNodePackageJson(packageJsonFilePath);\n }\n\n /**\n * Loads the specified package.json file, if it is not already present in the cache.\n *\n * @remarks\n * Unless {@link IPackageJsonLookupParameters.loadExtraFields} was specified,\n * the returned IPackageJson object will contain a subset of essential fields.\n * The returned object should be considered to be immutable; the caller must never\n * modify it.\n *\n * @param jsonFilename - a relative or absolute path to a package.json file\n */\n public loadPackageJson(jsonFilename: string): IPackageJson {\n const packageJson: INodePackageJson = this.loadNodePackageJson(jsonFilename);\n\n if (!packageJson.version) {\n throw new Error(`Error reading \"${jsonFilename}\":\\n The required field \"version\" was not found`);\n }\n\n return packageJson as IPackageJson;\n }\n\n /**\n * This function is similar to {@link PackageJsonLookup.loadPackageJson}, except that it does not report an error\n * if the `version` field is missing from the package.json file.\n */\n public loadNodePackageJson(jsonFilename: string): INodePackageJson {\n return this._loadPackageJsonInner(jsonFilename);\n }\n\n private _loadPackageJsonInner(jsonFilename: string): IPackageJson;\n private _loadPackageJsonInner(\n jsonFilename: string,\n errorsToIgnore: Set<TryLoadPackageJsonInternalErrorCode>\n ): IPackageJson | undefined;\n private _loadPackageJsonInner(\n jsonFilename: string,\n errorsToIgnore?: Set<TryLoadPackageJsonInternalErrorCode>\n ): IPackageJson | undefined {\n const loadResult: ITryLoadPackageJsonInternalResult = this._tryLoadNodePackageJsonInner(jsonFilename);\n\n if (loadResult.error && errorsToIgnore?.has(loadResult.error)) {\n return undefined;\n }\n\n switch (loadResult.error) {\n case 'FILE_NOT_FOUND': {\n throw new Error(`Input file not found: ${jsonFilename}`);\n }\n\n case 'MISSING_NAME_FIELD': {\n throw new Error(`Error reading \"${jsonFilename}\":\\n The required field \"name\" was not found`);\n }\n\n case 'OTHER_ERROR': {\n throw loadResult.errorObject;\n }\n\n default: {\n return loadResult.packageJson;\n }\n }\n }\n\n /**\n * Try to load a package.json file as an INodePackageJson,\n * returning undefined if the found file does not contain a `name` field.\n */\n private _tryLoadNodePackageJsonInner(jsonFilename: string): ITryLoadPackageJsonInternalResult {\n // Since this will be a cache key, follow any symlinks and get an absolute path\n // to minimize duplication. (Note that duplication can still occur due to e.g. character case.)\n let normalizedFilePath: string;\n try {\n normalizedFilePath = FileSystem.getRealPath(jsonFilename);\n } catch (e) {\n if (FileSystem.isNotExistError(e)) {\n return {\n error: 'FILE_NOT_FOUND'\n };\n } else {\n return {\n error: 'OTHER_ERROR',\n errorObject: e\n };\n }\n }\n\n let packageJson: IPackageJson | undefined = this._packageJsonCache.get(normalizedFilePath);\n\n if (!packageJson) {\n const loadedPackageJson: IPackageJson = JsonFile.load(normalizedFilePath);\n\n // Make sure this is really a package.json file. CommonJS has fairly strict requirements,\n // but NPM only requires \"name\" and \"version\"\n if (!loadedPackageJson.name) {\n return {\n error: 'MISSING_NAME_FIELD'\n };\n }\n\n if (this._loadExtraFields) {\n packageJson = loadedPackageJson;\n } else {\n packageJson = {} as IPackageJson;\n\n // Unless \"loadExtraFields\" was requested, copy over the essential fields only\n packageJson.bin = loadedPackageJson.bin;\n packageJson.dependencies = loadedPackageJson.dependencies;\n packageJson.description = loadedPackageJson.description;\n packageJson.devDependencies = loadedPackageJson.devDependencies;\n packageJson.exports = loadedPackageJson.exports;\n packageJson.homepage = loadedPackageJson.homepage;\n packageJson.license = loadedPackageJson.license;\n packageJson.main = loadedPackageJson.main;\n packageJson.name = loadedPackageJson.name;\n packageJson.optionalDependencies = loadedPackageJson.optionalDependencies;\n packageJson.peerDependencies = loadedPackageJson.peerDependencies;\n packageJson.private = loadedPackageJson.private;\n packageJson.scripts = loadedPackageJson.scripts;\n packageJson.tsdocMetadata = loadedPackageJson.tsdocMetadata;\n packageJson.typings = loadedPackageJson.typings || loadedPackageJson.types;\n packageJson.version = loadedPackageJson.version;\n }\n\n Object.freeze(packageJson);\n this._packageJsonCache.set(normalizedFilePath, packageJson);\n }\n\n return {\n packageJson\n };\n }\n\n // Recursive part of the algorithm from tryGetPackageFolderFor()\n private _tryGetPackageFolderFor(resolvedFileOrFolderPath: string): string | undefined {\n // Two lookups are required, because get() cannot distinguish the undefined value\n // versus a missing key.\n if (this._packageFolderCache.has(resolvedFileOrFolderPath)) {\n return this._packageFolderCache.get(resolvedFileOrFolderPath);\n }\n\n // Is resolvedFileOrFolderPath itself a folder with a valid package.json file? If so, return it.\n const packageJsonFilePath: string = `${resolvedFileOrFolderPath}/${FileConstants.PackageJson}`;\n const packageJson: IPackageJson | undefined = this._loadPackageJsonInner(\n packageJsonFilePath,\n new Set(['FILE_NOT_FOUND', 'MISSING_NAME_FIELD'])\n );\n if (packageJson) {\n this._packageFolderCache.set(resolvedFileOrFolderPath, resolvedFileOrFolderPath);\n return resolvedFileOrFolderPath;\n }\n\n // Otherwise go up one level\n const parentFolder: string | undefined = path.dirname(resolvedFileOrFolderPath);\n if (!parentFolder || parentFolder === resolvedFileOrFolderPath) {\n // We reached the root directory without finding a package.json file,\n // so cache the negative result\n this._packageFolderCache.set(resolvedFileOrFolderPath, undefined);\n return undefined; // no match\n }\n\n // Recurse upwards, caching every step along the way\n const parentResult: string | undefined = this._tryGetPackageFolderFor(parentFolder);\n // Cache the parent's answer as well\n this._packageFolderCache.set(resolvedFileOrFolderPath, parentResult);\n\n return parentResult;\n }\n}\n"]} | ||
| {"version":3,"file":"PackageJsonLookup.js","sourceRoot":"","sources":["../src/PackageJsonLookup.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,gDAAkC;AAElC,yCAAsC;AAEtC,2CAA4C;AAC5C,6CAA0C;AA6C1C;;;;;GAKG;AACH,MAAa,iBAAiB;IAG5B;;;;;;;;;OASG;IACI,MAAM,KAAK,QAAQ;QACxB,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;YACjC,iBAAiB,CAAC,SAAS,GAAG,IAAI,iBAAiB,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,iBAAiB,CAAC,SAAS,CAAC;IACrC,CAAC;IAYD,YAAmB,UAAyC;QAVpD,qBAAgB,GAAY,KAAK,CAAC;QAWxC,IAAI,UAAU,EAAE,CAAC;YACf,IAAI,UAAU,CAAC,eAAe,EAAE,CAAC;gBAC/B,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC,eAAe,CAAC;YACrD,CAAC;QACH,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACI,MAAM,CAAC,kBAAkB,CAAC,eAAuB;QACtD,MAAM,WAAW,GACf,iBAAiB,CAAC,QAAQ,CAAC,qBAAqB,CAAC,eAAe,CAAC,CAAC;QAEpE,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;YAC9B,MAAM,IAAI,KAAK,CACb,kFAAkF;gBAChF,wBAAwB,eAAe,EAAE,CAC5C,CAAC;QACJ,CAAC;QAED,IAAI,WAAW,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YACtC,OAAO,WAA2B,CAAC;QACrC,CAAC;QAED,MAAM,SAAS,G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CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,CAAC,EAAE,CAAC;YAC3D,OAAO,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QAChE,CAAC;QAED,iGAAiG;QACjG,MAAM,mBAAmB,GAAW,GAAG,wBAAwB,IAAI,yBAAa,CAAC,WAAW,EAAE,CAAC;QAC/F,MAAM,WAAW,GAA6B,IAAI,CAAC,qBAAqB,CACtE,mBAAmB,EACnB,IAAI,GAAG,CAAC,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CAAC,CAClD,CAAC;QACF,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;YACjF,OAAO,wBAAwB,CAAC;QAClC,CAAC;QAED,4BAA4B;QAC5B,MAAM,YAAY,GAAuB,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC;QAChF,IAAI,CAAC,YAAY,IAAI,YAAY,KAAK,wBAAwB,EAAE,CAAC;YAC/D,qEAAqE;YACrE,+BAA+B;YAC/B,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,EAAE,SAAS,CAAC,CAAC;YAClE,OAAO,SAAS,CAAC,CAAC,WAAW;QAC/B,CAAC;QAED,oDAAoD;QACpD,MAAM,YAAY,GAAuB,IAAI,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC;QACpF,oCAAoC;QACpC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;QAErE,OAAO,YAAY,CAAC;IACtB,CAAC;CACF;AA5VD,8CA4VC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'node:path';\n\nimport { JsonFile } from './JsonFile';\nimport type { IPackageJson, INodePackageJson } from './IPackageJson';\nimport { FileConstants } from './Constants';\nimport { FileSystem } from './FileSystem';\n\n/**\n * Constructor parameters for {@link PackageJsonLookup}\n *\n * @public\n */\nexport interface IPackageJsonLookupParameters {\n /**\n * Certain package.json fields such as \"contributors\" can be very large, and may\n * significantly increase the memory footprint for the PackageJsonLookup cache.\n * By default, PackageJsonLookup only loads a subset of standard commonly used\n * fields names. Set loadExtraFields=true to always return all fields.\n */\n loadExtraFields?: boolean;\n}\n\ntype TryLoadPackageJsonInternalErrorCode =\n | 'MISSING_NAME_FIELD'\n | 'FILE_NOT_FOUND'\n | 'MISSING_VERSION_FIELD'\n | 'OTHER_ERROR';\n\ninterface ITryLoadPackageJsonInternalSuccessResult {\n packageJson: IPackageJson;\n error?: never;\n}\n\ninterface ITryLoadPackageJsonInternalFailureResult {\n error: TryLoadPackageJsonInternalErrorCode;\n}\ninterface ITryLoadPackageJsonInternalKnownFailureResult extends ITryLoadPackageJsonInternalFailureResult {\n error: 'MISSING_NAME_FIELD' | 'FILE_NOT_FOUND';\n}\n\ninterface ITryLoadPackageJsonInternalUnknownFailureResult extends ITryLoadPackageJsonInternalFailureResult {\n error: 'OTHER_ERROR';\n errorObject: Error;\n}\n\ntype ITryLoadPackageJsonInternalResult =\n | ITryLoadPackageJsonInternalSuccessResult\n | ITryLoadPackageJsonInternalKnownFailureResult\n | ITryLoadPackageJsonInternalUnknownFailureResult;\n\n/**\n * This class provides methods for finding the nearest \"package.json\" for a folder\n * and retrieving the name of the package. The results are cached.\n *\n * @public\n */\nexport class PackageJsonLookup {\n private static _instance: PackageJsonLookup | undefined;\n\n /**\n * A singleton instance of `PackageJsonLookup`, which is useful for short-lived processes\n * that can reasonably assume that the file system will not be modified after the cache\n * is populated.\n *\n * @remarks\n * For long-running processes that need to clear the cache at appropriate times,\n * it is recommended to create your own instance of `PackageJsonLookup` instead\n * of relying on this instance.\n */\n public static get instance(): PackageJsonLookup {\n if (!PackageJsonLookup._instance) {\n PackageJsonLookup._instance = new PackageJsonLookup({ loadExtraFields: true });\n }\n\n return PackageJsonLookup._instance;\n }\n\n private _loadExtraFields: boolean = false;\n\n // Cached the return values for tryGetPackageFolder():\n // sourceFilePath --> packageJsonFolder\n private _packageFolderCache!: Map<string, string | undefined>;\n\n // Cached the return values for getPackageName():\n // packageJsonPath --> packageName\n private _packageJsonCache!: Map<string, IPackageJson>;\n\n public constructor(parameters?: IPackageJsonLookupParameters) {\n if (parameters) {\n if (parameters.loadExtraFields) {\n this._loadExtraFields = parameters.loadExtraFields;\n }\n }\n this.clearCache();\n }\n\n /**\n * A helper for loading the caller's own package.json file.\n *\n * @remarks\n *\n * This function provides a concise and efficient way for an NPM package to report metadata about itself.\n * For example, a tool might want to report its version.\n *\n * The `loadOwnPackageJson()` probes upwards from the caller's folder, expecting to find a package.json file,\n * which is assumed to be the caller's package. The result is cached, under the assumption that a tool's\n * own package.json (and intermediary folders) will never change during the lifetime of the process.\n *\n * @example\n * ```ts\n * // Report the version of our NPM package\n * const myPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname).version;\n * console.log(`Cool Tool - Version ${myPackageVersion}`);\n * ```\n *\n * @param dirnameOfCaller - The NodeJS `__dirname` macro for the caller.\n * @returns This function always returns a valid `IPackageJson` object. If any problems are encountered during\n * loading, an exception will be thrown instead.\n */\n public static loadOwnPackageJson(dirnameOfCaller: string): IPackageJson {\n const packageJson: IPackageJson | undefined =\n PackageJsonLookup.instance.tryLoadPackageJsonFor(dirnameOfCaller);\n\n if (packageJson === undefined) {\n throw new Error(\n `PackageJsonLookup.loadOwnPackageJson() failed to find the caller's package.json.` +\n ` The __dirname was: ${dirnameOfCaller}`\n );\n }\n\n if (packageJson.version !== undefined) {\n return packageJson as IPackageJson;\n }\n\n const errorPath: string =\n PackageJsonLookup.instance.tryGetPackageJsonFilePathFor(dirnameOfCaller) || 'package.json';\n throw new Error(\n `PackageJsonLookup.loadOwnPackageJson() failed because the \"version\" field is missing in` +\n ` ${errorPath}`\n );\n }\n\n /**\n * Clears the internal file cache.\n * @remarks\n * Call this method if changes have been made to the package.json files on disk.\n */\n public clearCache(): void {\n this._packageFolderCache = new Map<string, string | undefined>();\n this._packageJsonCache = new Map<string, IPackageJson>();\n }\n\n /**\n * Returns the absolute path of a folder containing a package.json file, by looking\n * upwards from the specified fileOrFolderPath. If no package.json can be found,\n * undefined is returned.\n *\n * @remarks\n * The fileOrFolderPath is not required to actually exist on disk.\n * The fileOrFolderPath itself can be the return value, if it is a folder containing\n * a package.json file.\n * Both positive and negative lookup results are cached.\n *\n * @param fileOrFolderPath - a relative or absolute path to a source file or folder\n * that may be part of a package\n * @returns an absolute path to a folder containing a package.json file\n */\n public tryGetPackageFolderFor(fileOrFolderPath: string): string | undefined {\n // Convert it to an absolute path\n const resolvedFileOrFolderPath: string = path.resolve(fileOrFolderPath);\n\n // Optimistically hope that the starting string is already in the cache,\n // in which case we can avoid disk access entirely.\n //\n // (Two lookups are required, because get() cannot distinguish the undefined value\n // versus a missing key.)\n if (this._packageFolderCache.has(resolvedFileOrFolderPath)) {\n return this._packageFolderCache.get(resolvedFileOrFolderPath);\n }\n\n // Now call the recursive part of the algorithm\n return this._tryGetPackageFolderFor(resolvedFileOrFolderPath);\n }\n\n /**\n * If the specified file or folder is part of a package, this returns the absolute path\n * to the associated package.json file.\n *\n * @remarks\n * The package folder is determined using the same algorithm\n * as {@link PackageJsonLookup.tryGetPackageFolderFor}.\n *\n * @param fileOrFolderPath - a relative or absolute path to a source file or folder\n * that may be part of a package\n * @returns an absolute path to * package.json file\n */\n public tryGetPackageJsonFilePathFor(fileOrFolderPath: string): string | undefined {\n const packageJsonFolder: string | undefined = this.tryGetPackageFolderFor(fileOrFolderPath);\n if (!packageJsonFolder) {\n return undefined;\n }\n return path.join(packageJsonFolder, FileConstants.PackageJson);\n }\n\n /**\n * If the specified file or folder is part of a package, this loads and returns the\n * associated package.json file.\n *\n * @remarks\n * The package folder is determined using the same algorithm\n * as {@link PackageJsonLookup.tryGetPackageFolderFor}.\n *\n * @param fileOrFolderPath - a relative or absolute path to a source file or folder\n * that may be part of a package\n * @returns an IPackageJson object, or undefined if the fileOrFolderPath does not\n * belong to a package\n */\n public tryLoadPackageJsonFor(fileOrFolderPath: string): IPackageJson | undefined {\n const packageJsonFilePath: string | undefined = this.tryGetPackageJsonFilePathFor(fileOrFolderPath);\n if (!packageJsonFilePath) {\n return undefined;\n }\n return this.loadPackageJson(packageJsonFilePath);\n }\n\n /**\n * This function is similar to {@link PackageJsonLookup.tryLoadPackageJsonFor}, except that it does not report\n * an error if the `version` field is missing from the package.json file.\n */\n public tryLoadNodePackageJsonFor(fileOrFolderPath: string): INodePackageJson | undefined {\n const packageJsonFilePath: string | undefined = this.tryGetPackageJsonFilePathFor(fileOrFolderPath);\n if (!packageJsonFilePath) {\n return undefined;\n }\n return this.loadNodePackageJson(packageJsonFilePath);\n }\n\n /**\n * Loads the specified package.json file, if it is not already present in the cache.\n *\n * @remarks\n * Unless {@link IPackageJsonLookupParameters.loadExtraFields} was specified,\n * the returned IPackageJson object will contain a subset of essential fields.\n * The returned object should be considered to be immutable; the caller must never\n * modify it.\n *\n * @param jsonFilename - a relative or absolute path to a package.json file\n */\n public loadPackageJson(jsonFilename: string): IPackageJson {\n const packageJson: INodePackageJson = this.loadNodePackageJson(jsonFilename);\n\n if (!packageJson.version) {\n throw new Error(`Error reading \"${jsonFilename}\":\\n The required field \"version\" was not found`);\n }\n\n return packageJson as IPackageJson;\n }\n\n /**\n * This function is similar to {@link PackageJsonLookup.loadPackageJson}, except that it does not report an error\n * if the `version` field is missing from the package.json file.\n */\n public loadNodePackageJson(jsonFilename: string): INodePackageJson {\n return this._loadPackageJsonInner(jsonFilename);\n }\n\n private _loadPackageJsonInner(jsonFilename: string): IPackageJson;\n private _loadPackageJsonInner(\n jsonFilename: string,\n errorsToIgnore: Set<TryLoadPackageJsonInternalErrorCode>\n ): IPackageJson | undefined;\n private _loadPackageJsonInner(\n jsonFilename: string,\n errorsToIgnore?: Set<TryLoadPackageJsonInternalErrorCode>\n ): IPackageJson | undefined {\n const loadResult: ITryLoadPackageJsonInternalResult = this._tryLoadNodePackageJsonInner(jsonFilename);\n\n if (loadResult.error && errorsToIgnore?.has(loadResult.error)) {\n return undefined;\n }\n\n switch (loadResult.error) {\n case 'FILE_NOT_FOUND': {\n throw new Error(`Input file not found: ${jsonFilename}`);\n }\n\n case 'MISSING_NAME_FIELD': {\n throw new Error(`Error reading \"${jsonFilename}\":\\n The required field \"name\" was not found`);\n }\n\n case 'OTHER_ERROR': {\n throw loadResult.errorObject;\n }\n\n default: {\n return loadResult.packageJson;\n }\n }\n }\n\n /**\n * Try to load a package.json file as an INodePackageJson,\n * returning undefined if the found file does not contain a `name` field.\n */\n private _tryLoadNodePackageJsonInner(jsonFilename: string): ITryLoadPackageJsonInternalResult {\n // Since this will be a cache key, follow any symlinks and get an absolute path\n // to minimize duplication. (Note that duplication can still occur due to e.g. character case.)\n let normalizedFilePath: string;\n try {\n normalizedFilePath = FileSystem.getRealPath(jsonFilename);\n } catch (e) {\n if (FileSystem.isNotExistError(e)) {\n return {\n error: 'FILE_NOT_FOUND'\n };\n } else {\n return {\n error: 'OTHER_ERROR',\n errorObject: e\n };\n }\n }\n\n let packageJson: IPackageJson | undefined = this._packageJsonCache.get(normalizedFilePath);\n\n if (!packageJson) {\n const loadedPackageJson: IPackageJson = JsonFile.load(normalizedFilePath);\n\n // Make sure this is really a package.json file. CommonJS has fairly strict requirements,\n // but NPM only requires \"name\" and \"version\"\n if (!loadedPackageJson.name) {\n return {\n error: 'MISSING_NAME_FIELD'\n };\n }\n\n if (this._loadExtraFields) {\n packageJson = loadedPackageJson;\n } else {\n packageJson = {} as IPackageJson;\n\n // Unless \"loadExtraFields\" was requested, copy over the essential fields only\n packageJson.bin = loadedPackageJson.bin;\n packageJson.dependencies = loadedPackageJson.dependencies;\n packageJson.description = loadedPackageJson.description;\n packageJson.devDependencies = loadedPackageJson.devDependencies;\n packageJson.exports = loadedPackageJson.exports;\n packageJson.homepage = loadedPackageJson.homepage;\n packageJson.license = loadedPackageJson.license;\n packageJson.main = loadedPackageJson.main;\n packageJson.name = loadedPackageJson.name;\n packageJson.optionalDependencies = loadedPackageJson.optionalDependencies;\n packageJson.peerDependencies = loadedPackageJson.peerDependencies;\n packageJson.private = loadedPackageJson.private;\n packageJson.scripts = loadedPackageJson.scripts;\n packageJson.tsdocMetadata = loadedPackageJson.tsdocMetadata;\n packageJson.typings = loadedPackageJson.typings || loadedPackageJson.types;\n packageJson.version = loadedPackageJson.version;\n }\n\n Object.freeze(packageJson);\n this._packageJsonCache.set(normalizedFilePath, packageJson);\n }\n\n return {\n packageJson\n };\n }\n\n // Recursive part of the algorithm from tryGetPackageFolderFor()\n private _tryGetPackageFolderFor(resolvedFileOrFolderPath: string): string | undefined {\n // Two lookups are required, because get() cannot distinguish the undefined value\n // versus a missing key.\n if (this._packageFolderCache.has(resolvedFileOrFolderPath)) {\n return this._packageFolderCache.get(resolvedFileOrFolderPath);\n }\n\n // Is resolvedFileOrFolderPath itself a folder with a valid package.json file? If so, return it.\n const packageJsonFilePath: string = `${resolvedFileOrFolderPath}/${FileConstants.PackageJson}`;\n const packageJson: IPackageJson | undefined = this._loadPackageJsonInner(\n packageJsonFilePath,\n new Set(['FILE_NOT_FOUND', 'MISSING_NAME_FIELD'])\n );\n if (packageJson) {\n this._packageFolderCache.set(resolvedFileOrFolderPath, resolvedFileOrFolderPath);\n return resolvedFileOrFolderPath;\n }\n\n // Otherwise go up one level\n const parentFolder: string | undefined = path.dirname(resolvedFileOrFolderPath);\n if (!parentFolder || parentFolder === resolvedFileOrFolderPath) {\n // We reached the root directory without finding a package.json file,\n // so cache the negative result\n this._packageFolderCache.set(resolvedFileOrFolderPath, undefined);\n return undefined; // no match\n }\n\n // Recurse upwards, caching every step along the way\n const parentResult: string | undefined = this._tryGetPackageFolderFor(parentFolder);\n // Cache the parent's answer as well\n this._packageFolderCache.set(resolvedFileOrFolderPath, parentResult);\n\n return parentResult;\n }\n}\n"]} |
+1
-1
@@ -39,3 +39,3 @@ "use strict"; | ||
| exports.Path = void 0; | ||
| const path = __importStar(require("path")); | ||
| const path = __importStar(require("node:path")); | ||
| /** | ||
@@ -42,0 +42,0 @@ * Common operations for manipulating file and directory paths. |
+1
-1
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Path.js","sourceRoot":"","sources":["../src/Path.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,2CAA6B;AAkE7B;;;;;GAKG;AACH,MAAa,IAAI;IASf;;;;;;;;;OASG;IACI,MAAM,CAAC,OAAO,CAAC,SAAiB,EAAE,gBAAwB;QAC/D,6EAA6E;QAC7E,uEAAuE;QACvE,sFAAsF;QACtF,MAAM,YAAY,GAAW,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;QACxE,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACpD,CAAC;IAED;;;;;;;;OAQG;IACI,MAAM,CAAC,cAAc,CAAC,SAAiB,EAAE,gBAAwB;QACtE,MAAM,YAAY,GAAW,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;QACxE,OAAO,YAAY,KAAK,EAAE,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC3E,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,OAAO,CAAC,KAAa,EAAE,KAAa;QAChD,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;IAC5C,CAAC;IAED;;;;;;;;OAQG;IACI,MAAM,CAAC,eAAe,CAAC,OAAoC;QAChE,sCAAsC;QACtC,MAAM,YAAY,GAAW,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QACtF,MAAM,cAAc,GAAY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AAiB;QAChD,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;YAC/B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,uBAAuB;QACvB,IAAI,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;;AA9LH,oBA+LC;AA9LC,qEAAqE;AACrE,mCAAmC;AACpB,uBAAkB,GAAW,YAAY,CAAC;AAEzD,yDAAyD;AACzD,oBAAoB;AACL,4BAAuB,GAAW,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'path';\n\n/**\n * The format that the FileError message should conform to. The supported formats are:\n * - Unix: `<path>:<line>:<column> - <message>`\n * - VisualStudio: `<path>(<line>,<column>) - <message>`\n *\n * @public\n */\nexport type FileLocationStyle = 'Unix' | 'VisualStudio';\n\n/**\n * Options for {@link Path.formatFileLocation}.\n * @public\n */\nexport interface IPathFormatFileLocationOptions {\n /**\n * The base path to use when converting `pathToFormat` to a relative path. If not specified,\n * `pathToFormat` will be used as-is.\n */\n baseFolder?: string;\n /**\n * The path that will be used to specify the file location.\n */\n pathToFormat: string;\n /**\n * The message related to the file location.\n */\n message: string;\n /**\n * The style of file location formatting to use.\n */\n format: FileLocationStyle;\n /**\n * The optional line number. If not specified, the line number will not be included\n * in the formatted string.\n */\n line?: number;\n /**\n * The optional column number. If not specified, the column number will not be included\n * in the formatted string.\n */\n column?: number;\n}\n\n/**\n * Options for {@link Path.formatConcisely}.\n * @public\n */\nexport interface IPathFormatConciselyOptions {\n /**\n * The path to be converted.\n */\n pathToConvert: string;\n\n /**\n * The base path to use when converting `pathToConvert` to a relative path.\n */\n baseFolder: string;\n\n /**\n * If set to true, don't include the leading `./` if the path is under the base folder.\n */\n trimLeadingDotSlash?: boolean;\n}\n\n/**\n * Common operations for manipulating file and directory paths.\n * @remarks\n * This API is intended to eventually be a complete replacement for the NodeJS \"path\" API.\n * @public\n */\nexport class Path {\n // Matches a relative path consisting entirely of periods and slashes\n // Example: \".\", \"..\", \"../..\", etc\n private static _relativePathRegex: RegExp = /^[.\\/\\\\]+$/;\n\n // Matches a relative path segment that traverses upwards\n // Example: \"a/../b\"\n private static _upwardPathSegmentRegex: RegExp = /([\\/\\\\]|^)\\.\\.([\\/\\\\]|$)/;\n\n /**\n * Returns true if \"childPath\" is located inside the \"parentFolderPath\" folder\n * or one of its child folders. Note that \"parentFolderPath\" is not considered to be\n * under itself. The \"childPath\" can refer to any type of file system object.\n *\n * @remarks\n * The indicated file/folder objects are not required to actually exist on disk.\n * For example, \"parentFolderPath\" is interpreted as a folder name even if it refers to a file.\n * If the paths are relative, they will first be resolved using path.resolve().\n */\n public static isUnder(childPath: string, parentFolderPath: string): boolean {\n // If childPath is under parentPath, then relativePath will be something like\n // \"../..\" or \"..\\\\..\", which consists entirely of periods and slashes.\n // (Note that something like \"....t\" is actually a valid filename, but \"....\" is not.)\n const relativePath: string = path.relative(childPath, parentFolderPath);\n return Path._relativePathRegex.test(relativePath);\n }\n\n /**\n * Returns true if \"childPath\" is equal to \"parentFolderPath\", or if it is inside that folder\n * or one of its children. The \"childPath\" can refer to any type of file system object.\n *\n * @remarks\n * The indicated file/folder objects are not required to actually exist on disk.\n * For example, \"parentFolderPath\" is interpreted as a folder name even if it refers to a file.\n * If the paths are relative, they will first be resolved using path.resolve().\n */\n public static isUnderOrEqual(childPath: string, parentFolderPath: string): boolean {\n const relativePath: string = path.relative(childPath, parentFolderPath);\n return relativePath === '' || Path._relativePathRegex.test(relativePath);\n }\n\n /**\n * Returns true if `path1` and `path2` refer to the same underlying path.\n *\n * @remarks\n *\n * The comparison is performed using `path.relative()`.\n */\n public static isEqual(path1: string, path2: string): boolean {\n return path.relative(path1, path2) === '';\n }\n\n /**\n * Formats a path to look nice for reporting purposes.\n * @remarks\n * If `pathToConvert` is under the `baseFolder`, then it will be converted to a relative with the `./` prefix\n * unless the {@link IPathFormatConciselyOptions.trimLeadingDotSlash} option is set to `true`.\n * Otherwise, it will be converted to an absolute path.\n *\n * Backslashes will be converted to slashes, unless the path starts with an OS-specific string like `C:\\`.\n */\n public static formatConcisely(options: IPathFormatConciselyOptions): string {\n // Same logic as Path.isUnderOrEqual()\n const relativePath: string = path.relative(options.pathToConvert, options.baseFolder);\n const isUnderOrEqual: boolean = relativePath === '' || Path._relativePathRegex.test(relativePath);\n\n if (isUnderOrEqual) {\n // Note that isUnderOrEqual()'s relativePath is the reverse direction\n const convertedPath: string = Path.convertToSlashes(\n path.relative(options.baseFolder, options.pathToConvert)\n );\n if (options.trimLeadingDotSlash) {\n return convertedPath;\n } else {\n return `./${convertedPath}`;\n }\n }\n\n const absolutePath: string = path.resolve(options.pathToConvert);\n return absolutePath;\n }\n\n /**\n * Formats a file location to look nice for reporting purposes.\n * @remarks\n * If `pathToFormat` is under the `baseFolder`, then it will be converted to a relative with the `./` prefix.\n * Otherwise, it will be converted to an absolute path.\n *\n * Backslashes will be converted to slashes, unless the path starts with an OS-specific string like `C:\\`.\n */\n public static formatFileLocation(options: IPathFormatFileLocationOptions): string {\n const { message, format, pathToFormat, baseFolder, line, column } = options;\n\n // Convert the path to be relative to the base folder, if specified. Otherwise, use\n // the path as-is.\n const filePath: string = baseFolder\n ? Path.formatConcisely({\n pathToConvert: pathToFormat,\n baseFolder,\n trimLeadingDotSlash: true\n })\n : path.resolve(pathToFormat);\n\n let formattedFileLocation: string;\n switch (format) {\n case 'Unix': {\n if (line !== undefined && column !== undefined) {\n formattedFileLocation = `:${line}:${column}`;\n } else if (line !== undefined) {\n formattedFileLocation = `:${line}`;\n } else {\n formattedFileLocation = '';\n }\n\n break;\n }\n\n case 'VisualStudio': {\n if (line !== undefined && column !== undefined) {\n formattedFileLocation = `(${line},${column})`;\n } else if (line !== undefined) {\n formattedFileLocation = `(${line})`;\n } else {\n formattedFileLocation = '';\n }\n\n break;\n }\n\n default: {\n throw new Error(`Unknown format: ${format}`);\n }\n }\n\n return `${filePath}${formattedFileLocation} - ${message}`;\n }\n\n /**\n * Replaces Windows-style backslashes with POSIX-style slashes.\n *\n * @remarks\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n public static convertToSlashes(inputPath: string): string {\n return inputPath.replace(/\\\\/g, '/');\n }\n\n /**\n * Replaces POSIX-style slashes with Windows-style backslashes\n *\n * @remarks\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n public static convertToBackslashes(inputPath: string): string {\n return inputPath.replace(/\\//g, '\\\\');\n }\n /**\n * Replaces slashes or backslashes with the appropriate slash for the current operating system.\n */\n public static convertToPlatformDefault(inputPath: string): string {\n return path.sep === '/' ? Path.convertToSlashes(inputPath) : Path.convertToBackslashes(inputPath);\n }\n\n /**\n * Returns true if the specified path is a relative path and does not use `..` to walk upwards.\n *\n * @example\n * ```ts\n * // These evaluate to true\n * isDownwardRelative('folder');\n * isDownwardRelative('file');\n * isDownwardRelative('folder/');\n * isDownwardRelative('./folder/');\n * isDownwardRelative('./folder/file');\n *\n * // These evaluate to false\n * isDownwardRelative('../folder');\n * isDownwardRelative('folder/../file');\n * isDownwardRelative('/folder/file');\n * ```\n */\n public static isDownwardRelative(inputPath: string): boolean {\n if (path.isAbsolute(inputPath)) {\n return false;\n }\n // Does it contain \"..\"\n if (Path._upwardPathSegmentRegex.test(inputPath)) {\n return false;\n }\n return true;\n }\n}\n"]} | ||
| {"version":3,"file":"Path.js","sourceRoot":"","sources":["../src/Path.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,gDAAkC;AAkElC;;;;;GAKG;AACH,MAAa,IAAI;IASf;;;;;;;;;OASG;IACI,MAAM,CAAC,OAAO,CAAC,SAAiB,EAAE,gBAAwB;QAC/D,6EAA6E;QA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. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as path from 'node:path';\n\n/**\n * The format that the FileError message should conform to. The supported formats are:\n * - Unix: `<path>:<line>:<column> - <message>`\n * - VisualStudio: `<path>(<line>,<column>) - <message>`\n *\n * @public\n */\nexport type FileLocationStyle = 'Unix' | 'VisualStudio';\n\n/**\n * Options for {@link Path.formatFileLocation}.\n * @public\n */\nexport interface IPathFormatFileLocationOptions {\n /**\n * The base path to use when converting `pathToFormat` to a relative path. If not specified,\n * `pathToFormat` will be used as-is.\n */\n baseFolder?: string;\n /**\n * The path that will be used to specify the file location.\n */\n pathToFormat: string;\n /**\n * The message related to the file location.\n */\n message: string;\n /**\n * The style of file location formatting to use.\n */\n format: FileLocationStyle;\n /**\n * The optional line number. If not specified, the line number will not be included\n * in the formatted string.\n */\n line?: number;\n /**\n * The optional column number. If not specified, the column number will not be included\n * in the formatted string.\n */\n column?: number;\n}\n\n/**\n * Options for {@link Path.formatConcisely}.\n * @public\n */\nexport interface IPathFormatConciselyOptions {\n /**\n * The path to be converted.\n */\n pathToConvert: string;\n\n /**\n * The base path to use when converting `pathToConvert` to a relative path.\n */\n baseFolder: string;\n\n /**\n * If set to true, don't include the leading `./` if the path is under the base folder.\n */\n trimLeadingDotSlash?: boolean;\n}\n\n/**\n * Common operations for manipulating file and directory paths.\n * @remarks\n * This API is intended to eventually be a complete replacement for the NodeJS \"path\" API.\n * @public\n */\nexport class Path {\n // Matches a relative path consisting entirely of periods and slashes\n // Example: \".\", \"..\", \"../..\", etc\n private static _relativePathRegex: RegExp = /^[.\\/\\\\]+$/;\n\n // Matches a relative path segment that traverses upwards\n // Example: \"a/../b\"\n private static _upwardPathSegmentRegex: RegExp = /([\\/\\\\]|^)\\.\\.([\\/\\\\]|$)/;\n\n /**\n * Returns true if \"childPath\" is located inside the \"parentFolderPath\" folder\n * or one of its child folders. Note that \"parentFolderPath\" is not considered to be\n * under itself. The \"childPath\" can refer to any type of file system object.\n *\n * @remarks\n * The indicated file/folder objects are not required to actually exist on disk.\n * For example, \"parentFolderPath\" is interpreted as a folder name even if it refers to a file.\n * If the paths are relative, they will first be resolved using path.resolve().\n */\n public static isUnder(childPath: string, parentFolderPath: string): boolean {\n // If childPath is under parentPath, then relativePath will be something like\n // \"../..\" or \"..\\\\..\", which consists entirely of periods and slashes.\n // (Note that something like \"....t\" is actually a valid filename, but \"....\" is not.)\n const relativePath: string = path.relative(childPath, parentFolderPath);\n return Path._relativePathRegex.test(relativePath);\n }\n\n /**\n * Returns true if \"childPath\" is equal to \"parentFolderPath\", or if it is inside that folder\n * or one of its children. The \"childPath\" can refer to any type of file system object.\n *\n * @remarks\n * The indicated file/folder objects are not required to actually exist on disk.\n * For example, \"parentFolderPath\" is interpreted as a folder name even if it refers to a file.\n * If the paths are relative, they will first be resolved using path.resolve().\n */\n public static isUnderOrEqual(childPath: string, parentFolderPath: string): boolean {\n const relativePath: string = path.relative(childPath, parentFolderPath);\n return relativePath === '' || Path._relativePathRegex.test(relativePath);\n }\n\n /**\n * Returns true if `path1` and `path2` refer to the same underlying path.\n *\n * @remarks\n *\n * The comparison is performed using `path.relative()`.\n */\n public static isEqual(path1: string, path2: string): boolean {\n return path.relative(path1, path2) === '';\n }\n\n /**\n * Formats a path to look nice for reporting purposes.\n * @remarks\n * If `pathToConvert` is under the `baseFolder`, then it will be converted to a relative with the `./` prefix\n * unless the {@link IPathFormatConciselyOptions.trimLeadingDotSlash} option is set to `true`.\n * Otherwise, it will be converted to an absolute path.\n *\n * Backslashes will be converted to slashes, unless the path starts with an OS-specific string like `C:\\`.\n */\n public static formatConcisely(options: IPathFormatConciselyOptions): string {\n // Same logic as Path.isUnderOrEqual()\n const relativePath: string = path.relative(options.pathToConvert, options.baseFolder);\n const isUnderOrEqual: boolean = relativePath === '' || Path._relativePathRegex.test(relativePath);\n\n if (isUnderOrEqual) {\n // Note that isUnderOrEqual()'s relativePath is the reverse direction\n const convertedPath: string = Path.convertToSlashes(\n path.relative(options.baseFolder, options.pathToConvert)\n );\n if (options.trimLeadingDotSlash) {\n return convertedPath;\n } else {\n return `./${convertedPath}`;\n }\n }\n\n const absolutePath: string = path.resolve(options.pathToConvert);\n return absolutePath;\n }\n\n /**\n * Formats a file location to look nice for reporting purposes.\n * @remarks\n * If `pathToFormat` is under the `baseFolder`, then it will be converted to a relative with the `./` prefix.\n * Otherwise, it will be converted to an absolute path.\n *\n * Backslashes will be converted to slashes, unless the path starts with an OS-specific string like `C:\\`.\n */\n public static formatFileLocation(options: IPathFormatFileLocationOptions): string {\n const { message, format, pathToFormat, baseFolder, line, column } = options;\n\n // Convert the path to be relative to the base folder, if specified. Otherwise, use\n // the path as-is.\n const filePath: string = baseFolder\n ? Path.formatConcisely({\n pathToConvert: pathToFormat,\n baseFolder,\n trimLeadingDotSlash: true\n })\n : path.resolve(pathToFormat);\n\n let formattedFileLocation: string;\n switch (format) {\n case 'Unix': {\n if (line !== undefined && column !== undefined) {\n formattedFileLocation = `:${line}:${column}`;\n } else if (line !== undefined) {\n formattedFileLocation = `:${line}`;\n } else {\n formattedFileLocation = '';\n }\n\n break;\n }\n\n case 'VisualStudio': {\n if (line !== undefined && column !== undefined) {\n formattedFileLocation = `(${line},${column})`;\n } else if (line !== undefined) {\n formattedFileLocation = `(${line})`;\n } else {\n formattedFileLocation = '';\n }\n\n break;\n }\n\n default: {\n throw new Error(`Unknown format: ${format}`);\n }\n }\n\n return `${filePath}${formattedFileLocation} - ${message}`;\n }\n\n /**\n * Replaces Windows-style backslashes with POSIX-style slashes.\n *\n * @remarks\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n public static convertToSlashes(inputPath: string): string {\n return inputPath.replace(/\\\\/g, '/');\n }\n\n /**\n * Replaces POSIX-style slashes with Windows-style backslashes\n *\n * @remarks\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n public static convertToBackslashes(inputPath: string): string {\n return inputPath.replace(/\\//g, '\\\\');\n }\n /**\n * Replaces slashes or backslashes with the appropriate slash for the current operating system.\n */\n public static convertToPlatformDefault(inputPath: string): string {\n return path.sep === '/' ? Path.convertToSlashes(inputPath) : Path.convertToBackslashes(inputPath);\n }\n\n /**\n * Returns true if the specified path is a relative path and does not use `..` to walk upwards.\n *\n * @example\n * ```ts\n * // These evaluate to true\n * isDownwardRelative('folder');\n * isDownwardRelative('file');\n * isDownwardRelative('folder/');\n * isDownwardRelative('./folder/');\n * isDownwardRelative('./folder/file');\n *\n * // These evaluate to false\n * isDownwardRelative('../folder');\n * isDownwardRelative('folder/../file');\n * isDownwardRelative('/folder/file');\n * ```\n */\n public static isDownwardRelative(inputPath: string): boolean {\n if (path.isAbsolute(inputPath)) {\n return false;\n }\n // Does it contain \"..\"\n if (Path._upwardPathSegmentRegex.test(inputPath)) {\n return false;\n }\n return true;\n }\n}\n"]} |
@@ -1,3 +0,3 @@ | ||
| import * as nodeFs from 'fs'; | ||
| import * as nodePath from 'path'; | ||
| import * as nodeFs from 'node:fs'; | ||
| import * as nodePath from 'node:path'; | ||
| /** | ||
@@ -4,0 +4,0 @@ * Arguments used to create a function that resolves symlinked node_modules in a path |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"RealNodeModulePath.d.ts","sourceRoot":"","sources":["../src/RealNodeModulePath.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,MAAM,MAAM,IAAI,CAAC;AAC7B,OAAO,KAAK,QAAQ,MAAM,MAAM,CAAC;AAEjC;;;GAGG;AACH,MAAM,WAAW,kCAAkC;IACjD,EAAE,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,OAAO,MAAM,EAAE,WAAW,GAAG,cAAc,CAAC,CAAC,CAAC;IAChE,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,OAAO,QAAQ,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC;IACjF;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;A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AG,CAAkE;IACtF,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoE;IAC1F,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAiD;gBAE5D,OAAO,GAAE,kCAAuC;IA0GnE;;;OAGG;IACI,UAAU,IAAI,IAAI;IAIzB;;;;;OAKG;IACH,OAAO,CAAC,YAAY;CA4BrB"} |
@@ -39,4 +39,4 @@ "use strict"; | ||
| exports.RealNodeModulePathResolver = void 0; | ||
| const nodeFs = __importStar(require("fs")); | ||
| const nodePath = __importStar(require("path")); | ||
| const nodeFs = __importStar(require("node:fs")); | ||
| const nodePath = __importStar(require("node:path")); | ||
| /** | ||
@@ -43,0 +43,0 @@ * This class encapsulates a caching resolver for symlinks in node_modules directories. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"RealNodeModulePath.js","sourceRoot":"","sources":["../src/RealNodeModulePath.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,2CAA6B;AAC7B,+CAAiC;AAgBjC;;;;;;;;;;;;;GAaG;AACH,MAAa,0BAA0B;IAgBrC,YAAmB,UAA8C,EAAE;QACjE,MAAM,EACJ,EAAE,EAAE,EAAE,SAAS,GAAG,MAAM,CAAC,SAAS,EAAE,YAAY,GAAG,MAAM,CAAC,YAAY,EAAE,GAAG,MAAM,EACjF,IAAI,EAAE,EACJ,UAAU,GAAG,QAAQ,CAAC,UAAU,EAChC,IAAI,GAAG,QAAQ,CAAC,IAAI,EACpB,OAAO,GAAG,QAAQ,CAAC,OAAO,EAC1B,GAAG,GAAG,QAAQ,CAAC,GAAG,EACnB,GAAG,QAAQ,EACZ,kBAAkB,GAAG,KAAK,EAC3B,GAAG,OAAO,CAAC;QACZ,MAAM,KAAK,GAAwB,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC;QAC7D,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE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G,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC;gBACjF,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,qDAAqD;YACrD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,GAAY,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;CACF;AApKD,gEAoKC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as nodeFs from 'fs';\nimport * as nodePath from 'path';\n\n/**\n * Arguments used to create a function that resolves symlinked node_modules in a path\n * @public\n */\nexport interface IRealNodeModulePathResolverOptions {\n fs?: Partial<Pick<typeof nodeFs, 'lstatSync' | 'readlinkSync'>>;\n path?: Partial<Pick<typeof nodePath, 'isAbsolute' | 'join' | 'resolve' | 'sep'>>;\n /**\n * If set to true, the resolver will not throw if part of the path does not exist.\n * @defaultValue false\n */\n ignoreMissingPaths?: boolean;\n}\n\n/**\n * This class encapsulates a caching resolver for symlinks in node_modules directories.\n * It assumes that the only symlinks that exist in input paths are those that correspond to\n * npm packages.\n *\n * @remarks\n * In a repository with a symlinked node_modules installation, some symbolic links need to be mapped for\n * node module resolution to produce correct results. However, calling `fs.realpathSync.native` on every path,\n * as is commonly done by most resolvers, involves an enormous number of file system operations (for reference,\n * each invocation of `fs.realpathSync.native` involves a series of `fs.readlinkSync` calls, up to one for each\n * path segment in the input).\n *\n * @public\n */\nexport class RealNodeModulePathResolver {\n /**\n * Similar in function to `fs.realpathSync.native`, but assumes the only symlinks present are npm packages.\n *\n * @param input - A path to a file or directory, where the path separator is `${require('node:path').sep}`\n * @returns The real path to the input, resolving the node_modules symlinks in the path\n * @public\n */\n public readonly realNodeModulePath: (input: string) => string;\n\n private readonly _cache: Map<string, string | false>;\n private readonly _errorCache: Map<string, Error>;\n private readonly _fs: Required<NonNullable<IRealNodeModulePathResolverOptions['fs']>>;\n private readonly _path: Required<NonNullable<IRealNodeModulePathResolverOptions['path']>>;\n private readonly _lstatOptions: Pick<nodeFs.StatSyncOptions, 'throwIfNoEntry'>;\n\n public constructor(options: IRealNodeModulePathResolverOptions = {}) {\n const {\n fs: { lstatSync = nodeFs.lstatSync, readlinkSync = nodeFs.readlinkSync } = nodeFs,\n path: {\n isAbsolute = nodePath.isAbsolute,\n join = nodePath.join,\n resolve = nodePath.resolve,\n sep = nodePath.sep\n } = nodePath,\n ignoreMissingPaths = false\n } = options;\n const cache: Map<string, string> = (this._cache = new Map());\n this._errorCache = new Map();\n this._fs = {\n lstatSync,\n readlinkSync\n };\n this._path = {\n isAbsolute,\n join,\n resolve,\n sep\n };\n this._lstatOptions = {\n throwIfNoEntry: !ignoreMissingPaths\n };\n\n const nodeModulesToken: string = `${sep}node_modules${sep}`;\n const self: this = this;\n\n function realNodeModulePathInternal(input: string): string {\n // Find the last node_modules path segment\n const nodeModulesIndex: number = input.lastIndexOf(nodeModulesToken);\n if (nodeModulesIndex < 0) {\n // No node_modules in path, so we assume it is already the real path\n return input;\n }\n\n // First assume that the next path segment after node_modules is a symlink\n let linkStart: number = nodeModulesIndex + nodeModulesToken.length - 1;\n let linkEnd: number = input.indexOf(sep, linkStart + 1);\n // If the path segment starts with a '@', then it is a scoped package\n const isScoped: boolean = input.charAt(linkStart + 1) === '@';\n if (isScoped) {\n // For a scoped package, the scope is an ordinary directory, so we need to find the next path segment\n if (linkEnd < 0) {\n // Symlink missing, so see if anything before the last node_modules needs resolving,\n // and preserve the rest of the path\n return join(\n realNodeModulePathInternal(input.slice(0, nodeModulesIndex)),\n input.slice(nodeModulesIndex + 1),\n // Joining to `.` will clean up any extraneous trailing slashes\n '.'\n );\n }\n\n linkStart = linkEnd;\n linkEnd = input.indexOf(sep, linkStart + 1);\n }\n\n // No trailing separator, so the link is the last path segment\n if (linkEnd < 0) {\n linkEnd = input.length;\n }\n\n const linkCandidate: string = input.slice(0, linkEnd);\n // Check if the link is a symlink\n const linkTarget: string | undefined = self._tryReadLink(linkCandidate);\n if (linkTarget && isAbsolute(linkTarget)) {\n // Absolute path, combine the link target with any remaining path segments\n // Cache the resolution to avoid the readlink call in subsequent calls\n cache.set(linkCandidate, linkTarget);\n cache.set(linkTarget, linkTarget);\n // Joining to `.` will clean up any extraneous trailing slashes\n return join(linkTarget, input.slice(linkEnd + 1), '.');\n }\n\n // Relative path or does not exist\n // Either way, the path before the last node_modules could itself be in a node_modules folder\n // So resolve the base path to find out what paths are relative to\n const realpathBeforeNodeModules: string = realNodeModulePathInternal(input.slice(0, nodeModulesIndex));\n if (linkTarget) {\n // Relative path in symbolic link. Should be resolved relative to real path of base path.\n const resolvedTarget: string = resolve(\n realpathBeforeNodeModules,\n input.slice(nodeModulesIndex + 1, linkStart),\n linkTarget\n );\n // Cache the result of the combined resolution to avoid the readlink call in subsequent calls\n cache.set(linkCandidate, resolvedTarget);\n cache.set(resolvedTarget, resolvedTarget);\n // Joining to `.` will clean up any extraneous trailing slashes\n return join(resolvedTarget, input.slice(linkEnd + 1), '.');\n }\n\n // No symlink, so just return the real path before the last node_modules combined with the\n // subsequent path segments\n // Joining to `.` will clean up any extraneous trailing slashes\n return join(realpathBeforeNodeModules, input.slice(nodeModulesIndex + 1), '.');\n }\n\n this.realNodeModulePath = (input: string) => {\n return realNodeModulePathInternal(resolve(input));\n };\n }\n\n /**\n * Clears the cache of resolved symlinks.\n * @public\n */\n public clearCache(): void {\n this._cache.clear();\n }\n\n /**\n * Tries to read a symbolic link at the specified path.\n * If the input is not a symbolic link, returns undefined.\n * @param link - The link to try to read\n * @returns The target of the symbolic link, or undefined if the input is not a symbolic link\n */\n private _tryReadLink(link: string): string | undefined {\n const cached: string | false | undefined = this._cache.get(link);\n if (cached !== undefined) {\n return cached || undefined;\n }\n\n const cachedError: Error | undefined = this._errorCache.get(link);\n if (cachedError) {\n // Fill the properties but fix the stack trace.\n throw Object.assign(new Error(cachedError.message), cachedError);\n }\n\n // On Windows, calling `readlink` on a directory throws an EUNKOWN, not EINVAL, so just pay the cost\n // of an lstat call.\n try {\n const stat: nodeFs.Stats | undefined = this._fs.lstatSync(link, this._lstatOptions);\n if (stat?.isSymbolicLink()) {\n // path.join(x, '.') will trim trailing slashes, if applicable\n const result: string = this._path.join(this._fs.readlinkSync(link, 'utf8'), '.');\n return result;\n }\n\n // Ensure we cache that this was not a symbolic link.\n this._cache.set(link, false);\n } catch (err) {\n this._errorCache.set(link, err as Error);\n }\n }\n}\n"]} | ||
| {"version":3,"file":"RealNodeModulePath.js","sourceRoot":"","sources":["../src/RealNodeModulePath.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,gDAAkC;AAClC,oDAAsC;AAgBtC;;;;;;;;;;;;;GAaG;AACH,MAAa,0BAA0B;IAgBrC,YAAmB,UAA8C,EAAE;QACjE,MAAM,EACJ,EAAE,EAAE,EAAE,SAAS,GAAG,MAAM,CAAC,SAAS,EAAE,YAAY,GAAG,MAAM,CAAC,YAAY,EAAE,GAAG,MAAM,EACjF,IAAI,EAAE,EACJ,UAAU,GAAG,QAAQ,CAAC,UAAU,EAChC,IAAI,GAAG,QAAQ,CAAC,IAAI,EACpB,OAAO,GAAG,QAAQ,CAAC,OAAO,EAC1B,GAAG,GAAG,QAAQ,CAAC,GAAG,EACnB,GAAG,QAAQ,EACZ,kBAAkB,GAAG,KAAK,EAC3B,GAAG,OAAO,CAAC;QACZ,MAAM,KAAK,GAAwB,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC;QAC7D,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG;YACT,SAAS;YACT,YAAY;SACb,CAAC;QACF,IAAI,CAAC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,CAAC;YAChB,CAAC;YAED,qDAAqD;YACrD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,GAAY,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;CACF;AApKD,gEAoKC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as nodeFs from 'node:fs';\nimport * as nodePath from 'node:path';\n\n/**\n * Arguments used to create a function that resolves symlinked node_modules in a path\n * @public\n */\nexport interface IRealNodeModulePathResolverOptions {\n fs?: Partial<Pick<typeof nodeFs, 'lstatSync' | 'readlinkSync'>>;\n path?: Partial<Pick<typeof nodePath, 'isAbsolute' | 'join' | 'resolve' | 'sep'>>;\n /**\n * If set to true, the resolver will not throw if part of the path does not exist.\n * @defaultValue false\n */\n ignoreMissingPaths?: boolean;\n}\n\n/**\n * This class encapsulates a caching resolver for symlinks in node_modules directories.\n * It assumes that the only symlinks that exist in input paths are those that correspond to\n * npm packages.\n *\n * @remarks\n * In a repository with a symlinked node_modules installation, some symbolic links need to be mapped for\n * node module resolution to produce correct results. However, calling `fs.realpathSync.native` on every path,\n * as is commonly done by most resolvers, involves an enormous number of file system operations (for reference,\n * each invocation of `fs.realpathSync.native` involves a series of `fs.readlinkSync` calls, up to one for each\n * path segment in the input).\n *\n * @public\n */\nexport class RealNodeModulePathResolver {\n /**\n * Similar in function to `fs.realpathSync.native`, but assumes the only symlinks present are npm packages.\n *\n * @param input - A path to a file or directory, where the path separator is `${require('node:path').sep}`\n * @returns The real path to the input, resolving the node_modules symlinks in the path\n * @public\n */\n public readonly realNodeModulePath: (input: string) => string;\n\n private readonly _cache: Map<string, string | false>;\n private readonly _errorCache: Map<string, Error>;\n private readonly _fs: Required<NonNullable<IRealNodeModulePathResolverOptions['fs']>>;\n private readonly _path: Required<NonNullable<IRealNodeModulePathResolverOptions['path']>>;\n private readonly _lstatOptions: Pick<nodeFs.StatSyncOptions, 'throwIfNoEntry'>;\n\n public constructor(options: IRealNodeModulePathResolverOptions = {}) {\n const {\n fs: { lstatSync = nodeFs.lstatSync, readlinkSync = nodeFs.readlinkSync } = nodeFs,\n path: {\n isAbsolute = nodePath.isAbsolute,\n join = nodePath.join,\n resolve = nodePath.resolve,\n sep = nodePath.sep\n } = nodePath,\n ignoreMissingPaths = false\n } = options;\n const cache: Map<string, string> = (this._cache = new Map());\n this._errorCache = new Map();\n this._fs = {\n lstatSync,\n readlinkSync\n };\n this._path = {\n isAbsolute,\n join,\n resolve,\n sep\n };\n this._lstatOptions = {\n throwIfNoEntry: !ignoreMissingPaths\n };\n\n const nodeModulesToken: string = `${sep}node_modules${sep}`;\n const self: this = this;\n\n function realNodeModulePathInternal(input: string): string {\n // Find the last node_modules path segment\n const nodeModulesIndex: number = input.lastIndexOf(nodeModulesToken);\n if (nodeModulesIndex < 0) {\n // No node_modules in path, so we assume it is already the real path\n return input;\n }\n\n // First assume that the next path segment after node_modules is a symlink\n let linkStart: number = nodeModulesIndex + nodeModulesToken.length - 1;\n let linkEnd: number = input.indexOf(sep, linkStart + 1);\n // If the path segment starts with a '@', then it is a scoped package\n const isScoped: boolean = input.charAt(linkStart + 1) === '@';\n if (isScoped) {\n // For a scoped package, the scope is an ordinary directory, so we need to find the next path segment\n if (linkEnd < 0) {\n // Symlink missing, so see if anything before the last node_modules needs resolving,\n // and preserve the rest of the path\n return join(\n realNodeModulePathInternal(input.slice(0, nodeModulesIndex)),\n input.slice(nodeModulesIndex + 1),\n // Joining to `.` will clean up any extraneous trailing slashes\n '.'\n );\n }\n\n linkStart = linkEnd;\n linkEnd = input.indexOf(sep, linkStart + 1);\n }\n\n // No trailing separator, so the link is the last path segment\n if (linkEnd < 0) {\n linkEnd = input.length;\n }\n\n const linkCandidate: string = input.slice(0, linkEnd);\n // Check if the link is a symlink\n const linkTarget: string | undefined = self._tryReadLink(linkCandidate);\n if (linkTarget && isAbsolute(linkTarget)) {\n // Absolute path, combine the link target with any remaining path segments\n // Cache the resolution to avoid the readlink call in subsequent calls\n cache.set(linkCandidate, linkTarget);\n cache.set(linkTarget, linkTarget);\n // Joining to `.` will clean up any extraneous trailing slashes\n return join(linkTarget, input.slice(linkEnd + 1), '.');\n }\n\n // Relative path or does not exist\n // Either way, the path before the last node_modules could itself be in a node_modules folder\n // So resolve the base path to find out what paths are relative to\n const realpathBeforeNodeModules: string = realNodeModulePathInternal(input.slice(0, nodeModulesIndex));\n if (linkTarget) {\n // Relative path in symbolic link. Should be resolved relative to real path of base path.\n const resolvedTarget: string = resolve(\n realpathBeforeNodeModules,\n input.slice(nodeModulesIndex + 1, linkStart),\n linkTarget\n );\n // Cache the result of the combined resolution to avoid the readlink call in subsequent calls\n cache.set(linkCandidate, resolvedTarget);\n cache.set(resolvedTarget, resolvedTarget);\n // Joining to `.` will clean up any extraneous trailing slashes\n return join(resolvedTarget, input.slice(linkEnd + 1), '.');\n }\n\n // No symlink, so just return the real path before the last node_modules combined with the\n // subsequent path segments\n // Joining to `.` will clean up any extraneous trailing slashes\n return join(realpathBeforeNodeModules, input.slice(nodeModulesIndex + 1), '.');\n }\n\n this.realNodeModulePath = (input: string) => {\n return realNodeModulePathInternal(resolve(input));\n };\n }\n\n /**\n * Clears the cache of resolved symlinks.\n * @public\n */\n public clearCache(): void {\n this._cache.clear();\n }\n\n /**\n * Tries to read a symbolic link at the specified path.\n * If the input is not a symbolic link, returns undefined.\n * @param link - The link to try to read\n * @returns The target of the symbolic link, or undefined if the input is not a symbolic link\n */\n private _tryReadLink(link: string): string | undefined {\n const cached: string | false | undefined = this._cache.get(link);\n if (cached !== undefined) {\n return cached || undefined;\n }\n\n const cachedError: Error | undefined = this._errorCache.get(link);\n if (cachedError) {\n // Fill the properties but fix the stack trace.\n throw Object.assign(new Error(cachedError.message), cachedError);\n }\n\n // On Windows, calling `readlink` on a directory throws an EUNKOWN, not EINVAL, so just pay the cost\n // of an lstat call.\n try {\n const stat: nodeFs.Stats | undefined = this._fs.lstatSync(link, this._lstatOptions);\n if (stat?.isSymbolicLink()) {\n // path.join(x, '.') will trim trailing slashes, if applicable\n const result: string = this._path.join(this._fs.readlinkSync(link, 'utf8'), '.');\n return result;\n }\n\n // Ensure we cache that this was not a symbolic link.\n this._cache.set(link, false);\n } catch (err) {\n this._errorCache.set(link, err as Error);\n }\n }\n}\n"]} |
@@ -1,2 +0,2 @@ | ||
| import type * as child_process from 'child_process'; | ||
| import type * as child_process from 'node:child_process'; | ||
| /** | ||
@@ -3,0 +3,0 @@ * Details about how the `child_process.ChildProcess` was created. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"SubprocessTerminator.d.ts","sourceRoot":"","sources":["../src/SubprocessTerminator.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,aAAa,MAAM,eAAe,CAAC;AAKpD;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;;OASG;IACH,QAAQ,EAAE,OAAO,CAAC;CACnB;AAOD;;;;;;;;;;;;GAYG;AACH,qBAAa,oBAAoB;IAC/B;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,YAAY,CAAkB;IAE7C;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB,CAA8C;IAE/E,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAyC;IAE3E;;OAEG;IACH,gBAAuB,mBAAmB,EAAE,kBAAkB,CAE5D;IAEF;;;OAGG;WACW,qBAAqB,CACjC,UAAU,EAAE,aAAa,CAAC,YAAY,EACtC,iBAAiB,EAAE,kBAAkB,GACpC,IAAI;IA8BP;;OAEG;WACW,eAAe,CAC3B,UAAU,EAAE,aAAa,CAAC,YAAY,EACtC,iBAAiB,EAAE,kBAAkB,GACpC,IAAI;IAmDP,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAcjC,OAAO,CAAC,MAAM,CAAC,sBAAsB;IAuCrC,OAAO,CAAC,MAAM,CAAC,0BAA0B;IASzC,OAAO,CAAC,MAAM,CAAC,OAAO;IAQtB,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAajC,OAAO,CAAC,MAAM,CAAC,SAAS;CAKzB"} | ||
| {"version":3,"file":"SubprocessTerminator.d.ts","sourceRoot":"","sources":["../src/SubprocessTerminator.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,aAAa,MAAM,oBAAoB,CAAC;AAKzD;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;;OASG;IACH,QAAQ,EAAE,OAAO,CAAC;CACnB;AAOD;;;;;;;;;;;;GAYG;AACH,qBAAa,oBAAoB;IAC/B;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,YAAY,CAAkB;IAE7C;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB,CAA8C;IAE/E,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAyC;IAE3E;;OAEG;IACH,gBAAuB,mBAAmB,EAAE,kBAAkB,CAE5D;IAEF;;;OAGG;WACW,qBAAqB,CACjC,UAAU,EAAE,aAAa,CAAC,YAAY,EACtC,iBAAiB,EAAE,kBAAkB,GACpC,IAAI;IA8BP;;OAEG;WACW,eAAe,CAC3B,UAAU,EAAE,aAAa,CAAC,YAAY,EACtC,iBAAiB,EAAE,kBAAkB,GACpC,IAAI;IAmDP,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAcjC,OAAO,CAAC,MAAM,CAAC,sBAAsB;IAuCrC,OAAO,CAAC,MAAM,CAAC,0BAA0B;IASzC,OAAO,CAAC,MAAM,CAAC,OAAO;IAQtB,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAajC,OAAO,CAAC,MAAM,CAAC,SAAS;CAKzB"} |
@@ -9,3 +9,3 @@ "use strict"; | ||
| exports.SubprocessTerminator = void 0; | ||
| const process_1 = __importDefault(require("process")); | ||
| const node_process_1 = __importDefault(require("node:process")); | ||
| const Executable_1 = require("./Executable"); | ||
@@ -99,3 +99,3 @@ /** | ||
| // Passing a negative PID terminates the entire group instead of just the one process | ||
| process_1.default.kill(-pid, 'SIGKILL'); | ||
| node_process_1.default.kill(-pid, 'SIGKILL'); | ||
| } | ||
@@ -108,5 +108,5 @@ } | ||
| SubprocessTerminator._logDebug('initialize'); | ||
| process_1.default.prependListener('SIGTERM', SubprocessTerminator._onTerminateSignal); | ||
| process_1.default.prependListener('SIGINT', SubprocessTerminator._onTerminateSignal); | ||
| process_1.default.prependListener('exit', SubprocessTerminator._onExit); | ||
| node_process_1.default.prependListener('SIGTERM', SubprocessTerminator._onTerminateSignal); | ||
| node_process_1.default.prependListener('SIGINT', SubprocessTerminator._onTerminateSignal); | ||
| node_process_1.default.prependListener('exit', SubprocessTerminator._onExit); | ||
| } | ||
@@ -118,4 +118,4 @@ } | ||
| SubprocessTerminator._initialized = false; | ||
| process_1.default.removeListener('SIGTERM', SubprocessTerminator._onTerminateSignal); | ||
| process_1.default.removeListener('SIGINT', SubprocessTerminator._onTerminateSignal); | ||
| node_process_1.default.removeListener('SIGTERM', SubprocessTerminator._onTerminateSignal); | ||
| node_process_1.default.removeListener('SIGINT', SubprocessTerminator._onTerminateSignal); | ||
| const trackedSubprocesses = Array.from(SubprocessTerminator._subprocessesByPid.values()); | ||
@@ -142,4 +142,4 @@ let firstError = undefined; | ||
| console.error(firstError.toString()); | ||
| if (!process_1.default.exitCode) { | ||
| process_1.default.exitCode = 1; | ||
| if (!node_process_1.default.exitCode) { | ||
| node_process_1.default.exitCode = 1; | ||
| } | ||
@@ -169,3 +169,3 @@ } | ||
| SubprocessTerminator._logDebug(`relaying ${signal}`); | ||
| process_1.default.kill(process_1.default.pid, signal); | ||
| node_process_1.default.kill(node_process_1.default.pid, signal); | ||
| } | ||
@@ -189,3 +189,3 @@ // For debugging | ||
| SubprocessTerminator._subprocessesByPid = new Map(); | ||
| SubprocessTerminator._isWindows = process_1.default.platform === 'win32'; | ||
| SubprocessTerminator._isWindows = node_process_1.default.platform === 'win32'; | ||
| /** | ||
@@ -195,4 +195,4 @@ * The recommended options when creating a child process. | ||
| SubprocessTerminator.RECOMMENDED_OPTIONS = { | ||
| detached: process_1.default.platform !== 'win32' | ||
| detached: node_process_1.default.platform !== 'win32' | ||
| }; | ||
| //# sourceMappingURL=SubprocessTerminator.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"SubprocessTerminator.js","sourceRoot":"","sources":["../src/SubprocessTerminator.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;AAG3D,sDAA8B;AAE9B,6CAA0C;AA0B1C;;;;;;;;;;;;GAYG;AACH,MAAa,oBAAoB;IAqB/B;;;OAGG;IACI,MAAM,CAAC,qBAAqB,CACjC,UAAsC,EACtC,iBAAqC;QAErC,IAAI,OAAO,UAAU,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC5C,kCAAkC;YAClC,OAAO;QACT,CAAC;QAED,oBAAoB,CAAC,0BAA0B,CAAC,iBAAiB,CAAC,CAAC;QAEnE,oBAAoB,CAAC,kBAAkB,EAAE,CAAC;QAE1C,mBAAmB;QACnB,MAAM,GAAG,GAAuB,UAAU,CAAC,GAAG,CAAC;QAC/C,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACtB,+BAA+B;YAC/B,OAAO;QACT,CAAC;QAED,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,QAAuB,EAAE,MAA6B,EAAQ,EAAE;YACtF,IAAI,oBAAoB,CAAC,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;gBACxD,oBAAoB,CAAC,SAAS,CAAC,eAAe,GAAG,EAAE,CAAC,CAAC;YACvD,CAAC;QACH,CAAC,CAAC,CAAC;QACH,oBAAoB,CAAC,kBAAkB,CAAC,GAAG,CAAC,GAAG,EAAE;YAC/C,UAAU;YACV,iBAAiB;SAClB,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AAsB,EAAE,CAAC;QAE9C,sFAAsF;QACtF,0FAA0F;QAC1F,iCAAiC;QACjC,oBAAoB,CAAC,SAAS,CAAC,YAAY,MAAM,EAAE,CAAC,CAAC;QACrD,iBAAO,CAAC,IAAI,CAAC,iBAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACpC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,SAAS,CAAC,OAAe;QACtC,8EAA8E;QAC9E,gEAAgE;QAChE,uBAAuB;IACzB,CAAC;;AA1MH,oDA2MC;AA1MC;;GAEG;AACY,iCAAY,GAAY,KAAK,CAAC;AAE7C;;;GAGG;AACY,uCAAkB,GAAoC,IAAI,GAAG,EAAE,CAAC;AAEvD,+BAAU,GAAY,iBAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AAE3E;;GAEG;AACoB,wCAAmB,GAAuB;IAC/D,QAAQ,EAAE,iBAAO,CAAC,QAAQ,KAAK,OAAO;CACvC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type * as child_process from 'child_process';\nimport process from 'process';\n\nimport { Executable } from './Executable';\n\n/**\n * Details about how the `child_process.ChildProcess` was created.\n *\n * @beta\n */\nexport interface ISubprocessOptions {\n /**\n * Whether or not the child process was started in detached mode.\n *\n * @remarks\n * On POSIX systems, detached=true is required for killing the subtree. Attempting to kill the\n * subtree on POSIX systems with detached=false will throw an error. On Windows, detached=true\n * creates a separate console window and is not required for killing the subtree. In general,\n * it is recommended to use SubprocessTerminator.RECOMMENDED_OPTIONS when forking or spawning\n * a child process.\n */\n detached: boolean;\n}\n\ninterface ITrackedSubprocess {\n subprocess: child_process.ChildProcess;\n subprocessOptions: ISubprocessOptions;\n}\n\n/**\n * When a child process is created, registering it with the SubprocessTerminator will ensure\n * that the child gets terminated when the current process terminates.\n *\n * @remarks\n * This works by hooking the current process's events for SIGTERM/SIGINT/exit, and ensuring the\n * child process gets terminated in those cases.\n *\n * SubprocessTerminator doesn't do anything on Windows, since by default Windows automatically\n * terminates child processes when their parent is terminated.\n *\n * @beta\n */\nexport class SubprocessTerminator {\n /**\n * Whether the hooks are installed\n */\n private static _initialized: boolean = false;\n\n /**\n * The list of registered child processes. Processes are removed from this set if they\n * terminate on their own.\n */\n private static _subprocessesByPid: Map<number, ITrackedSubprocess> = new Map();\n\n private static readonly _isWindows: boolean = process.platform === 'win32';\n\n /**\n * The recommended options when creating a child process.\n */\n public static readonly RECOMMENDED_OPTIONS: ISubprocessOptions = {\n detached: process.platform !== 'win32'\n };\n\n /**\n * Registers a child process so that it will be terminated automatically if the current process\n * is terminated.\n */\n public static killProcessTreeOnExit(\n subprocess: child_process.ChildProcess,\n subprocessOptions: ISubprocessOptions\n ): void {\n if (typeof subprocess.exitCode === 'number') {\n // Process has already been killed\n return;\n }\n\n SubprocessTerminator._validateSubprocessOptions(subprocessOptions);\n\n SubprocessTerminator._ensureInitialized();\n\n // Closure variable\n const pid: number | undefined = subprocess.pid;\n if (pid === undefined) {\n // The process failed to spawn.\n return;\n }\n\n subprocess.on('close', (exitCode: number | null, signal: NodeJS.Signals | null): void => {\n if (SubprocessTerminator._subprocessesByPid.delete(pid)) {\n SubprocessTerminator._logDebug(`untracking #${pid}`);\n }\n });\n SubprocessTerminator._subprocessesByPid.set(pid, {\n subprocess,\n subprocessOptions\n });\n\n SubprocessTerminator._logDebug(`tracking #${pid}`);\n }\n\n /**\n * Terminate the child process and all of its children.\n */\n public static killProcessTree(\n subprocess: child_process.ChildProcess,\n subprocessOptions: ISubprocessOptions\n ): void {\n const pid: number | undefined = subprocess.pid;\n if (pid === undefined) {\n // The process failed to spawn.\n return;\n }\n\n // Don't attempt to kill the same process twice\n if (SubprocessTerminator._subprocessesByPid.delete(pid)) {\n SubprocessTerminator._logDebug(`untracking #${pid} via killProcessTree()`);\n }\n\n SubprocessTerminator._validateSubprocessOptions(subprocessOptions);\n\n if (typeof subprocess.exitCode === 'number') {\n // Process has already been killed\n return;\n }\n\n SubprocessTerminator._logDebug(`terminating #${pid}`);\n\n if (SubprocessTerminator._isWindows) {\n // On Windows we have a problem that CMD.exe launches child processes, but when CMD.exe is killed\n // the child processes may continue running. Also if we send signals to CMD.exe the child processes\n // will not receive them. The safest solution is not to attempt a graceful shutdown, but simply\n // kill the entire process tree.\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync('TaskKill.exe', [\n '/T', // \"Terminates the specified process and any child processes which were started by it.\"\n '/F', // Without this, TaskKill will try to use WM_CLOSE which doesn't work with CLI tools\n '/PID',\n pid.toString()\n ]);\n\n if (result.status) {\n const output: string = result.output.join('\\n');\n // Nonzero exit code\n if (output.indexOf('not found') >= 0) {\n // The PID does not exist\n } else {\n // Another error occurred, for example TaskKill.exe does not support\n // the expected CLI syntax\n throw new Error(`TaskKill.exe returned exit code ${result.status}:\\n` + output + '\\n');\n }\n }\n } else {\n // Passing a negative PID terminates the entire group instead of just the one process\n process.kill(-pid, 'SIGKILL');\n }\n }\n\n // Install the hooks\n private static _ensureInitialized(): void {\n if (!SubprocessTerminator._initialized) {\n SubprocessTerminator._initialized = true;\n\n SubprocessTerminator._logDebug('initialize');\n\n process.prependListener('SIGTERM', SubprocessTerminator._onTerminateSignal);\n process.prependListener('SIGINT', SubprocessTerminator._onTerminateSignal);\n\n process.prependListener('exit', SubprocessTerminator._onExit);\n }\n }\n\n // Uninstall the hooks and perform cleanup\n private static _cleanupChildProcesses(): void {\n if (SubprocessTerminator._initialized) {\n SubprocessTerminator._initialized = false;\n\n process.removeListener('SIGTERM', SubprocessTerminator._onTerminateSignal);\n process.removeListener('SIGINT', SubprocessTerminator._onTerminateSignal);\n\n const trackedSubprocesses: ITrackedSubprocess[] = Array.from(\n SubprocessTerminator._subprocessesByPid.values()\n );\n\n let firstError: Error | undefined = undefined;\n\n for (const trackedSubprocess of trackedSubprocesses) {\n try {\n SubprocessTerminator.killProcessTree(trackedSubprocess.subprocess, { detached: true });\n } catch (error) {\n if (firstError === undefined) {\n firstError = error as Error;\n }\n }\n }\n\n if (firstError !== undefined) {\n // This is generally an unexpected error such as the TaskKill.exe command not being found,\n // not a trivial issue such as a nonexistent PID. Since this occurs during process shutdown,\n // we should not interfere with control flow by throwing an exception or calling process.exit().\n // So simply write to STDERR and ensure our exit code indicates the problem.\n // eslint-disable-next-line no-console\n console.error('\\nAn unexpected error was encountered while attempting to clean up child processes:');\n // eslint-disable-next-line no-console\n console.error(firstError.toString());\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n }\n }\n }\n\n private static _validateSubprocessOptions(subprocessOptions: ISubprocessOptions): void {\n if (!SubprocessTerminator._isWindows) {\n if (!subprocessOptions.detached) {\n // Setting detached=true is what creates the process group that we use to kill the children\n throw new Error('killProcessTree() requires detached=true on this operating system');\n }\n }\n }\n\n private static _onExit(exitCode: number): void {\n SubprocessTerminator._logDebug(`received exit(${exitCode})`);\n\n SubprocessTerminator._cleanupChildProcesses();\n\n SubprocessTerminator._logDebug(`finished exit()`);\n }\n\n private static _onTerminateSignal(signal: string): void {\n SubprocessTerminator._logDebug(`received signal ${signal}`);\n\n SubprocessTerminator._cleanupChildProcesses();\n\n // When a listener is added to SIGTERM, Node.js strangely provides no way to reference\n // the original handler. But we can invoke it by removing our listener and then resending\n // the signal to our own process.\n SubprocessTerminator._logDebug(`relaying ${signal}`);\n process.kill(process.pid, signal);\n }\n\n // For debugging\n private static _logDebug(message: string): void {\n //const logLine: string = `SubprocessTerminator: [${process.pid}] ${message}`;\n // fs.writeFileSync('trace.log', logLine + '\\n', { flag: 'a' });\n //console.log(logLine);\n }\n}\n"]} | ||
| {"version":3,"file":"SubprocessTerminator.js","sourceRoot":"","sources":["../src/SubprocessTerminator.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;AAG3D,gEAAmC;AAEnC,6CAA0C;AA0B1C;;;;;;;;;;;;GAYG;AACH,MAAa,oBAAoB;IAqB/B;;;OAGG;IACI,MAAM,CAAC,qBAAqB,CACj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,wCAAmB,GAAuB;IAC/D,QAAQ,EAAE,sBAAO,CAAC,QAAQ,KAAK,OAAO;CACvC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type * as child_process from 'node:child_process';\nimport process from 'node:process';\n\nimport { Executable } from './Executable';\n\n/**\n * Details about how the `child_process.ChildProcess` was created.\n *\n * @beta\n */\nexport interface ISubprocessOptions {\n /**\n * Whether or not the child process was started in detached mode.\n *\n * @remarks\n * On POSIX systems, detached=true is required for killing the subtree. Attempting to kill the\n * subtree on POSIX systems with detached=false will throw an error. On Windows, detached=true\n * creates a separate console window and is not required for killing the subtree. In general,\n * it is recommended to use SubprocessTerminator.RECOMMENDED_OPTIONS when forking or spawning\n * a child process.\n */\n detached: boolean;\n}\n\ninterface ITrackedSubprocess {\n subprocess: child_process.ChildProcess;\n subprocessOptions: ISubprocessOptions;\n}\n\n/**\n * When a child process is created, registering it with the SubprocessTerminator will ensure\n * that the child gets terminated when the current process terminates.\n *\n * @remarks\n * This works by hooking the current process's events for SIGTERM/SIGINT/exit, and ensuring the\n * child process gets terminated in those cases.\n *\n * SubprocessTerminator doesn't do anything on Windows, since by default Windows automatically\n * terminates child processes when their parent is terminated.\n *\n * @beta\n */\nexport class SubprocessTerminator {\n /**\n * Whether the hooks are installed\n */\n private static _initialized: boolean = false;\n\n /**\n * The list of registered child processes. Processes are removed from this set if they\n * terminate on their own.\n */\n private static _subprocessesByPid: Map<number, ITrackedSubprocess> = new Map();\n\n private static readonly _isWindows: boolean = process.platform === 'win32';\n\n /**\n * The recommended options when creating a child process.\n */\n public static readonly RECOMMENDED_OPTIONS: ISubprocessOptions = {\n detached: process.platform !== 'win32'\n };\n\n /**\n * Registers a child process so that it will be terminated automatically if the current process\n * is terminated.\n */\n public static killProcessTreeOnExit(\n subprocess: child_process.ChildProcess,\n subprocessOptions: ISubprocessOptions\n ): void {\n if (typeof subprocess.exitCode === 'number') {\n // Process has already been killed\n return;\n }\n\n SubprocessTerminator._validateSubprocessOptions(subprocessOptions);\n\n SubprocessTerminator._ensureInitialized();\n\n // Closure variable\n const pid: number | undefined = subprocess.pid;\n if (pid === undefined) {\n // The process failed to spawn.\n return;\n }\n\n subprocess.on('close', (exitCode: number | null, signal: NodeJS.Signals | null): void => {\n if (SubprocessTerminator._subprocessesByPid.delete(pid)) {\n SubprocessTerminator._logDebug(`untracking #${pid}`);\n }\n });\n SubprocessTerminator._subprocessesByPid.set(pid, {\n subprocess,\n subprocessOptions\n });\n\n SubprocessTerminator._logDebug(`tracking #${pid}`);\n }\n\n /**\n * Terminate the child process and all of its children.\n */\n public static killProcessTree(\n subprocess: child_process.ChildProcess,\n subprocessOptions: ISubprocessOptions\n ): void {\n const pid: number | undefined = subprocess.pid;\n if (pid === undefined) {\n // The process failed to spawn.\n return;\n }\n\n // Don't attempt to kill the same process twice\n if (SubprocessTerminator._subprocessesByPid.delete(pid)) {\n SubprocessTerminator._logDebug(`untracking #${pid} via killProcessTree()`);\n }\n\n SubprocessTerminator._validateSubprocessOptions(subprocessOptions);\n\n if (typeof subprocess.exitCode === 'number') {\n // Process has already been killed\n return;\n }\n\n SubprocessTerminator._logDebug(`terminating #${pid}`);\n\n if (SubprocessTerminator._isWindows) {\n // On Windows we have a problem that CMD.exe launches child processes, but when CMD.exe is killed\n // the child processes may continue running. Also if we send signals to CMD.exe the child processes\n // will not receive them. The safest solution is not to attempt a graceful shutdown, but simply\n // kill the entire process tree.\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync('TaskKill.exe', [\n '/T', // \"Terminates the specified process and any child processes which were started by it.\"\n '/F', // Without this, TaskKill will try to use WM_CLOSE which doesn't work with CLI tools\n '/PID',\n pid.toString()\n ]);\n\n if (result.status) {\n const output: string = result.output.join('\\n');\n // Nonzero exit code\n if (output.indexOf('not found') >= 0) {\n // The PID does not exist\n } else {\n // Another error occurred, for example TaskKill.exe does not support\n // the expected CLI syntax\n throw new Error(`TaskKill.exe returned exit code ${result.status}:\\n` + output + '\\n');\n }\n }\n } else {\n // Passing a negative PID terminates the entire group instead of just the one process\n process.kill(-pid, 'SIGKILL');\n }\n }\n\n // Install the hooks\n private static _ensureInitialized(): void {\n if (!SubprocessTerminator._initialized) {\n SubprocessTerminator._initialized = true;\n\n SubprocessTerminator._logDebug('initialize');\n\n process.prependListener('SIGTERM', SubprocessTerminator._onTerminateSignal);\n process.prependListener('SIGINT', SubprocessTerminator._onTerminateSignal);\n\n process.prependListener('exit', SubprocessTerminator._onExit);\n }\n }\n\n // Uninstall the hooks and perform cleanup\n private static _cleanupChildProcesses(): void {\n if (SubprocessTerminator._initialized) {\n SubprocessTerminator._initialized = false;\n\n process.removeListener('SIGTERM', SubprocessTerminator._onTerminateSignal);\n process.removeListener('SIGINT', SubprocessTerminator._onTerminateSignal);\n\n const trackedSubprocesses: ITrackedSubprocess[] = Array.from(\n SubprocessTerminator._subprocessesByPid.values()\n );\n\n let firstError: Error | undefined = undefined;\n\n for (const trackedSubprocess of trackedSubprocesses) {\n try {\n SubprocessTerminator.killProcessTree(trackedSubprocess.subprocess, { detached: true });\n } catch (error) {\n if (firstError === undefined) {\n firstError = error as Error;\n }\n }\n }\n\n if (firstError !== undefined) {\n // This is generally an unexpected error such as the TaskKill.exe command not being found,\n // not a trivial issue such as a nonexistent PID. Since this occurs during process shutdown,\n // we should not interfere with control flow by throwing an exception or calling process.exit().\n // So simply write to STDERR and ensure our exit code indicates the problem.\n // eslint-disable-next-line no-console\n console.error('\\nAn unexpected error was encountered while attempting to clean up child processes:');\n // eslint-disable-next-line no-console\n console.error(firstError.toString());\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n }\n }\n }\n\n private static _validateSubprocessOptions(subprocessOptions: ISubprocessOptions): void {\n if (!SubprocessTerminator._isWindows) {\n if (!subprocessOptions.detached) {\n // Setting detached=true is what creates the process group that we use to kill the children\n throw new Error('killProcessTree() requires detached=true on this operating system');\n }\n }\n }\n\n private static _onExit(exitCode: number): void {\n SubprocessTerminator._logDebug(`received exit(${exitCode})`);\n\n SubprocessTerminator._cleanupChildProcesses();\n\n SubprocessTerminator._logDebug(`finished exit()`);\n }\n\n private static _onTerminateSignal(signal: string): void {\n SubprocessTerminator._logDebug(`received signal ${signal}`);\n\n SubprocessTerminator._cleanupChildProcesses();\n\n // When a listener is added to SIGTERM, Node.js strangely provides no way to reference\n // the original handler. But we can invoke it by removing our listener and then resending\n // the signal to our own process.\n SubprocessTerminator._logDebug(`relaying ${signal}`);\n process.kill(process.pid, signal);\n }\n\n // For debugging\n private static _logDebug(message: string): void {\n //const logLine: string = `SubprocessTerminator: [${process.pid}] ${message}`;\n // fs.writeFileSync('trace.log', logLine + '\\n', { flag: 'a' });\n //console.log(logLine);\n }\n}\n"]} |
+1
-1
@@ -39,3 +39,3 @@ "use strict"; | ||
| exports.Text = exports.NewlineKind = exports.Encoding = void 0; | ||
| const os = __importStar(require("os")); | ||
| const os = __importStar(require("node:os")); | ||
| /** | ||
@@ -42,0 +42,0 @@ * The allowed types of encodings, as supported by Node.js |
+1
-1
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Text.js","sourceRoot":"","sources":["../src/Text.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,uCAAyB;AAEzB;;;GAGG;AACH,IAAY,QAEX;AAFD,WAAY,QAAQ;IAClB,yBAAa,CAAA;AACf,CAAC,EAFW,QAAQ,wBAAR,QAAQ,QAEnB;AAED;;;GAGG;AACH,IAAY,WAkBX;AAlBD,WAAY,WAAW;IACrB;;OAEG;IACH,4BAAa,CAAA;IAEb;;;;;OAKG;IACH,wBAAS,CAAA;IAET;;OAEG;IACH,+BAAgB,CAAA;AAClB,CAAC,EAlBW,WAAW,2BAAX,WAAW,QAkBtB;AAwBD,MAAM,aAAa,GAAW,kBAAkB,CAAC;AACjD,MAAM,oBAAoB,GAAW,oBAAoB,CAAC;AAE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ACI,MAAM,CAAC,OAAO,CAAC,CAAS;QAC7B,kEAAkE;QAClE,OAAO,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,SAAS,EAAE,EAAE,CAAC,CAAC;IACvE,CAAC;IASM,MAAM,CAAC,eAAe,CAAC,CAAqB;QACjD,OAAO,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;;AArMH,oBAsMC;AArMyB,kBAAa,GAAW,aAAa,CAAC;AACtC,uBAAkB,GAAW,oBAAoB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'os';\n\n/**\n * The allowed types of encodings, as supported by Node.js\n * @public\n */\nexport enum Encoding {\n Utf8 = 'utf8'\n}\n\n/**\n * Enumeration controlling conversion of newline characters.\n * @public\n */\nexport enum NewlineKind {\n /**\n * Windows-style newlines\n */\n CrLf = '\\r\\n',\n\n /**\n * POSIX-style newlines\n *\n * @remarks\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n Lf = '\\n',\n\n /**\n * Default newline type for this operating system (`os.EOL`).\n */\n OsDefault = 'os'\n}\n\n/**\n * Options used when calling the {@link Text.readLinesFromIterable} or\n * {@link Text.readLinesFromIterableAsync} methods.\n *\n * @public\n */\nexport interface IReadLinesFromIterableOptions {\n /**\n * The encoding of the input iterable. The default is utf8.\n */\n encoding?: Encoding;\n\n /**\n * If true, empty lines will not be returned. The default is false.\n */\n ignoreEmptyLines?: boolean;\n}\n\ninterface IReadLinesFromIterableState {\n remaining: string;\n}\n\nconst NEWLINE_REGEX: RegExp = /\\r\\n|\\n\\r|\\r|\\n/g;\nconst NEWLINE_AT_END_REGEX: RegExp = /(\\r\\n|\\n\\r|\\r|\\n)$/;\n\nfunction* readLinesFromChunk(\n // eslint-disable-next-line @rushstack/no-new-null\n chunk: string | Buffer | null,\n encoding: Encoding,\n ignoreEmptyLines: boolean,\n state: IReadLinesFromIterableState\n): Generator<string> {\n if (!chunk) {\n return;\n }\n const remaining: string = state.remaining + (typeof chunk === 'string' ? chunk : chunk.toString(encoding));\n let startIndex: number = 0;\n const matches: IterableIterator<RegExpMatchArray> = remaining.matchAll(NEWLINE_REGEX);\n for (const match of matches) {\n const endIndex: number = match.index!;\n if (startIndex !== endIndex || !ignoreEmptyLines) {\n yield remaining.substring(startIndex, endIndex);\n }\n startIndex = endIndex + match[0].length;\n }\n state.remaining = remaining.substring(startIndex);\n}\n\n/**\n * Operations for working with strings that contain text.\n *\n * @remarks\n * The utilities provided by this class are intended to be simple, small, and very\n * broadly applicable.\n *\n * @public\n */\nexport class Text {\n private static readonly _newLineRegEx: RegExp = NEWLINE_REGEX;\n private static readonly _newLineAtEndRegEx: RegExp = NEWLINE_AT_END_REGEX;\n\n /**\n * Returns the same thing as targetString.replace(searchValue, replaceValue), except that\n * all matches are replaced, rather than just the first match.\n * @param input - The string to be modified\n * @param searchValue - The value to search for\n * @param replaceValue - The replacement text\n */\n public static replaceAll(input: string, searchValue: string, replaceValue: string): string {\n return input.split(searchValue).join(replaceValue);\n }\n\n /**\n * Converts all newlines in the provided string to use Windows-style CRLF end of line characters.\n */\n public static convertToCrLf(input: string): string {\n return input.replace(Text._newLineRegEx, '\\r\\n');\n }\n\n /**\n * Converts all newlines in the provided string to use POSIX-style LF end of line characters.\n *\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n public static convertToLf(input: string): string {\n return input.replace(Text._newLineRegEx, '\\n');\n }\n\n /**\n * Converts all newlines in the provided string to use the specified newline type.\n */\n public static convertTo(input: string, newlineKind: NewlineKind): string {\n return input.replace(Text._newLineRegEx, Text.getNewline(newlineKind));\n }\n\n /**\n * Returns the newline character sequence for the specified `NewlineKind`.\n */\n public static getNewline(newlineKind: NewlineKind): string {\n switch (newlineKind) {\n case NewlineKind.CrLf:\n return '\\r\\n';\n case NewlineKind.Lf:\n return '\\n';\n case NewlineKind.OsDefault:\n return os.EOL;\n default:\n throw new Error('Unsupported newline kind');\n }\n }\n\n /**\n * Append characters to the end of a string to ensure the result has a minimum length.\n * @remarks\n * If the string length already exceeds the minimum length, then the string is unchanged.\n * The string is not truncated.\n */\n public static padEnd(s: string, minimumLength: number, paddingCharacter: string = ' '): string {\n if (paddingCharacter.length !== 1) {\n throw new Error('The paddingCharacter parameter must be a single character.');\n }\n\n if (s.length < minimumLength) {\n const paddingArray: string[] = new Array(minimumLength - s.length);\n paddingArray.unshift(s);\n return paddingArray.join(paddingCharacter);\n } else {\n return s;\n }\n }\n\n /**\n * Append characters to the start of a string to ensure the result has a minimum length.\n * @remarks\n * If the string length already exceeds the minimum length, then the string is unchanged.\n * The string is not truncated.\n */\n public static padStart(s: string, minimumLength: number, paddingCharacter: string = ' '): string {\n if (paddingCharacter.length !== 1) {\n throw new Error('The paddingCharacter parameter must be a single character.');\n }\n\n if (s.length < minimumLength) {\n const paddingArray: string[] = new Array(minimumLength - s.length);\n paddingArray.push(s);\n return paddingArray.join(paddingCharacter);\n } else {\n return s;\n }\n }\n\n /**\n * If the string is longer than maximumLength characters, truncate it to that length\n * using \"...\" to indicate the truncation.\n *\n * @remarks\n * For example truncateWithEllipsis('1234578', 5) would produce '12...'.\n */\n public static truncateWithEllipsis(s: string, maximumLength: number): string {\n if (maximumLength < 0) {\n throw new Error('The maximumLength cannot be a negative number');\n }\n\n if (s.length <= maximumLength) {\n return s;\n }\n\n if (s.length <= 3) {\n return s.substring(0, maximumLength);\n }\n\n return s.substring(0, maximumLength - 3) + '...';\n }\n\n /**\n * Returns the input string with a trailing `\\n` character appended, if not already present.\n */\n public static ensureTrailingNewline(s: string, newlineKind: NewlineKind = NewlineKind.Lf): string {\n // Is there already a newline?\n if (Text._newLineAtEndRegEx.test(s)) {\n return s; // yes, no change\n }\n return s + newlineKind; // no, add it\n }\n\n /**\n * Escapes a string so that it can be treated as a literal string when used in a regular expression.\n */\n public static escapeRegExp(literal: string): string {\n return literal.replace(/[^A-Za-z0-9_]/g, '\\\\$&');\n }\n\n /**\n * Read lines from an iterable object that returns strings or buffers, and return a generator that\n * produces the lines as strings. The lines will not include the newline characters.\n *\n * @param iterable - An iterable object that returns strings or buffers\n * @param options - Options used when reading the lines from the provided iterable\n */\n public static async *readLinesFromIterableAsync(\n iterable: AsyncIterable<string | Buffer>,\n options: IReadLinesFromIterableOptions = {}\n ): AsyncGenerator<string> {\n const { encoding = Encoding.Utf8, ignoreEmptyLines = false } = options;\n const state: IReadLinesFromIterableState = { remaining: '' };\n for await (const chunk of iterable) {\n yield* readLinesFromChunk(chunk, encoding, ignoreEmptyLines, state);\n }\n const remaining: string = state.remaining;\n if (remaining.length) {\n yield remaining;\n }\n }\n\n /**\n * Read lines from an iterable object that returns strings or buffers, and return a generator that\n * produces the lines as strings. The lines will not include the newline characters.\n *\n * @param iterable - An iterable object that returns strings or buffers\n * @param options - Options used when reading the lines from the provided iterable\n */\n public static *readLinesFromIterable(\n // eslint-disable-next-line @rushstack/no-new-null\n iterable: Iterable<string | Buffer | null>,\n options: IReadLinesFromIterableOptions = {}\n ): Generator<string> {\n const { encoding = Encoding.Utf8, ignoreEmptyLines = false } = options;\n const state: IReadLinesFromIterableState = { remaining: '' };\n for (const chunk of iterable) {\n yield* readLinesFromChunk(chunk, encoding, ignoreEmptyLines, state);\n }\n const remaining: string = state.remaining;\n if (remaining.length) {\n yield remaining;\n }\n }\n\n /**\n * Returns a new string that is the input string with the order of characters reversed.\n */\n public static reverse(s: string): string {\n // Benchmarks of several algorithms: https://jsbench.me/4bkfflcm2z\n return s.split('').reduce((newString, char) => char + newString, '');\n }\n\n /**\n * Splits the provided string by newlines. Note that leading and trailing newlines will produce\n * leading or trailing empty string array entries.\n */\n public static splitByNewLines(s: undefined): undefined;\n public static splitByNewLines(s: string): string[];\n public static splitByNewLines(s: string | undefined): string[] | undefined;\n public static splitByNewLines(s: string | undefined): string[] | undefined {\n return s?.split(/\\r?\\n/);\n }\n}\n"]} | ||
| {"version":3,"file":"Text.js","sourceRoot":"","sources":["../src/Text.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,4CAA8B;AAE9B;;;GAGG;AACH,IAAY,QAEX;AAFD,WAAY,QAAQ;IAClB,yBAAa,CAAA;AACf,CAAC,EAFW,QAAQ,wBAAR,QAAQ,QAEnB;AAED;;;GAGG;AACH,IAAY,WAkBX;AAlBD,WAAY,WAAW;IACrB;;OAEG;IACH,4BAAa,CAAA;IAEb;;;;;OAKG;IACH,wBAAS,CAAA;IAET;;OAEG;IACH,+BAAgB,CAAA;AAClB,CAAC,EAlBW,WAAW,2BAAX,WAAW,QAkBtB;AAwBD,MAAM,aAAa,GAAW,kBAAkB,CAAC;AACjD,MAAM,oBAAoB,GAAW,oBAAoB,CAAC;AAE1D,QAAQ,CAAC,CAAC,kBAAkB;AAC1B,kDAAkD;AAClD,KAA6B,EAC7B,QAAkB,EAClB,gBAAyB,EACzB,KAAkC;IAElC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO;IACT,CAAC;IACD,MAAM,SAAS,GAAW,KAAK,CAAC,SAAS,GAAG,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC3G,IAAI,UAAU,GAAW,CAAC,CAAC;IAC3B,MAAM,OAAO,GAAuC,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;IACtF,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAW,KAAK,CAAC,KAAM,CAAC;QACtC,IAAI,UAAU,KAAK,QAAQ,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACjD,MA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CAAC;YACrB,MAAM,SAAS,CAAC;QAClB,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,CAAC,qBAAqB;IAClC,kDAAkD;IAClD,QAA0C,EAC1C,UAAyC,EAAE;QAE3C,MAAM,EAAE,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;QACvE,MAAM,KAAK,GAAgC,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;QAC7D,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;YAC7B,KAAK,CAAC,CAAC,kBAAkB,CAAC,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,KAAK,CAAC,CAAC;QACtE,CAAC;QACD,MAAM,SAAS,GAAW,KAAK,CAAC,SAAS,CAAC;QAC1C,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;YACrB,MAAM,SAAS,CAAC;QAClB,CAAC;IACH,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,OAAO,CAAC,CAAS;QAC7B,kEAAkE;QAClE,OAAO,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,SAAS,EAAE,EAAE,CAAC,CAAC;IACvE,CAAC;IASM,MAAM,CAAC,eAAe,CAAC,CAAqB;QACjD,OAAO,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;;AArMH,oBAsMC;AArMyB,kBAAa,GAAW,aAAa,CAAC;AACtC,uBAAkB,GAAW,oBAAoB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport * as os from 'node:os';\n\n/**\n * The allowed types of encodings, as supported by Node.js\n * @public\n */\nexport enum Encoding {\n Utf8 = 'utf8'\n}\n\n/**\n * Enumeration controlling conversion of newline characters.\n * @public\n */\nexport enum NewlineKind {\n /**\n * Windows-style newlines\n */\n CrLf = '\\r\\n',\n\n /**\n * POSIX-style newlines\n *\n * @remarks\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n Lf = '\\n',\n\n /**\n * Default newline type for this operating system (`os.EOL`).\n */\n OsDefault = 'os'\n}\n\n/**\n * Options used when calling the {@link Text.readLinesFromIterable} or\n * {@link Text.readLinesFromIterableAsync} methods.\n *\n * @public\n */\nexport interface IReadLinesFromIterableOptions {\n /**\n * The encoding of the input iterable. The default is utf8.\n */\n encoding?: Encoding;\n\n /**\n * If true, empty lines will not be returned. The default is false.\n */\n ignoreEmptyLines?: boolean;\n}\n\ninterface IReadLinesFromIterableState {\n remaining: string;\n}\n\nconst NEWLINE_REGEX: RegExp = /\\r\\n|\\n\\r|\\r|\\n/g;\nconst NEWLINE_AT_END_REGEX: RegExp = /(\\r\\n|\\n\\r|\\r|\\n)$/;\n\nfunction* readLinesFromChunk(\n // eslint-disable-next-line @rushstack/no-new-null\n chunk: string | Buffer | null,\n encoding: Encoding,\n ignoreEmptyLines: boolean,\n state: IReadLinesFromIterableState\n): Generator<string> {\n if (!chunk) {\n return;\n }\n const remaining: string = state.remaining + (typeof chunk === 'string' ? chunk : chunk.toString(encoding));\n let startIndex: number = 0;\n const matches: IterableIterator<RegExpMatchArray> = remaining.matchAll(NEWLINE_REGEX);\n for (const match of matches) {\n const endIndex: number = match.index!;\n if (startIndex !== endIndex || !ignoreEmptyLines) {\n yield remaining.substring(startIndex, endIndex);\n }\n startIndex = endIndex + match[0].length;\n }\n state.remaining = remaining.substring(startIndex);\n}\n\n/**\n * Operations for working with strings that contain text.\n *\n * @remarks\n * The utilities provided by this class are intended to be simple, small, and very\n * broadly applicable.\n *\n * @public\n */\nexport class Text {\n private static readonly _newLineRegEx: RegExp = NEWLINE_REGEX;\n private static readonly _newLineAtEndRegEx: RegExp = NEWLINE_AT_END_REGEX;\n\n /**\n * Returns the same thing as targetString.replace(searchValue, replaceValue), except that\n * all matches are replaced, rather than just the first match.\n * @param input - The string to be modified\n * @param searchValue - The value to search for\n * @param replaceValue - The replacement text\n */\n public static replaceAll(input: string, searchValue: string, replaceValue: string): string {\n return input.split(searchValue).join(replaceValue);\n }\n\n /**\n * Converts all newlines in the provided string to use Windows-style CRLF end of line characters.\n */\n public static convertToCrLf(input: string): string {\n return input.replace(Text._newLineRegEx, '\\r\\n');\n }\n\n /**\n * Converts all newlines in the provided string to use POSIX-style LF end of line characters.\n *\n * POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.\n */\n public static convertToLf(input: string): string {\n return input.replace(Text._newLineRegEx, '\\n');\n }\n\n /**\n * Converts all newlines in the provided string to use the specified newline type.\n */\n public static convertTo(input: string, newlineKind: NewlineKind): string {\n return input.replace(Text._newLineRegEx, Text.getNewline(newlineKind));\n }\n\n /**\n * Returns the newline character sequence for the specified `NewlineKind`.\n */\n public static getNewline(newlineKind: NewlineKind): string {\n switch (newlineKind) {\n case NewlineKind.CrLf:\n return '\\r\\n';\n case NewlineKind.Lf:\n return '\\n';\n case NewlineKind.OsDefault:\n return os.EOL;\n default:\n throw new Error('Unsupported newline kind');\n }\n }\n\n /**\n * Append characters to the end of a string to ensure the result has a minimum length.\n * @remarks\n * If the string length already exceeds the minimum length, then the string is unchanged.\n * The string is not truncated.\n */\n public static padEnd(s: string, minimumLength: number, paddingCharacter: string = ' '): string {\n if (paddingCharacter.length !== 1) {\n throw new Error('The paddingCharacter parameter must be a single character.');\n }\n\n if (s.length < minimumLength) {\n const paddingArray: string[] = new Array(minimumLength - s.length);\n paddingArray.unshift(s);\n return paddingArray.join(paddingCharacter);\n } else {\n return s;\n }\n }\n\n /**\n * Append characters to the start of a string to ensure the result has a minimum length.\n * @remarks\n * If the string length already exceeds the minimum length, then the string is unchanged.\n * The string is not truncated.\n */\n public static padStart(s: string, minimumLength: number, paddingCharacter: string = ' '): string {\n if (paddingCharacter.length !== 1) {\n throw new Error('The paddingCharacter parameter must be a single character.');\n }\n\n if (s.length < minimumLength) {\n const paddingArray: string[] = new Array(minimumLength - s.length);\n paddingArray.push(s);\n return paddingArray.join(paddingCharacter);\n } else {\n return s;\n }\n }\n\n /**\n * If the string is longer than maximumLength characters, truncate it to that length\n * using \"...\" to indicate the truncation.\n *\n * @remarks\n * For example truncateWithEllipsis('1234578', 5) would produce '12...'.\n */\n public static truncateWithEllipsis(s: string, maximumLength: number): string {\n if (maximumLength < 0) {\n throw new Error('The maximumLength cannot be a negative number');\n }\n\n if (s.length <= maximumLength) {\n return s;\n }\n\n if (s.length <= 3) {\n return s.substring(0, maximumLength);\n }\n\n return s.substring(0, maximumLength - 3) + '...';\n }\n\n /**\n * Returns the input string with a trailing `\\n` character appended, if not already present.\n */\n public static ensureTrailingNewline(s: string, newlineKind: NewlineKind = NewlineKind.Lf): string {\n // Is there already a newline?\n if (Text._newLineAtEndRegEx.test(s)) {\n return s; // yes, no change\n }\n return s + newlineKind; // no, add it\n }\n\n /**\n * Escapes a string so that it can be treated as a literal string when used in a regular expression.\n */\n public static escapeRegExp(literal: string): string {\n return literal.replace(/[^A-Za-z0-9_]/g, '\\\\$&');\n }\n\n /**\n * Read lines from an iterable object that returns strings or buffers, and return a generator that\n * produces the lines as strings. The lines will not include the newline characters.\n *\n * @param iterable - An iterable object that returns strings or buffers\n * @param options - Options used when reading the lines from the provided iterable\n */\n public static async *readLinesFromIterableAsync(\n iterable: AsyncIterable<string | Buffer>,\n options: IReadLinesFromIterableOptions = {}\n ): AsyncGenerator<string> {\n const { encoding = Encoding.Utf8, ignoreEmptyLines = false } = options;\n const state: IReadLinesFromIterableState = { remaining: '' };\n for await (const chunk of iterable) {\n yield* readLinesFromChunk(chunk, encoding, ignoreEmptyLines, state);\n }\n const remaining: string = state.remaining;\n if (remaining.length) {\n yield remaining;\n }\n }\n\n /**\n * Read lines from an iterable object that returns strings or buffers, and return a generator that\n * produces the lines as strings. The lines will not include the newline characters.\n *\n * @param iterable - An iterable object that returns strings or buffers\n * @param options - Options used when reading the lines from the provided iterable\n */\n public static *readLinesFromIterable(\n // eslint-disable-next-line @rushstack/no-new-null\n iterable: Iterable<string | Buffer | null>,\n options: IReadLinesFromIterableOptions = {}\n ): Generator<string> {\n const { encoding = Encoding.Utf8, ignoreEmptyLines = false } = options;\n const state: IReadLinesFromIterableState = { remaining: '' };\n for (const chunk of iterable) {\n yield* readLinesFromChunk(chunk, encoding, ignoreEmptyLines, state);\n }\n const remaining: string = state.remaining;\n if (remaining.length) {\n yield remaining;\n }\n }\n\n /**\n * Returns a new string that is the input string with the order of characters reversed.\n */\n public static reverse(s: string): string {\n // Benchmarks of several algorithms: https://jsbench.me/4bkfflcm2z\n return s.split('').reduce((newString, char) => char + newString, '');\n }\n\n /**\n * Splits the provided string by newlines. Note that leading and trailing newlines will produce\n * leading or trailing empty string array entries.\n */\n public static splitByNewLines(s: undefined): undefined;\n public static splitByNewLines(s: string): string[];\n public static splitByNewLines(s: string | undefined): string[] | undefined;\n public static splitByNewLines(s: string | undefined): string[] | undefined {\n return s?.split(/\\r?\\n/);\n }\n}\n"]} |
+2
-2
| { | ||
| "name": "@rushstack/node-core-library", | ||
| "version": "5.15.1", | ||
| "version": "5.16.0", | ||
| "description": "Core libraries that every NodeJS toolchain project should use", | ||
@@ -24,3 +24,3 @@ "main": "lib/index.js", | ||
| "devDependencies": { | ||
| "@rushstack/heft": "0.74.3", | ||
| "@rushstack/heft": "1.0.0", | ||
| "@types/fs-extra": "7.0.0", | ||
@@ -27,0 +27,0 @@ "@types/jju": "1.4.1", |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 3 instances in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
1245818
0.06%17754
0.07%109
-5.22%0
-100%