@ms-cloudpack/cli 0.72.61 → 0.72.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commands/init/InitSummaryData.js +7 -2
- package/lib/commands/init/InitSummaryData.js.map +1 -1
- package/lib/commands/init/init.d.ts +1 -1
- package/lib/commands/init/init.d.ts.map +1 -1
- package/lib/commands/init/init.js.map +1 -1
- package/lib/commands/init/verifyExports.d.ts +3 -5
- package/lib/commands/init/verifyExports.d.ts.map +1 -1
- package/lib/commands/init/verifyExports.js.map +1 -1
- package/lib/utilities/AutoDisposableList.js +1 -3
- package/lib/utilities/AutoDisposableList.js.map +1 -1
- package/lib/utilities/CloudpackCommand.js +3 -0
- package/lib/utilities/CloudpackCommand.js.map +1 -1
- package/lib/utilities/CommandExecutor.js +27 -17
- package/lib/utilities/CommandExecutor.js.map +1 -1
- package/package.json +5 -5
|
@@ -6,9 +6,14 @@ import { requiredChangeTypes } from './types/GeneratedChange.js';
|
|
|
6
6
|
* `formatInitSummary` helper to convert it to a string for the user.
|
|
7
7
|
*/
|
|
8
8
|
export class InitSummaryData {
|
|
9
|
+
/** Set this to indicate that the generated config was deleted. */
|
|
10
|
+
deletedGeneratedConfig = false;
|
|
11
|
+
_packageResults;
|
|
12
|
+
_generatedUpdates;
|
|
13
|
+
_startTime;
|
|
14
|
+
_appPath;
|
|
15
|
+
_check;
|
|
9
16
|
constructor(params) {
|
|
10
|
-
/** Set this to indicate that the generated config was deleted. */
|
|
11
|
-
this.deletedGeneratedConfig = false;
|
|
12
17
|
this._packageResults = {};
|
|
13
18
|
this._generatedUpdates = {};
|
|
14
19
|
this._startTime = Date.now();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InitSummaryData.js","sourceRoot":"","sources":["../../../src/commands/init/InitSummaryData.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE;;;;;GAKG;AACH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,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;QACrF,CAAC;QAED,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,QAAQ;YACtB,QAAQ;YACR,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM;YACvD,YAAY;YACZ,WAAW;YACX,aAAa;YACb,YAAY;YACZ,oBAAoB;YACpB,MAAM,EAAE,WAAW,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,oBAAoB,GAAG,CAAC,CAAC;YACpE,kBAAkB;YAClB,oBAAoB;YACpB,oBAAoB,EAAE,aAAa;YACnC,sBAAsB,EAAE,IAAI,CAAC,sBAAsB;SACpD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { InitSummary } from './types/InitSummary.js';\nimport type { GeneratedPackageChanges } from './types/GeneratedPackageChanges.js';\nimport type {\n InitPackageResult,\n InitPackageResultErrors,\n InitPackageResultWarnings,\n} from './types/InitPackageResult.js';\nimport type { InitOptions } from './types/InitOptions.js';\nimport type { BundleMessage } from '@ms-cloudpack/common-types';\nimport { requiredChangeTypes } from './types/GeneratedChange.js';\nimport type { EnsurePackageBundledResult } from '@ms-cloudpack/api-server';\n\n/**\n * Creates a summary tracking helper for the `init` verb to use to record statistics about results and needed\n * changes. The `record*` methods of the returned object will be used within init to add the stats, and the\n * `summarize` method will return the final tally. The resulting `InitSummary` object can be used in the\n * `formatInitSummary` helper to convert it to a string for the user.\n */\nexport class InitSummaryData {\n /** Set this to indicate that the generated config was deleted. */\n public deletedGeneratedConfig = false;\n\n private _packageResults: Record<string, InitPackageResult>;\n private _generatedUpdates: Record<string, GeneratedPackageChanges>;\n private _startTime: number;\n private _appPath: string;\n private _check: boolean;\n\n constructor(\n params: Pick<InitOptions, 'check'> & {\n appPath: string;\n },\n ) {\n this._packageResults = {};\n this._generatedUpdates = {};\n this._startTime = Date.now();\n this._appPath = params.appPath;\n this._check = !!params.check;\n }\n\n /**\n * Returns whether any generated changes have been recorded.\n */\n public hasChanges(): boolean {\n return Object.values(this._generatedUpdates).length > 0;\n }\n\n /**\n * Saves a package result.\n */\n public recordResult(\n packagePath: string,\n result: Pick<EnsurePackageBundledResult, 'name' | 'version' | 'info' | 'outputPath' | 'errors' | 'warnings'>,\n ): void {\n this._packageResults[packagePath] = {\n path: packagePath,\n name: result.name,\n version: result.version,\n info: result.info,\n outputPath: result.outputPath,\n errors: result.errors,\n warnings: result.warnings,\n };\n }\n\n /**\n * Record an exception for a given package path.\n * This creates a bundle message like \"Error thrown while (context): (error)\".\n * (Unlike `addErrors`, this will create an overall package result if one doesn't exist yet.)\n */\n public recordException(params: {\n packagePath: string;\n error: unknown;\n source: string;\n /** Description of the context in which the error was thrown, e.g. \"evaluating package\" */\n context: string;\n /** Package name in case no result has been recorded for this package yet */\n name?: string;\n /** Package version in case no result has been recorded for this package yet */\n version?: string;\n }): void {\n const { packagePath, error, source, context, name = '<unknown>', version = '<unknown>' } = params;\n if (!this._packageResults[packagePath]) {\n this.recordResult(packagePath, { name, version });\n }\n\n const text = `Error thrown while ${context}: ${(error as Error).stack || error}`;\n this.addErrors(packagePath, [{ text, source }]);\n }\n\n /**\n * Record more errors for a given package path.\n */\n public addErrors(packagePath: string, errors: BundleMessage[]): void {\n const packageResult = this._packageResults[packagePath];\n if (!packageResult) {\n throw new Error(`Package result not found for path ${packagePath}`);\n }\n\n packageResult.errors = [...(packageResult.errors || []), ...errors];\n }\n\n /**\n * Returns the package results.\n * @returns The package results.\n */\n public getResults(): Record<string, InitPackageResult> {\n return this._packageResults;\n }\n\n /**\n * Saves a generated file update.\n * @param allChanges - The generated file update to save.\n */\n public recordGeneratedChanges(allChanges: GeneratedPackageChanges[]): void {\n for (const update of allChanges) {\n const { name, version, path, changes } = update;\n // Only record changes if there are any, so that hasChanges() is accurate.\n if (changes.length) {\n const updatesForPackage = (this._generatedUpdates[path] ??= { name, version, path, changes: [] });\n\n updatesForPackage.changes.push(...changes);\n }\n }\n }\n\n /**\n * Returns the summary of the results.\n */\n public summarize(): InitSummary {\n const duration = Date.now() - this._startTime;\n let totalSuccess = 0;\n let totalErrors = 0;\n let totalWarnings = 0;\n let totalChanges = 0;\n let totalRequiredChanges = 0;\n const packagesWithErrors: InitPackageResultErrors[] = [];\n const packagesWithWarnings: InitPackageResultWarnings[] = [];\n\n for (const packageResult of Object.values(this._packageResults)) {\n if (packageResult.errors?.length) {\n packagesWithErrors.push(packageResult as InitPackageResultErrors);\n totalErrors += packageResult.errors.length;\n } else {\n totalSuccess++;\n }\n\n if (packageResult.warnings?.length) {\n packagesWithWarnings.push(packageResult as InitPackageResultWarnings);\n totalWarnings += packageResult.warnings.length;\n }\n }\n\n const sortedUpdates = Object.values(this._generatedUpdates).sort((a, b) => a.path.localeCompare(b.path));\n\n for (const updates of sortedUpdates) {\n totalChanges += updates.changes.length;\n totalRequiredChanges += updates.changes.filter((u) => requiredChangeTypes[u.type]).length;\n updates.changes = updates.changes.sort((a, b) => a.change.localeCompare(b.change));\n }\n\n return {\n appPath: this._appPath,\n duration,\n totalPackages: Object.keys(this._packageResults).length,\n totalSuccess,\n totalErrors,\n totalWarnings,\n totalChanges,\n totalRequiredChanges,\n failed: totalErrors > 0 || (this._check && totalRequiredChanges > 0),\n packagesWithErrors,\n packagesWithWarnings,\n generatedFileUpdates: sortedUpdates,\n deletedGeneratedConfig: this.deletedGeneratedConfig,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"InitSummaryData.js","sourceRoot":"","sources":["../../../src/commands/init/InitSummaryData.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IAC1B,kEAAkE;IAC3D,sBAAsB,GAAG,KAAK,CAAC;IAE9B,eAAe,CAAoC;IACnD,iBA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CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;QACrF,CAAC;QAED,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,QAAQ;YACtB,QAAQ;YACR,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM;YACvD,YAAY;YACZ,WAAW;YACX,aAAa;YACb,YAAY;YACZ,oBAAoB;YACpB,MAAM,EAAE,WAAW,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,oBAAoB,GAAG,CAAC,CAAC;YACpE,kBAAkB;YAClB,oBAAoB;YACpB,oBAAoB,EAAE,aAAa;YACnC,sBAAsB,EAAE,IAAI,CAAC,sBAAsB;SACpD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { InitSummary } from './types/InitSummary.js';\nimport type { GeneratedPackageChanges } from './types/GeneratedPackageChanges.js';\nimport type {\n InitPackageResult,\n InitPackageResultErrors,\n InitPackageResultWarnings,\n} from './types/InitPackageResult.js';\nimport type { InitOptions } from './types/InitOptions.js';\nimport type { BundleMessage } from '@ms-cloudpack/common-types';\nimport { requiredChangeTypes } from './types/GeneratedChange.js';\nimport type { EnsurePackageBundledResult } from '@ms-cloudpack/api-server';\n\n/**\n * Creates a summary tracking helper for the `init` verb to use to record statistics about results and needed\n * changes. The `record*` methods of the returned object will be used within init to add the stats, and the\n * `summarize` method will return the final tally. The resulting `InitSummary` object can be used in the\n * `formatInitSummary` helper to convert it to a string for the user.\n */\nexport class InitSummaryData {\n /** Set this to indicate that the generated config was deleted. */\n public deletedGeneratedConfig = false;\n\n private _packageResults: Record<string, InitPackageResult>;\n private _generatedUpdates: Record<string, GeneratedPackageChanges>;\n private _startTime: number;\n private _appPath: string;\n private _check: boolean;\n\n constructor(\n params: Pick<InitOptions, 'check'> & {\n appPath: string;\n },\n ) {\n this._packageResults = {};\n this._generatedUpdates = {};\n this._startTime = Date.now();\n this._appPath = params.appPath;\n this._check = !!params.check;\n }\n\n /**\n * Returns whether any generated changes have been recorded.\n */\n public hasChanges(): boolean {\n return Object.values(this._generatedUpdates).length > 0;\n }\n\n /**\n * Saves a package result.\n */\n public recordResult(\n packagePath: string,\n result: Pick<EnsurePackageBundledResult, 'name' | 'version' | 'info' | 'outputPath' | 'errors' | 'warnings'>,\n ): void {\n this._packageResults[packagePath] = {\n path: packagePath,\n name: result.name,\n version: result.version,\n info: result.info,\n outputPath: result.outputPath,\n errors: result.errors,\n warnings: result.warnings,\n };\n }\n\n /**\n * Record an exception for a given package path.\n * This creates a bundle message like \"Error thrown while (context): (error)\".\n * (Unlike `addErrors`, this will create an overall package result if one doesn't exist yet.)\n */\n public recordException(params: {\n packagePath: string;\n error: unknown;\n source: string;\n /** Description of the context in which the error was thrown, e.g. \"evaluating package\" */\n context: string;\n /** Package name in case no result has been recorded for this package yet */\n name?: string;\n /** Package version in case no result has been recorded for this package yet */\n version?: string;\n }): void {\n const { packagePath, error, source, context, name = '<unknown>', version = '<unknown>' } = params;\n if (!this._packageResults[packagePath]) {\n this.recordResult(packagePath, { name, version });\n }\n\n const text = `Error thrown while ${context}: ${(error as Error).stack || error}`;\n this.addErrors(packagePath, [{ text, source }]);\n }\n\n /**\n * Record more errors for a given package path.\n */\n public addErrors(packagePath: string, errors: BundleMessage[]): void {\n const packageResult = this._packageResults[packagePath];\n if (!packageResult) {\n throw new Error(`Package result not found for path ${packagePath}`);\n }\n\n packageResult.errors = [...(packageResult.errors || []), ...errors];\n }\n\n /**\n * Returns the package results.\n * @returns The package results.\n */\n public getResults(): Record<string, InitPackageResult> {\n return this._packageResults;\n }\n\n /**\n * Saves a generated file update.\n * @param allChanges - The generated file update to save.\n */\n public recordGeneratedChanges(allChanges: GeneratedPackageChanges[]): void {\n for (const update of allChanges) {\n const { name, version, path, changes } = update;\n // Only record changes if there are any, so that hasChanges() is accurate.\n if (changes.length) {\n const updatesForPackage = (this._generatedUpdates[path] ??= { name, version, path, changes: [] });\n\n updatesForPackage.changes.push(...changes);\n }\n }\n }\n\n /**\n * Returns the summary of the results.\n */\n public summarize(): InitSummary {\n const duration = Date.now() - this._startTime;\n let totalSuccess = 0;\n let totalErrors = 0;\n let totalWarnings = 0;\n let totalChanges = 0;\n let totalRequiredChanges = 0;\n const packagesWithErrors: InitPackageResultErrors[] = [];\n const packagesWithWarnings: InitPackageResultWarnings[] = [];\n\n for (const packageResult of Object.values(this._packageResults)) {\n if (packageResult.errors?.length) {\n packagesWithErrors.push(packageResult as InitPackageResultErrors);\n totalErrors += packageResult.errors.length;\n } else {\n totalSuccess++;\n }\n\n if (packageResult.warnings?.length) {\n packagesWithWarnings.push(packageResult as InitPackageResultWarnings);\n totalWarnings += packageResult.warnings.length;\n }\n }\n\n const sortedUpdates = Object.values(this._generatedUpdates).sort((a, b) => a.path.localeCompare(b.path));\n\n for (const updates of sortedUpdates) {\n totalChanges += updates.changes.length;\n totalRequiredChanges += updates.changes.filter((u) => requiredChangeTypes[u.type]).length;\n updates.changes = updates.changes.sort((a, b) => a.change.localeCompare(b.change));\n }\n\n return {\n appPath: this._appPath,\n duration,\n totalPackages: Object.keys(this._packageResults).length,\n totalSuccess,\n totalErrors,\n totalWarnings,\n totalChanges,\n totalRequiredChanges,\n failed: totalErrors > 0 || (this._check && totalRequiredChanges > 0),\n packagesWithErrors,\n packagesWithWarnings,\n generatedFileUpdates: sortedUpdates,\n deletedGeneratedConfig: this.deletedGeneratedConfig,\n };\n }\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import type { AppCommandContext, CommandActionParams } from '../../types/Command
|
|
|
4
4
|
/**
|
|
5
5
|
* Init execution function.
|
|
6
6
|
*/
|
|
7
|
-
export declare function init(params: Pick<CommandActionParams<InitOptions>, keyof AppCommandContext | 'options' | '
|
|
7
|
+
export declare function init(params: Pick<CommandActionParams<InitOptions>, keyof AppCommandContext | 'options' | 'isMultiApp'> & {
|
|
8
8
|
/**
|
|
9
9
|
* App summary object, created ahead of time so that a partial summary can be generated
|
|
10
10
|
* if the process is interrupted.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/commands/init/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAI1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAS3F;;GAEG;AACH,wBAAsB,IAAI,CACxB,MAAM,EAAE,IAAI,CAAC,mBAAmB,CAAC,WAAW,CAAC,EAAE,MAAM,iBAAiB,GAAG,SAAS,GAAG,
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/commands/init/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAI1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAS3F;;GAEG;AACH,wBAAsB,IAAI,CACxB,MAAM,EAAE,IAAI,CAAC,mBAAmB,CAAC,WAAW,CAAC,EAAE,MAAM,iBAAiB,GAAG,SAAS,GAAG,YAAY,CAAC,GAAG;IACnG;;;OAGG;IACH,WAAW,EAAE,eAAe,CAAC;CAC9B,GACA,OAAO,CAAC,IAAI,CAAC,CAgBf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","sourceRoot":"","sources":["../../../src/commands/init/init.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,YAAY,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C;YAClC,WAAW,CAAC,sBAAsB,GAAG,IAAI,CAAC;QAC5C,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type { EnsurePackageBundledContext } from '@ms-cloudpack/api-server';\nimport type { PackageImporterContext } from '@ms-cloudpack/common-types';\nimport type { InitOptions } from './types/InitOptions.js';\n\nimport { createPartialApiContext } from '@ms-cloudpack/api-server';\nimport { writeGeneratedConfig } from '@ms-cloudpack/config';\nimport type { InitSummaryData } from './InitSummaryData.js';\nimport { evaluatePath } from './evaluatePath.js';\nimport { verifyExports } from './verifyExports.js';\nimport type { AppCommandContext, CommandActionParams } from '../../types/CommandAction.js';\nimport path from 'path';\nimport { writeJson } from '@ms-cloudpack/json-utilities';\nimport { runPrerequisites } from '../../utilities/runPrerequisites.js';\nimport { getFilteredPackages } from '../../utilities/getFilteredPackages.js';\nimport { optimizeDependencies } from './optimizeDependencies.js';\nimport { bulletedList } from '@ms-cloudpack/task-reporter';\nimport type { Span } from '@ms-cloudpack/telemetry';\n\n/**\n * Init execution function.\n */\nexport async function init(\n params: Pick<CommandActionParams<InitOptions>, keyof AppCommandContext | 'options' | 'autoDispose' | 'isMultiApp'> & {\n /**\n * App summary object, created ahead of time so that a partial summary can be generated\n * if the process is interrupted.\n */\n summaryData: InitSummaryData;\n },\n): Promise<void> {\n const { options, summaryData, isMultiApp, config, telemetryClient } = params;\n\n await telemetryClient.tracer.startActiveSpan('INIT_APP', async (span) => {\n // Run prerequisites for the app.\n await runPrerequisites(params);\n\n // If --reset is specified, reset the generated config.\n if (options.reset) {\n config.generated = {};\n }\n\n const apiContext = await createPartialApiContext(params);\n\n await initApp({ apiContext, span, summaryData, options, isMultiApp });\n });\n}\n\nasync function initApp(\n params: Pick<Parameters<typeof init>[0], 'summaryData' | 'isMultiApp' | 'options'> & {\n apiContext: EnsurePackageBundledContext;\n span: Span;\n },\n): Promise<void> {\n const { apiContext, options, summaryData, span, isMultiApp } = params;\n const { config } = apiContext.session;\n const { appPath } = config;\n\n const resolveMap = apiContext.session.resolveMap;\n\n // Ensure config.generated.packageSettings is initialized.\n config.generated.packageSettings ??= [];\n\n let isExitingPrematurely = false;\n\n await new Promise<void>((resolve) => {\n let pending = 0;\n const visitedSet = new Set<string>();\n const refreshPaths = new Set<string>();\n const priorityMap = new Map<string, number>();\n\n // Start with the app path or requested matches\n const initialPaths = options.match ? getFilteredPackages(resolveMap, options.match) : [appPath];\n if (!initialPaths.length) {\n summaryData.addErrors(appPath, [{ text: `No packages found matching ${options.match}`, source: 'init' }]);\n resolve();\n }\n\n enqueuePaths(new Map(initialPaths.map((packagePath) => [packagePath, undefined])));\n\n /**\n * Enqueue more paths.\n * @param newPaths Mapping from package path to importer context.\n */\n function enqueuePaths(newPaths: Map<string, PackageImporterContext | undefined>): void {\n if (isExitingPrematurely) {\n return;\n }\n\n // Iterate through the given paths.\n for (const [packagePath, importerContext] of newPaths) {\n if (visitedSet.has(packagePath)) {\n console.debug(`Skipping ${packagePath} as it has already been visited.`);\n continue;\n }\n\n visitedSet.add(packagePath);\n pending++;\n\n const shouldForce = refreshPaths.delete(packagePath);\n\n // Get the priority value for this package path, defaults to 0.\n const priority = priorityMap.get(packagePath) ?? 0;\n // Lower priority of this package path by 1.\n priorityMap.set(packagePath, priority - 1);\n\n // Evaluate this path, but don't await - when we're done, we'll re-enqueue newly discovered paths.\n evaluatePath({\n appPath,\n packagePath,\n importerContext,\n config,\n span,\n resolveMap,\n initOptions: options,\n summaryData,\n ctx: apiContext,\n // No need to force if we're in a multi-app scenario\n // as we'll re-evaluate packages if they are different since we use a different task id.\n shouldForce: !isMultiApp && shouldForce,\n isMultiApp,\n priority,\n })\n .then(({ pathsToEvaluate, pathsToRefresh, shouldExit }) => {\n pending--;\n\n if (shouldExit) {\n isExitingPrematurely = true;\n } else if (pathsToEvaluate?.size) {\n // If there are packages that need to be rebuilt, delete them from the visited set to re-enqueue them\n // and add them to the refresh set so that on re-enqueuing we pass the `shouldRerun` flag through\n // on single app runs.\n pathsToRefresh?.forEach((refreshPath) => {\n refreshPaths.add(refreshPath);\n visitedSet.delete(refreshPath);\n });\n\n // Try to enqueue the new paths.\n console.debug(\n `Enqueuing paths found from ${packagePath}:\\n` +\n bulletedList(\n [...pathsToEvaluate].map(([newPath, newContext]) => `${newPath} ${JSON.stringify(newContext)}`),\n ),\n );\n enqueuePaths(pathsToEvaluate);\n }\n\n // If nothing is pending after this call, we're complete.\n if (!pending) {\n resolve();\n }\n })\n .catch((error: unknown) => {\n // Record the exception as an init error for the package.\n // This gives better context than a stack trace which could have come from any package.\n let prefix = 'evaluating package';\n if (importerContext) {\n prefix += ` (context: ${JSON.stringify(importerContext, null, 2).replace(/\\s+/g, ' ')})`;\n }\n summaryData.recordException({ packagePath, error, source: 'init', context: prefix });\n\n // Don't immediately stop evaluation, but don't enqueue more paths.\n isExitingPrematurely = true;\n });\n }\n }\n }).catch((error: unknown) => {\n // If there's an error thrown from some other part of the promise besides evaluatePath (not likely),\n // record it as an init error for the app instead of allowing it to propagate.\n // This allows the overall init summary and any other errors to be logged as usual.\n isExitingPrematurely = true;\n summaryData.recordException({ packagePath: appPath, error, source: 'init', context: 'running init' });\n });\n\n // Log the resolve map to a file if requested. Do this *after* the main init process in case\n // any additional deps were discovered and added.\n if (options.logResolveMap) {\n console.log('\\nWriting resolve map to `resolve-map.json`.');\n await writeJson(path.join(appPath, 'resolve-map.json'), resolveMap);\n }\n\n if (isExitingPrematurely) {\n span.setAttribute('isExitingPrematurely', true);\n } else {\n // Only do extra checks if there's not a major error already\n if (config.features?.optimizeDependencies) {\n // Conditionally scan dependency usage so that we can populate\n // include/excludeDependencies automatically, ensuring the dep list\n // is both minimal (remove unused deps) and complete (include\n // specific devDeps.)\n const excludedDependenciesChanges = await optimizeDependencies(summaryData.getResults(), apiContext);\n summaryData.recordGeneratedChanges(excludedDependenciesChanges);\n }\n\n if (config.features?.verifyExports) {\n const packageResults = await verifyExports(summaryData.getResults(), apiContext);\n for (const [packagePath, errors] of Object.entries(packageResults)) {\n summaryData.addErrors(packagePath, errors);\n }\n }\n }\n\n // The feature \"removeUnusedExports\" doesn't (yet) write summary changes, but we still\n // want to write the generated config if that featureFlag is on.\n const hasSummaryChanges = config.features?.removeUnusedExports || summaryData.hasChanges();\n\n if (!options.check && hasSummaryChanges) {\n // Update the generated config: either write it if there are settings, or delete it if it\n // previously existed but is no longer needed.\n const generatedResult = await writeGeneratedConfig(config.generated, appPath);\n if (generatedResult === 'deleted') {\n summaryData.deletedGeneratedConfig = true;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"init.js","sourceRoot":"","sources":["../../../src/commands/init/init.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAG3D;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,IAAI,CACxB,MAMC;IAED,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC;IAE7E,MAAM,eAAe,CAAC,MAAM,CAAC,eAAe,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QACtE,iCAAiC;QACjC,MAAM,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAE/B,uDAAuD;QACv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AAM,CAAC,WAAW,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC;gBACnE,WAAW,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC;IACH,CAAC;IAED,sFAAsF;IACtF,gEAAgE;IAChE,MAAM,iBAAiB,GAAG,MAAM,CAAC,QAAQ,EAAE,mBAAmB,IAAI,WAAW,CAAC,UAAU,EAAE,CAAC;IAE3F,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,iBAAiB,EAAE,CAAC;QACxC,yFAAyF;QACzF,8CAA8C;QAC9C,MAAM,eAAe,GAAG,MAAM,oBAAoB,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC9E,IAAI,eAAe,KAAK,SAAS,EAAE,CAAC;YAClC,WAAW,CAAC,sBAAsB,GAAG,IAAI,CAAC;QAC5C,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type { EnsurePackageBundledContext } from '@ms-cloudpack/api-server';\nimport type { PackageImporterContext } from '@ms-cloudpack/common-types';\nimport type { InitOptions } from './types/InitOptions.js';\n\nimport { createPartialApiContext } from '@ms-cloudpack/api-server';\nimport { writeGeneratedConfig } from '@ms-cloudpack/config';\nimport type { InitSummaryData } from './InitSummaryData.js';\nimport { evaluatePath } from './evaluatePath.js';\nimport { verifyExports } from './verifyExports.js';\nimport type { AppCommandContext, CommandActionParams } from '../../types/CommandAction.js';\nimport path from 'path';\nimport { writeJson } from '@ms-cloudpack/json-utilities';\nimport { runPrerequisites } from '../../utilities/runPrerequisites.js';\nimport { getFilteredPackages } from '../../utilities/getFilteredPackages.js';\nimport { optimizeDependencies } from './optimizeDependencies.js';\nimport { bulletedList } from '@ms-cloudpack/task-reporter';\nimport type { Span } from '@ms-cloudpack/telemetry';\n\n/**\n * Init execution function.\n */\nexport async function init(\n params: Pick<CommandActionParams<InitOptions>, keyof AppCommandContext | 'options' | 'isMultiApp'> & {\n /**\n * App summary object, created ahead of time so that a partial summary can be generated\n * if the process is interrupted.\n */\n summaryData: InitSummaryData;\n },\n): Promise<void> {\n const { options, summaryData, isMultiApp, config, telemetryClient } = params;\n\n await telemetryClient.tracer.startActiveSpan('INIT_APP', async (span) => {\n // Run prerequisites for the app.\n await runPrerequisites(params);\n\n // If --reset is specified, reset the generated config.\n if (options.reset) {\n config.generated = {};\n }\n\n const apiContext = await createPartialApiContext(params);\n\n await initApp({ apiContext, span, summaryData, options, isMultiApp });\n });\n}\n\nasync function initApp(\n params: Pick<Parameters<typeof init>[0], 'summaryData' | 'isMultiApp' | 'options'> & {\n apiContext: EnsurePackageBundledContext;\n span: Span;\n },\n): Promise<void> {\n const { apiContext, options, summaryData, span, isMultiApp } = params;\n const { config } = apiContext.session;\n const { appPath } = config;\n\n const resolveMap = apiContext.session.resolveMap;\n\n // Ensure config.generated.packageSettings is initialized.\n config.generated.packageSettings ??= [];\n\n let isExitingPrematurely = false;\n\n await new Promise<void>((resolve) => {\n let pending = 0;\n const visitedSet = new Set<string>();\n const refreshPaths = new Set<string>();\n const priorityMap = new Map<string, number>();\n\n // Start with the app path or requested matches\n const initialPaths = options.match ? getFilteredPackages(resolveMap, options.match) : [appPath];\n if (!initialPaths.length) {\n summaryData.addErrors(appPath, [{ text: `No packages found matching ${options.match}`, source: 'init' }]);\n resolve();\n }\n\n enqueuePaths(new Map(initialPaths.map((packagePath) => [packagePath, undefined])));\n\n /**\n * Enqueue more paths.\n * @param newPaths Mapping from package path to importer context.\n */\n function enqueuePaths(newPaths: Map<string, PackageImporterContext | undefined>): void {\n if (isExitingPrematurely) {\n return;\n }\n\n // Iterate through the given paths.\n for (const [packagePath, importerContext] of newPaths) {\n if (visitedSet.has(packagePath)) {\n console.debug(`Skipping ${packagePath} as it has already been visited.`);\n continue;\n }\n\n visitedSet.add(packagePath);\n pending++;\n\n const shouldForce = refreshPaths.delete(packagePath);\n\n // Get the priority value for this package path, defaults to 0.\n const priority = priorityMap.get(packagePath) ?? 0;\n // Lower priority of this package path by 1.\n priorityMap.set(packagePath, priority - 1);\n\n // Evaluate this path, but don't await - when we're done, we'll re-enqueue newly discovered paths.\n evaluatePath({\n appPath,\n packagePath,\n importerContext,\n config,\n span,\n resolveMap,\n initOptions: options,\n summaryData,\n ctx: apiContext,\n // No need to force if we're in a multi-app scenario\n // as we'll re-evaluate packages if they are different since we use a different task id.\n shouldForce: !isMultiApp && shouldForce,\n isMultiApp,\n priority,\n })\n .then(({ pathsToEvaluate, pathsToRefresh, shouldExit }) => {\n pending--;\n\n if (shouldExit) {\n isExitingPrematurely = true;\n } else if (pathsToEvaluate?.size) {\n // If there are packages that need to be rebuilt, delete them from the visited set to re-enqueue them\n // and add them to the refresh set so that on re-enqueuing we pass the `shouldRerun` flag through\n // on single app runs.\n pathsToRefresh?.forEach((refreshPath) => {\n refreshPaths.add(refreshPath);\n visitedSet.delete(refreshPath);\n });\n\n // Try to enqueue the new paths.\n console.debug(\n `Enqueuing paths found from ${packagePath}:\\n` +\n bulletedList(\n [...pathsToEvaluate].map(([newPath, newContext]) => `${newPath} ${JSON.stringify(newContext)}`),\n ),\n );\n enqueuePaths(pathsToEvaluate);\n }\n\n // If nothing is pending after this call, we're complete.\n if (!pending) {\n resolve();\n }\n })\n .catch((error: unknown) => {\n // Record the exception as an init error for the package.\n // This gives better context than a stack trace which could have come from any package.\n let prefix = 'evaluating package';\n if (importerContext) {\n prefix += ` (context: ${JSON.stringify(importerContext, null, 2).replace(/\\s+/g, ' ')})`;\n }\n summaryData.recordException({ packagePath, error, source: 'init', context: prefix });\n\n // Don't immediately stop evaluation, but don't enqueue more paths.\n isExitingPrematurely = true;\n });\n }\n }\n }).catch((error: unknown) => {\n // If there's an error thrown from some other part of the promise besides evaluatePath (not likely),\n // record it as an init error for the app instead of allowing it to propagate.\n // This allows the overall init summary and any other errors to be logged as usual.\n isExitingPrematurely = true;\n summaryData.recordException({ packagePath: appPath, error, source: 'init', context: 'running init' });\n });\n\n // Log the resolve map to a file if requested. Do this *after* the main init process in case\n // any additional deps were discovered and added.\n if (options.logResolveMap) {\n console.log('\\nWriting resolve map to `resolve-map.json`.');\n await writeJson(path.join(appPath, 'resolve-map.json'), resolveMap);\n }\n\n if (isExitingPrematurely) {\n span.setAttribute('isExitingPrematurely', true);\n } else {\n // Only do extra checks if there's not a major error already\n if (config.features?.optimizeDependencies) {\n // Conditionally scan dependency usage so that we can populate\n // include/excludeDependencies automatically, ensuring the dep list\n // is both minimal (remove unused deps) and complete (include\n // specific devDeps.)\n const excludedDependenciesChanges = await optimizeDependencies(summaryData.getResults(), apiContext);\n summaryData.recordGeneratedChanges(excludedDependenciesChanges);\n }\n\n if (config.features?.verifyExports) {\n const packageResults = await verifyExports(summaryData.getResults(), apiContext);\n for (const [packagePath, errors] of Object.entries(packageResults)) {\n summaryData.addErrors(packagePath, errors);\n }\n }\n }\n\n // The feature \"removeUnusedExports\" doesn't (yet) write summary changes, but we still\n // want to write the generated config if that featureFlag is on.\n const hasSummaryChanges = config.features?.removeUnusedExports || summaryData.hasChanges();\n\n if (!options.check && hasSummaryChanges) {\n // Update the generated config: either write it if there are settings, or delete it if it\n // previously existed but is no longer needed.\n const generatedResult = await writeGeneratedConfig(config.generated, appPath);\n if (generatedResult === 'deleted') {\n summaryData.deletedGeneratedConfig = true;\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { PartialContext } from '@ms-cloudpack/api-server';
|
|
2
|
+
import type { BundleMessage } from '@ms-cloudpack/common-types';
|
|
2
3
|
import type { InitPackageResult } from './types/InitPackageResult.js';
|
|
3
4
|
/**
|
|
4
5
|
* Checks that the imports/exports of packages match.
|
|
@@ -7,8 +8,5 @@ import type { InitPackageResult } from './types/InitPackageResult.js';
|
|
|
7
8
|
* @param context - The context to use.
|
|
8
9
|
* @returns Mapping from absolute package path to errors.
|
|
9
10
|
*/
|
|
10
|
-
export declare function verifyExports(packageResults: Record<string, InitPackageResult>, context:
|
|
11
|
-
packages: PackageDefinitionsCache;
|
|
12
|
-
session: Session;
|
|
13
|
-
}): Promise<Record<string, BundleMessage[]>>;
|
|
11
|
+
export declare function verifyExports(packageResults: Record<string, InitPackageResult>, context: PartialContext<'packages', 'config' | 'resolveMap'>): Promise<Record<string, BundleMessage[]>>;
|
|
14
12
|
//# sourceMappingURL=verifyExports.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyExports.d.ts","sourceRoot":"","sources":["../../../src/commands/init/verifyExports.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"verifyExports.d.ts","sourceRoot":"","sources":["../../../src/commands/init/verifyExports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,KAAK,EACV,aAAa,EAMd,MAAM,4BAA4B,CAAC;AAQpC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAMtE;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,EACjD,OAAO,EAAE,cAAc,CAAC,UAAU,EAAE,QAAQ,GAAG,YAAY,CAAC,GAC3D,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC,CA+K1C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyExports.js","sourceRoot":"","sources":["../../../src/commands/init/verifyExports.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,qBAAqB,EACrB,cAAc,GACf,MAAM,iCAAiC,CAAC;AACzC,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAmB,MAAM,6BAA6B,CAAC;AAC/F,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OA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C,GAAG,MAAM,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,iBAAiB,CAAC,OAK1B;IAMC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,mBAAmB,EAAE,GAAG,OAAO,CAAC;IAE7E,MAAM,kBAAkB,GAAG,mBAAmB,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;IACxF,MAAM,SAAS,GACb,kBAAkB;QAClB,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,kBAAkB,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,KAAK,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAElH,0FAA0F;IAC1F,uBAAuB;IACvB,IAAI,CAAC,kBAAkB,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC;QAC5C,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,SAAoD,EAAE,CAAC;AACjG,CAAC","sourcesContent":["import type { BundleInfo } from '@ms-cloudpack/api-server';\nimport type {\n BundleMessage,\n PackageDefinitionsCache,\n PackageJson,\n ResolveMap,\n ResolveMapEntry,\n Session,\n WithRequired,\n} from '@ms-cloudpack/common-types';\nimport {\n findResolveMapEntry,\n getDependencies,\n getUnusedDependencies,\n getSourceEntry,\n} from '@ms-cloudpack/package-utilities';\nimport path from 'path';\nimport type { InitPackageResult } from './types/InitPackageResult.js';\nimport { bulletedList, formatPackageName, type BulletList } from '@ms-cloudpack/task-reporter';\nimport { getPackageSettings } from '@ms-cloudpack/config';\nimport semver from 'semver';\nimport { parseImportString } from '@ms-cloudpack/path-string-parsing';\n\n/**\n * Checks that the imports/exports of packages match.\n * To be called before `summarize`.\n * @param packageResults - The package results to check.\n * @param context - The context to use.\n * @returns Mapping from absolute package path to errors.\n */\nexport async function verifyExports(\n packageResults: Record<string, InitPackageResult>,\n context: {\n packages: PackageDefinitionsCache;\n session: Session;\n },\n): Promise<Record<string, BundleMessage[]>> {\n const { packages, session } = context;\n const { config, resolveMap } = session;\n const allErrors: Record<string, BundleMessage[]> = {};\n const packageResultsArray = Object.values(packageResults);\n const importsCache: Record<string, string[]> = {};\n\n // Iterate through each package\n for (const parentResult of packageResultsArray) {\n // Skip packages with build errors or no info\n if (!parentResult?.info || !parentResult.outputPath || parentResult.errors?.length) {\n continue;\n }\n\n // Skip packages with `ignoreMissingExports` set to true.\n const { name, version, path: parentPath } = parentResult;\n const ignoreMissingExports =\n getPackageSettings({\n name,\n version,\n userPackageSettings: config.packageSettings,\n includeBuiltIn: true,\n generatedPackageSettings: undefined,\n }).userPackageSettings?.ignoreMissingExports || {};\n\n if (ignoreMissingExports === true) {\n continue;\n }\n\n const parentDefinition = await packages.get(parentPath);\n\n /**\n * Mapping from imported dependency package ID (`name@version`) to import path\n * to an object with export names missing from that file, the importString, and bundledFile.\n */\n const depsMissingExports: Record<\n string,\n Record<\n string,\n {\n missingNames: Set<string>;\n importName: string;\n importPath: string;\n importVersion: string;\n bundledFile: string;\n }\n >\n > = {};\n const invalidSemver: Record<string, string> = {};\n\n // Find the main entry point for the parent package to list as the importing bundle.\n const importingBundle = path.join(parentResult.outputPath, parentResult.info?.['.']?.bundlePath || '');\n\n // Find the main entry point for the parent package to list as the importing source.\n const sourceMainEntry = await getSourceEntry({ entry: '.', inputPath: parentPath }, { packages, config });\n const importingSource = path.join(parentPath, sourceMainEntry || '.');\n\n // Iterate through each entry path from the parent package\n for (const { consumes } of Object.values(parentResult.info)) {\n // Skip entries with no imports\n if (!consumes?.length) {\n continue;\n }\n\n // Iterate through each imported package\n for (const { packageName: depName, importPath: depImportPath, names: consumedNames } of consumes) {\n const dependencyInfo = getDependencyInfo({\n packageName: depName,\n definition: parentDefinition,\n resolveMap,\n packageResultsArray,\n });\n // We don't have enough info to check this dependency, so skip it.\n if (!dependencyInfo) {\n continue;\n }\n\n const { depResolveMapEntry, depResult } = dependencyInfo;\n const { outputPath: depOutputPath, info: depEntries } = depResult;\n\n const importProduces = depEntries[depImportPath]?.produces;\n if (!importProduces) {\n // Skip if the imported package has no entry for the import path. (If the path is missing,\n // evaluateImportsForOverrides has already run and tried to fix it or reported an error.)\n continue;\n }\n\n const importProducesStarResult = await importProducesStar({\n packagePath: depResolveMapEntry.path,\n importPath: depImportPath,\n info: depEntries,\n context: { packages, resolveMap, packageResultsArray },\n cache: importsCache,\n });\n\n // Find any missing names.\n const missing = consumedNames.filter(\n (namedImport) =>\n namedImport !== '*' &&\n !importProducesStarResult.includes(namedImport) &&\n !ignoreMissingExports[depImportPath]?.includes(namedImport),\n );\n if (!missing.length) {\n continue;\n }\n\n // Figure out which actual file the exports appear to be missing from.\n const relativePath =\n (await getSourceEntry({ entry: depImportPath, inputPath: depResolveMapEntry.path }, { packages, config })) ||\n // If the package is missing an exports map, assume the import path is the real path.\n depImportPath;\n const filePath = path.join(depResolveMapEntry.path, relativePath);\n\n // Save the missing names for this path within the package.\n const depKey = `${depResolveMapEntry.name}@${depResolveMapEntry.version}`;\n depsMissingExports[depKey] ??= {};\n depsMissingExports[depKey][filePath] ??= {\n missingNames: new Set(),\n importName: depName,\n importPath: depImportPath,\n importVersion: depResolveMapEntry.version,\n bundledFile: path.join(depOutputPath ?? '', depEntries[depImportPath]?.bundlePath),\n };\n missing.forEach((m) => depsMissingExports[depKey][filePath].missingNames.add(m));\n\n // Check if the package satisfies the parent semver requirement.\n const requiredVersion =\n !invalidSemver[depKey] &&\n (getDependencies(parentDefinition)[depName] || getUnusedDependencies(parentDefinition)[depName]);\n if (requiredVersion && !semver.satisfies(depResolveMapEntry.version, requiredVersion)) {\n invalidSemver[depKey] = requiredVersion;\n }\n }\n }\n\n const errors: BundleMessage[] = [];\n\n for (const [packageId, missing] of Object.entries(depsMissingExports)) {\n // We want a single error for each package, with a bulleted list of files with missing exports.\n for (const [sourceFile, errorInfo] of Object.entries(missing)) {\n const { missingNames, importName, importPath, importVersion, bundledFile } = errorInfo;\n const error: BulletList = [\n `Importing bundle: ${importingBundle}`,\n `Importing source: ${importingSource}`,\n `Exporting package: ${formatPackageName({ name: importName, version: importVersion })}${importPath === '.' ? '' : ` (imported path: \"${importPath}\")`}`,\n `Exporting bundle: ${bundledFile}`,\n `Exporting source: ${sourceFile}`,\n `Missing export(s): { ${Array.from(missingNames).join(', ')} }`,\n ];\n\n if (invalidSemver[packageId]) {\n // If we have an invalid semver, add a note about that after exporting package.\n error.splice(\n 3,\n 0,\n `Incompatible version: ${formatPackageName({ name: importName, version: importVersion })} does not satisfy importer requirement \"${invalidSemver[packageId]}\"`,\n ['If this was unexpected, make sure you installed dependencies after pulling the latest changes.'],\n );\n }\n\n errors.push({\n text: `A bundle imported names from another bundle which were not exported:\\n${bulletedList(error)}\\n`,\n source: 'verify exports',\n // Don't include a whole-message location here because that doesn't make sense for this error type,\n // and we already put full paths to individual problem files within the message.\n });\n }\n }\n\n if (errors.length) {\n allErrors[parentPath] = errors;\n }\n }\n\n return allErrors;\n}\n\nasync function importProducesStar(params: {\n packagePath: string;\n info: BundleInfo;\n importPath: string;\n context: {\n packages: PackageDefinitionsCache;\n resolveMap: ResolveMap;\n packageResultsArray: InitPackageResult[];\n };\n visited?: Set<string>;\n cache?: Record<string, string[]>;\n}): Promise<string[]> {\n const { packagePath, info, importPath, context, visited = new Set(), cache = {} } = params;\n\n const key = `${packagePath}${importPath}`;\n // Check if the entry has already been visited to avoid cycles\n if (visited.has(key)) {\n return [];\n }\n\n // Mark the current entry as visited\n visited.add(key);\n\n const cachedResult = cache[key];\n if (cachedResult) {\n return cachedResult;\n }\n\n const { packages, resolveMap, packageResultsArray } = context;\n let result: string[] = [];\n\n // Iterate over the produced names\n for (const name of info[importPath].produces) {\n if (name.startsWith('*')) {\n // Extract the name and path from the format \"*ImportString\"\n const { packageName: depName, importPath: depImportPath } = parseImportString(name.slice(1));\n\n const dependencyInfo = getDependencyInfo({\n packageName: depName,\n definition: await packages.get(packagePath),\n resolveMap,\n packageResultsArray,\n });\n\n if (dependencyInfo) {\n const { depResolveMapEntry, depResult } = dependencyInfo;\n // Recursively aggregate the produced names from the other package\n result = result.concat(\n await importProducesStar({\n packagePath: depResolveMapEntry.path,\n info: depResult.info,\n importPath: depImportPath,\n context,\n visited,\n }),\n );\n }\n } else {\n // Add the name to the result if it doesn't start with '*'\n result.push(name);\n }\n }\n\n cache[key] = result;\n return result;\n}\n\nfunction getDependencyInfo(options: {\n packageName: string;\n definition: PackageJson;\n resolveMap: ResolveMap;\n packageResultsArray: InitPackageResult[];\n}):\n | {\n depResult: WithRequired<InitPackageResult, 'info'>;\n depResolveMapEntry: ResolveMapEntry;\n }\n | undefined {\n const { packageName, definition, resolveMap, packageResultsArray } = options;\n\n const depResolveMapEntry = findResolveMapEntry({ packageName, definition, resolveMap });\n const depResult =\n depResolveMapEntry &&\n packageResultsArray.find((r) => r.name === depResolveMapEntry.name && r.version === depResolveMapEntry.version);\n\n // Skip if we can't find the imported package in the resolve map, or there's no info about\n // its entries/exports.\n if (!depResolveMapEntry || !depResult?.info) {\n return undefined;\n }\n\n return { depResolveMapEntry, depResult: depResult as WithRequired<InitPackageResult, 'info'> };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"verifyExports.js","sourceRoot":"","sources":["../../../src/commands/init/verifyExports.ts"],"names":[],"mappings":"AASA,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,qBAAqB,EACrB,cAAc,GACf,MAAM,iCAAiC,CAAC;AACzC,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAmB,MAAM,6BAA6B,CAAC;AAC/F,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,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AE,UAAU,EAAE,mBAAmB,EAAE,GAAG,OAAO,CAAC;IAE7E,MAAM,kBAAkB,GAAG,mBAAmB,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;IACxF,MAAM,SAAS,GACb,kBAAkB;QAClB,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,kBAAkB,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,KAAK,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAElH,0FAA0F;IAC1F,uBAAuB;IACvB,IAAI,CAAC,kBAAkB,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC;QAC5C,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,SAAoD,EAAE,CAAC;AACjG,CAAC","sourcesContent":["import type { BundleInfo, PartialContext } from '@ms-cloudpack/api-server';\nimport type {\n BundleMessage,\n PackageDefinitionsCache,\n PackageJson,\n ResolveMap,\n ResolveMapEntry,\n WithRequired,\n} from '@ms-cloudpack/common-types';\nimport {\n findResolveMapEntry,\n getDependencies,\n getUnusedDependencies,\n getSourceEntry,\n} from '@ms-cloudpack/package-utilities';\nimport path from 'path';\nimport type { InitPackageResult } from './types/InitPackageResult.js';\nimport { bulletedList, formatPackageName, type BulletList } from '@ms-cloudpack/task-reporter';\nimport { getPackageSettings } from '@ms-cloudpack/config';\nimport semver from 'semver';\nimport { parseImportString } from '@ms-cloudpack/path-string-parsing';\n\n/**\n * Checks that the imports/exports of packages match.\n * To be called before `summarize`.\n * @param packageResults - The package results to check.\n * @param context - The context to use.\n * @returns Mapping from absolute package path to errors.\n */\nexport async function verifyExports(\n packageResults: Record<string, InitPackageResult>,\n context: PartialContext<'packages', 'config' | 'resolveMap'>,\n): Promise<Record<string, BundleMessage[]>> {\n const { packages, session } = context;\n const { config, resolveMap } = session;\n const allErrors: Record<string, BundleMessage[]> = {};\n const packageResultsArray = Object.values(packageResults);\n const importsCache: Record<string, string[]> = {};\n\n // Iterate through each package\n for (const parentResult of packageResultsArray) {\n // Skip packages with build errors or no info\n if (!parentResult?.info || !parentResult.outputPath || parentResult.errors?.length) {\n continue;\n }\n\n // Skip packages with `ignoreMissingExports` set to true.\n const { name, version, path: parentPath } = parentResult;\n const ignoreMissingExports =\n getPackageSettings({\n name,\n version,\n userPackageSettings: config.packageSettings,\n includeBuiltIn: true,\n generatedPackageSettings: undefined,\n }).userPackageSettings?.ignoreMissingExports || {};\n\n if (ignoreMissingExports === true) {\n continue;\n }\n\n const parentDefinition = await packages.get(parentPath);\n\n /**\n * Mapping from imported dependency package ID (`name@version`) to import path\n * to an object with export names missing from that file, the importString, and bundledFile.\n */\n const depsMissingExports: Record<\n string,\n Record<\n string,\n {\n missingNames: Set<string>;\n importName: string;\n importPath: string;\n importVersion: string;\n bundledFile: string;\n }\n >\n > = {};\n const invalidSemver: Record<string, string> = {};\n\n // Find the main entry point for the parent package to list as the importing bundle.\n const importingBundle = path.join(parentResult.outputPath, parentResult.info?.['.']?.bundlePath || '');\n\n // Find the main entry point for the parent package to list as the importing source.\n const sourceMainEntry = await getSourceEntry({ entry: '.', inputPath: parentPath }, { packages, config });\n const importingSource = path.join(parentPath, sourceMainEntry || '.');\n\n // Iterate through each entry path from the parent package\n for (const { consumes } of Object.values(parentResult.info)) {\n // Skip entries with no imports\n if (!consumes?.length) {\n continue;\n }\n\n // Iterate through each imported package\n for (const { packageName: depName, importPath: depImportPath, names: consumedNames } of consumes) {\n const dependencyInfo = getDependencyInfo({\n packageName: depName,\n definition: parentDefinition,\n resolveMap,\n packageResultsArray,\n });\n // We don't have enough info to check this dependency, so skip it.\n if (!dependencyInfo) {\n continue;\n }\n\n const { depResolveMapEntry, depResult } = dependencyInfo;\n const { outputPath: depOutputPath, info: depEntries } = depResult;\n\n const importProduces = depEntries[depImportPath]?.produces;\n if (!importProduces) {\n // Skip if the imported package has no entry for the import path. (If the path is missing,\n // evaluateImportsForOverrides has already run and tried to fix it or reported an error.)\n continue;\n }\n\n const importProducesStarResult = await importProducesStar({\n packagePath: depResolveMapEntry.path,\n importPath: depImportPath,\n info: depEntries,\n context: { packages, resolveMap, packageResultsArray },\n cache: importsCache,\n });\n\n // Find any missing names.\n const missing = consumedNames.filter(\n (namedImport) =>\n namedImport !== '*' &&\n !importProducesStarResult.includes(namedImport) &&\n !ignoreMissingExports[depImportPath]?.includes(namedImport),\n );\n if (!missing.length) {\n continue;\n }\n\n // Figure out which actual file the exports appear to be missing from.\n const relativePath =\n (await getSourceEntry({ entry: depImportPath, inputPath: depResolveMapEntry.path }, { packages, config })) ||\n // If the package is missing an exports map, assume the import path is the real path.\n depImportPath;\n const filePath = path.join(depResolveMapEntry.path, relativePath);\n\n // Save the missing names for this path within the package.\n const depKey = `${depResolveMapEntry.name}@${depResolveMapEntry.version}`;\n depsMissingExports[depKey] ??= {};\n depsMissingExports[depKey][filePath] ??= {\n missingNames: new Set(),\n importName: depName,\n importPath: depImportPath,\n importVersion: depResolveMapEntry.version,\n bundledFile: path.join(depOutputPath ?? '', depEntries[depImportPath]?.bundlePath),\n };\n missing.forEach((m) => depsMissingExports[depKey][filePath].missingNames.add(m));\n\n // Check if the package satisfies the parent semver requirement.\n const requiredVersion =\n !invalidSemver[depKey] &&\n (getDependencies(parentDefinition)[depName] || getUnusedDependencies(parentDefinition)[depName]);\n if (requiredVersion && !semver.satisfies(depResolveMapEntry.version, requiredVersion)) {\n invalidSemver[depKey] = requiredVersion;\n }\n }\n }\n\n const errors: BundleMessage[] = [];\n\n for (const [packageId, missing] of Object.entries(depsMissingExports)) {\n // We want a single error for each package, with a bulleted list of files with missing exports.\n for (const [sourceFile, errorInfo] of Object.entries(missing)) {\n const { missingNames, importName, importPath, importVersion, bundledFile } = errorInfo;\n const error: BulletList = [\n `Importing bundle: ${importingBundle}`,\n `Importing source: ${importingSource}`,\n `Exporting package: ${formatPackageName({ name: importName, version: importVersion })}${importPath === '.' ? '' : ` (imported path: \"${importPath}\")`}`,\n `Exporting bundle: ${bundledFile}`,\n `Exporting source: ${sourceFile}`,\n `Missing export(s): { ${Array.from(missingNames).join(', ')} }`,\n ];\n\n if (invalidSemver[packageId]) {\n // If we have an invalid semver, add a note about that after exporting package.\n error.splice(\n 3,\n 0,\n `Incompatible version: ${formatPackageName({ name: importName, version: importVersion })} does not satisfy importer requirement \"${invalidSemver[packageId]}\"`,\n ['If this was unexpected, make sure you installed dependencies after pulling the latest changes.'],\n );\n }\n\n errors.push({\n text: `A bundle imported names from another bundle which were not exported:\\n${bulletedList(error)}\\n`,\n source: 'verify exports',\n // Don't include a whole-message location here because that doesn't make sense for this error type,\n // and we already put full paths to individual problem files within the message.\n });\n }\n }\n\n if (errors.length) {\n allErrors[parentPath] = errors;\n }\n }\n\n return allErrors;\n}\n\nasync function importProducesStar(params: {\n packagePath: string;\n info: BundleInfo;\n importPath: string;\n context: {\n packages: PackageDefinitionsCache;\n resolveMap: ResolveMap;\n packageResultsArray: InitPackageResult[];\n };\n visited?: Set<string>;\n cache?: Record<string, string[]>;\n}): Promise<string[]> {\n const { packagePath, info, importPath, context, visited = new Set(), cache = {} } = params;\n\n const key = `${packagePath}${importPath}`;\n // Check if the entry has already been visited to avoid cycles\n if (visited.has(key)) {\n return [];\n }\n\n // Mark the current entry as visited\n visited.add(key);\n\n const cachedResult = cache[key];\n if (cachedResult) {\n return cachedResult;\n }\n\n const { packages, resolveMap, packageResultsArray } = context;\n let result: string[] = [];\n\n // Iterate over the produced names\n for (const name of info[importPath].produces) {\n if (name.startsWith('*')) {\n // Extract the name and path from the format \"*ImportString\"\n const { packageName: depName, importPath: depImportPath } = parseImportString(name.slice(1));\n\n const dependencyInfo = getDependencyInfo({\n packageName: depName,\n definition: await packages.get(packagePath),\n resolveMap,\n packageResultsArray,\n });\n\n if (dependencyInfo) {\n const { depResolveMapEntry, depResult } = dependencyInfo;\n // Recursively aggregate the produced names from the other package\n result = result.concat(\n await importProducesStar({\n packagePath: depResolveMapEntry.path,\n info: depResult.info,\n importPath: depImportPath,\n context,\n visited,\n }),\n );\n }\n } else {\n // Add the name to the result if it doesn't start with '*'\n result.push(name);\n }\n }\n\n cache[key] = result;\n return result;\n}\n\nfunction getDependencyInfo(options: {\n packageName: string;\n definition: PackageJson;\n resolveMap: ResolveMap;\n packageResultsArray: InitPackageResult[];\n}):\n | {\n depResult: WithRequired<InitPackageResult, 'info'>;\n depResolveMapEntry: ResolveMapEntry;\n }\n | undefined {\n const { packageName, definition, resolveMap, packageResultsArray } = options;\n\n const depResolveMapEntry = findResolveMapEntry({ packageName, definition, resolveMap });\n const depResult =\n depResolveMapEntry &&\n packageResultsArray.find((r) => r.name === depResolveMapEntry.name && r.version === depResolveMapEntry.version);\n\n // Skip if we can't find the imported package in the resolve map, or there's no info about\n // its entries/exports.\n if (!depResolveMapEntry || !depResult?.info) {\n return undefined;\n }\n\n return { depResolveMapEntry, depResult: depResult as WithRequired<InitPackageResult, 'info'> };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AutoDisposableList.js","sourceRoot":"","sources":["../../src/utilities/AutoDisposableList.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,kBAAkB;
|
|
1
|
+
{"version":3,"file":"AutoDisposableList.js","sourceRoot":"","sources":["../../src/utilities/AutoDisposableList.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,kBAAkB;IACZ,WAAW,GAAiB,EAAE,CAAC;IAEzC,GAAG,CAAuB,IAAO;QACtC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,KAAK,CAAC,OAAO;QAClB,IAAI,UAAU,GAAG,CAAC,CAAC;QACnB,MAAM,OAAO,CAAC,GAAG,CACf,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE;YAC/B,IAAI,CAAC;gBACH,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC;YACtB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,sBAAuB,GAAa,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;gBACnE,UAAU,EAAE,CAAC;YACf,CAAC;QACH,CAAC,CAAC,CACH,CAAC;QACF,IAAI,UAAU,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,qBAAqB,UAAU,gBAAgB,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { Disposable } from '../types/Disposable.js';\n\nexport class AutoDisposableList {\n private readonly disposables: Disposable[] = [];\n\n public add<T extends Disposable>(item: T): T {\n this.disposables.push(item);\n return item;\n }\n\n public async dispose(): Promise<void> {\n let errorCount = 0;\n await Promise.all(\n this.disposables.map(async (d) => {\n try {\n await d.dispose?.();\n } catch (err) {\n console.error(`Failed to dispose: ${(err as Error).stack || err}`);\n errorCount++;\n }\n }),\n );\n if (errorCount) {\n throw new Error(`Failed to dispose ${errorCount} disposable(s)`);\n }\n }\n}\n"]}
|
|
@@ -11,6 +11,9 @@ import { parseFeature } from './parseFeature.js';
|
|
|
11
11
|
* - Sub-commands should be created with the `.addSubCommand` method on the parent.
|
|
12
12
|
*/
|
|
13
13
|
export class CloudpackCommand {
|
|
14
|
+
_command;
|
|
15
|
+
_programOptions;
|
|
16
|
+
_discoverAppPaths;
|
|
14
17
|
/**
|
|
15
18
|
* This should only be used directly (outside this class) to create the top-level `program` command.
|
|
16
19
|
* To add sub-commands, use `.addSubCommand` instead.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudpackCommand.js","sourceRoot":"","sources":["../../src/utilities/CloudpackCommand.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAqE,MAAM,WAAW,CAAC;AAIrH,OAAO,EAAE,eAAe,EAA8B,MAAM,sBAAsB,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,CAAC,IAAI,EAAE,KAAK,SAAS,CAAC,CAAC;QACjE,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { Command, Help, Option, type AddHelpTextPosition, type Argument, type OutputConfiguration } from 'commander';\nimport type { CommandActionModule } from '../types/CommandAction.js';\nimport type { ProgramOptions } from '../types/ProgramOptions.js';\nimport type { SharedOptions } from '../types/SharedOptions.js';\nimport { CommandExecutor, type CommandExecutorParams } from './CommandExecutor.js';\nimport { environmentInfo } from '@ms-cloudpack/environment';\nimport { parseFeature } from './parseFeature.js';\nimport type { AppPathDiscoveryMode } from '../types/AppPathDiscoveryMode.js';\n\n/**\n * Parameters for creating a command.\n * `TOptions` should be the command-specific options (if any), e.g. `StartOptions`.\n */\ninterface CloudpackCommandParams<TOptions extends object, TArguments extends object>\n extends Pick<CommandExecutorParams, 'discoverAppPaths'> {\n /** Command name */\n name: string;\n\n /** Command description */\n description: string;\n\n /**\n * Options specific to this command. The record ensures that all options are available in the CLI.\n * Allow multiple options for the same key since commander supports it with negatable options.\n */\n options?: Record<keyof TOptions, Option | Option[]>; //\n\n /** Arguments specific to this command. Key order determines the arg order. */\n args?: Record<keyof TArguments, Argument>;\n\n /**\n * Function returning an async import of the command's `src/commands/<name>/execute.ts` module.\n * Importing only on demand makes Cloudpack start up faster since it doesn't have to parse\n * every command's dependencies (many of which may be unrelated to the command being run).\n *\n * This can be undefined for a command that only has sub-commands.\n */\n getExecutor?: () => Promise<CommandActionModule<TOptions>>;\n\n /** Usage message override */\n usage?: string;\n\n /** Alternative name for the command */\n alias?: string;\n\n /** Extra text to be displayed with the built-in help. */\n addHelpText?: {\n /**\n * `'before'` or `'after'` to affect just this command.\n * `'beforeAll'` or `'afterAll'` to affect this command and all its subcommands.\n */\n position: AddHelpTextPosition;\n text: string;\n };\n\n /** Output options override (mainly for testing) */\n outputOptions?: OutputConfiguration;\n\n /**\n * The shared options are relevant for most commands, but this allows omitting them from help\n * where they're not relevant. `true` hides all shared options, or an array hides specific ones.\n */\n hideSharedOptions?: Array<keyof SharedOptions> | true;\n}\n\n/**\n * This wraps the `Command` class from [`commander`](https://www.npmjs.com/package/commander) with\n * Cloudpack-specific functionality and simpler APIs.\n *\n * Similar to the pattern from `commander`, this class represents both the program and its sub-commands.\n * - The top-level \"program\" command should be created with `new CloudpackCommand()`.\n * - Sub-commands should be created with the `.addSubCommand` method on the parent.\n */\nexport class CloudpackCommand<TOptions extends object, TArguments extends object> {\n private _command: Command;\n private _programOptions: ProgramOptions;\n private _discoverAppPaths: AppPathDiscoveryMode | undefined;\n\n /**\n * This should only be used directly (outside this class) to create the top-level `program` command.\n * To add sub-commands, use `.addSubCommand` instead.\n */\n constructor(\n // The extra options here shouldn't be exposed to the `createSubCommand` API\n params: CloudpackCommandParams<TOptions, TArguments> & {\n programOptions: ProgramOptions;\n /** This must be undefined for the top-level program command */\n parent?: Command;\n },\n ) {\n this._programOptions = params.programOptions;\n this._discoverAppPaths = params.discoverAppPaths;\n\n const command = params.parent?.command(params.name) || new Command(params.name);\n this._command = command;\n\n command.version(params.programOptions.version);\n command.description(params.description);\n command.allowExcessArguments(false);\n command.createHelp = () => new CloudpackHelp();\n\n params.usage && command.usage(params.usage);\n params.alias && command.alias(params.alias);\n params.addHelpText && command.addHelpText(params.addHelpText.position, params.addHelpText.text);\n params.outputOptions && command.configureOutput(params.outputOptions);\n params.getExecutor && this._addAction(params.getExecutor);\n\n if (params.args) {\n this._addArguemnts<TArguments>(params.args);\n }\n\n if (params.options) {\n // Add the command-specific options first so they show up first in help\n this._addOptions<TOptions>(params.options);\n }\n\n // Add shared options. These must be manually added to the program command and each sub-command\n // because commander doesn't natively support inheriting options.\n this._addOptions<SharedOptions>(\n {\n verbose: new Option('-v, --verbose', 'Show additional details about the running tasks.'),\n debug: new Option('-d, --debug', 'Show debug information (superset of --verbose).').conflicts('verbose'),\n quiet: new Option('-q, --quiet', 'Disable non-essential logging.').conflicts('verbose').conflicts('debug'),\n color:\n // In the parsed options, this will be a boolean `color` with default value true (except in tests and CI)\n new Option('-n, --no-color', 'Disable colors in the output.').default(\n !environmentInfo.isJest && !environmentInfo.isLage && !environmentInfo.isCI,\n ),\n features: new Option('--features <featureNames...>', 'Enable experimental features.').argParser(parseFeature),\n cachePath: new Option(\n '--cache-path <path>',\n 'Custom cache folder. To change the default, run `cloudpack config set cachePath <path>`.',\n ),\n },\n params.hideSharedOptions,\n );\n }\n\n /** Create a child command. */\n public addSubCommand<TChildOptions extends object, TChildArguments extends object = never>(\n params: CloudpackCommandParams<TChildOptions, TChildArguments>,\n ): CloudpackCommand<TChildOptions, TChildArguments> {\n return new CloudpackCommand<TChildOptions, TChildArguments>({\n ...params,\n programOptions: this._programOptions,\n parent: this._command,\n });\n }\n\n /** Run the program (only works on the top-level program command). */\n public async run(): Promise<void> {\n if (this._command.parent) {\n throw new Error('Only the top-level program command can be run directly.');\n }\n\n await this._command.parseAsync(this._programOptions.argv);\n if (this._command.args.length === 0) {\n this._command.help();\n }\n }\n\n /** Add arguments. The generic enforces that argument objects are included for all keys of a type. */\n private _addArguemnts<TAddArguments extends object>(args: Record<keyof TAddArguments, Argument>): void {\n for (const argument of Object.values(args)) {\n this._command.addArgument(argument as Argument);\n }\n }\n\n /** Add options. The generic enforces that option objects are included for all keys of a type. */\n private _addOptions<TAddOptions extends object>(\n options: Record<keyof TAddOptions, Option | Option[]>,\n hideOptions?: Array<keyof TAddOptions> | true,\n ): void {\n for (const [name, optionOrOptions] of Object.entries(options) as [keyof TAddOptions, Option | Option[]][]) {\n const optionArray = Array.isArray(optionOrOptions) ? optionOrOptions : [optionOrOptions];\n for (const option of optionArray) {\n if (hideOptions === true || hideOptions?.includes(name)) {\n option.hideHelp();\n }\n this._command.addOption(option);\n }\n }\n }\n\n private _addAction(getExecutor: NonNullable<CloudpackCommandParams<TOptions, TArguments>['getExecutor']>): void {\n const command = this._command;\n // The action function receives parsed options as its first parameter, but we ignore those\n // because they only contain options *specific to this command*, not shared options like `debug`.\n command.action(async () => {\n // Commander has support for custom parsers that parse arguments.\n // Use processedArgs instead of args to get the parsed arguments.\n const processedArgs = command.processedArgs as string[];\n\n // Get the shared options too, not just the ones for this command.\n // (In `cloudpackCommand`, we added the shared options to each command object so that they show up\n // in help, but commander still seems to respect options only at the first command where they're\n // encountered, which for shared options will always be the program command.)\n const options = command.optsWithGlobals<TOptions & SharedOptions>();\n\n // Usually `command` will be a sub-command (e.g. \"bundle\"), but it could also be a sub-sub-command\n // (e.g. \"cache clean\").\n const verb = command.parent?.parent ? `${command.parent.name()} ${command.name()}` : command.name();\n\n // Dynamically import the execute function\n const { execute } = await getExecutor();\n if (typeof execute !== 'function') {\n // throw instead of exiting politely, since this is a major developer error\n throw new Error(`No execute function was exported from the command module for ${verb}.`);\n }\n\n const commandExecutor = new CommandExecutor<TOptions & SharedOptions>({\n args: processedArgs,\n options,\n execute,\n programOptions: this._programOptions,\n verb,\n discoverAppPaths: this._discoverAppPaths,\n });\n await commandExecutor.execute();\n });\n }\n}\n\nclass CloudpackHelp extends Help {\n visibleOptions(cmd: Command): Option[] {\n const options = super.visibleOptions(cmd);\n\n if (cmd.name() !== 'cloudpack') {\n // Remove --version from help except at the top level (it's not very useful)\n return options.filter((option) => option.name() !== 'version');\n }\n\n return options;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CloudpackCommand.js","sourceRoot":"","sources":["../../src/utilities/CloudpackCommand.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAqE,MAAM,WAAW,CAAC;AAIrH,OAAO,EAAE,eAAe,EAA8B,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AA2DjD;;;;;;;GAOG;AACH,MAAM,OAAO,gBAAgB;IACnB,QAAQ,CAAU;IAClB,eAAe,CAAiB;IAChC,iBAAiB,CAAmC;IAE5D;;;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,6EAA6E;YAC7E,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,EAA4B,CAAC;YAEpE,kGAAkG;YAClG,wBAAwB;YACxB,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;YAEpG,0CAA0C;YAC1C,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,WAAW,EAAE,CAAC;YACxC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;gBAClC,2EAA2E;gBAC3E,MAAM,IAAI,KAAK,CAAC,gEAAgE,IAAI,GAAG,CAAC,CAAC;YAC3F,CAAC;YAED,MAAM,eAAe,GAAG,IAAI,eAAe,CAA2B;gBACpE,IAAI,EAAE,aAAa;gBACnB,OAAO;gBACP,OAAO;gBACP,cAAc,EAAE,IAAI,CAAC,eAAe;gBACpC,IAAI;gBACJ,gBAAgB,EAAE,IAAI,CAAC,iBAAiB;aACzC,CAAC,CAAC;YACH,MAAM,eAAe,CAAC,OAAO,EAAE,CAAC;QAClC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,aAAc,SAAQ,IAAI;IAC9B,cAAc,CAAC,GAAY;QACzB,MAAM,OAAO,GAAG,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QAE1C,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,WAAW,EAAE,CAAC;YAC/B,4EAA4E;YAC5E,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS,CAAC,CAAC;QACjE,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { Command, Help, Option, type AddHelpTextPosition, type Argument, type OutputConfiguration } from 'commander';\nimport type { CommandActionModule } from '../types/CommandAction.js';\nimport type { ProgramOptions } from '../types/ProgramOptions.js';\nimport type { SharedOptions } from '../types/SharedOptions.js';\nimport { CommandExecutor, type CommandExecutorParams } from './CommandExecutor.js';\nimport { environmentInfo } from '@ms-cloudpack/environment';\nimport { parseFeature } from './parseFeature.js';\nimport type { AppPathDiscoveryMode } from '../types/AppPathDiscoveryMode.js';\n\n/**\n * Parameters for creating a command.\n * `TOptions` should be the command-specific options (if any), e.g. `StartOptions`.\n */\ninterface CloudpackCommandParams<TOptions extends object, TArguments extends object>\n extends Pick<CommandExecutorParams, 'discoverAppPaths'> {\n /** Command name */\n name: string;\n\n /** Command description */\n description: string;\n\n /**\n * Options specific to this command. The record ensures that all options are available in the CLI.\n * Allow multiple options for the same key since commander supports it with negatable options.\n */\n options?: Record<keyof TOptions, Option | Option[]>; //\n\n /** Arguments specific to this command. Key order determines the arg order. */\n args?: Record<keyof TArguments, Argument>;\n\n /**\n * Function returning an async import of the command's `src/commands/<name>/execute.ts` module.\n * Importing only on demand makes Cloudpack start up faster since it doesn't have to parse\n * every command's dependencies (many of which may be unrelated to the command being run).\n *\n * This can be undefined for a command that only has sub-commands.\n */\n getExecutor?: () => Promise<CommandActionModule<TOptions>>;\n\n /** Usage message override */\n usage?: string;\n\n /** Alternative name for the command */\n alias?: string;\n\n /** Extra text to be displayed with the built-in help. */\n addHelpText?: {\n /**\n * `'before'` or `'after'` to affect just this command.\n * `'beforeAll'` or `'afterAll'` to affect this command and all its subcommands.\n */\n position: AddHelpTextPosition;\n text: string;\n };\n\n /** Output options override (mainly for testing) */\n outputOptions?: OutputConfiguration;\n\n /**\n * The shared options are relevant for most commands, but this allows omitting them from help\n * where they're not relevant. `true` hides all shared options, or an array hides specific ones.\n */\n hideSharedOptions?: Array<keyof SharedOptions> | true;\n}\n\n/**\n * This wraps the `Command` class from [`commander`](https://www.npmjs.com/package/commander) with\n * Cloudpack-specific functionality and simpler APIs.\n *\n * Similar to the pattern from `commander`, this class represents both the program and its sub-commands.\n * - The top-level \"program\" command should be created with `new CloudpackCommand()`.\n * - Sub-commands should be created with the `.addSubCommand` method on the parent.\n */\nexport class CloudpackCommand<TOptions extends object, TArguments extends object> {\n private _command: Command;\n private _programOptions: ProgramOptions;\n private _discoverAppPaths: AppPathDiscoveryMode | undefined;\n\n /**\n * This should only be used directly (outside this class) to create the top-level `program` command.\n * To add sub-commands, use `.addSubCommand` instead.\n */\n constructor(\n // The extra options here shouldn't be exposed to the `createSubCommand` API\n params: CloudpackCommandParams<TOptions, TArguments> & {\n programOptions: ProgramOptions;\n /** This must be undefined for the top-level program command */\n parent?: Command;\n },\n ) {\n this._programOptions = params.programOptions;\n this._discoverAppPaths = params.discoverAppPaths;\n\n const command = params.parent?.command(params.name) || new Command(params.name);\n this._command = command;\n\n command.version(params.programOptions.version);\n command.description(params.description);\n command.allowExcessArguments(false);\n command.createHelp = () => new CloudpackHelp();\n\n params.usage && command.usage(params.usage);\n params.alias && command.alias(params.alias);\n params.addHelpText && command.addHelpText(params.addHelpText.position, params.addHelpText.text);\n params.outputOptions && command.configureOutput(params.outputOptions);\n params.getExecutor && this._addAction(params.getExecutor);\n\n if (params.args) {\n this._addArguemnts<TArguments>(params.args);\n }\n\n if (params.options) {\n // Add the command-specific options first so they show up first in help\n this._addOptions<TOptions>(params.options);\n }\n\n // Add shared options. These must be manually added to the program command and each sub-command\n // because commander doesn't natively support inheriting options.\n this._addOptions<SharedOptions>(\n {\n verbose: new Option('-v, --verbose', 'Show additional details about the running tasks.'),\n debug: new Option('-d, --debug', 'Show debug information (superset of --verbose).').conflicts('verbose'),\n quiet: new Option('-q, --quiet', 'Disable non-essential logging.').conflicts('verbose').conflicts('debug'),\n color:\n // In the parsed options, this will be a boolean `color` with default value true (except in tests and CI)\n new Option('-n, --no-color', 'Disable colors in the output.').default(\n !environmentInfo.isJest && !environmentInfo.isLage && !environmentInfo.isCI,\n ),\n features: new Option('--features <featureNames...>', 'Enable experimental features.').argParser(parseFeature),\n cachePath: new Option(\n '--cache-path <path>',\n 'Custom cache folder. To change the default, run `cloudpack config set cachePath <path>`.',\n ),\n },\n params.hideSharedOptions,\n );\n }\n\n /** Create a child command. */\n public addSubCommand<TChildOptions extends object, TChildArguments extends object = never>(\n params: CloudpackCommandParams<TChildOptions, TChildArguments>,\n ): CloudpackCommand<TChildOptions, TChildArguments> {\n return new CloudpackCommand<TChildOptions, TChildArguments>({\n ...params,\n programOptions: this._programOptions,\n parent: this._command,\n });\n }\n\n /** Run the program (only works on the top-level program command). */\n public async run(): Promise<void> {\n if (this._command.parent) {\n throw new Error('Only the top-level program command can be run directly.');\n }\n\n await this._command.parseAsync(this._programOptions.argv);\n if (this._command.args.length === 0) {\n this._command.help();\n }\n }\n\n /** Add arguments. The generic enforces that argument objects are included for all keys of a type. */\n private _addArguemnts<TAddArguments extends object>(args: Record<keyof TAddArguments, Argument>): void {\n for (const argument of Object.values(args)) {\n this._command.addArgument(argument as Argument);\n }\n }\n\n /** Add options. The generic enforces that option objects are included for all keys of a type. */\n private _addOptions<TAddOptions extends object>(\n options: Record<keyof TAddOptions, Option | Option[]>,\n hideOptions?: Array<keyof TAddOptions> | true,\n ): void {\n for (const [name, optionOrOptions] of Object.entries(options) as [keyof TAddOptions, Option | Option[]][]) {\n const optionArray = Array.isArray(optionOrOptions) ? optionOrOptions : [optionOrOptions];\n for (const option of optionArray) {\n if (hideOptions === true || hideOptions?.includes(name)) {\n option.hideHelp();\n }\n this._command.addOption(option);\n }\n }\n }\n\n private _addAction(getExecutor: NonNullable<CloudpackCommandParams<TOptions, TArguments>['getExecutor']>): void {\n const command = this._command;\n // The action function receives parsed options as its first parameter, but we ignore those\n // because they only contain options *specific to this command*, not shared options like `debug`.\n command.action(async () => {\n // Commander has support for custom parsers that parse arguments.\n // Use processedArgs instead of args to get the parsed arguments.\n const processedArgs = command.processedArgs as string[];\n\n // Get the shared options too, not just the ones for this command.\n // (In `cloudpackCommand`, we added the shared options to each command object so that they show up\n // in help, but commander still seems to respect options only at the first command where they're\n // encountered, which for shared options will always be the program command.)\n const options = command.optsWithGlobals<TOptions & SharedOptions>();\n\n // Usually `command` will be a sub-command (e.g. \"bundle\"), but it could also be a sub-sub-command\n // (e.g. \"cache clean\").\n const verb = command.parent?.parent ? `${command.parent.name()} ${command.name()}` : command.name();\n\n // Dynamically import the execute function\n const { execute } = await getExecutor();\n if (typeof execute !== 'function') {\n // throw instead of exiting politely, since this is a major developer error\n throw new Error(`No execute function was exported from the command module for ${verb}.`);\n }\n\n const commandExecutor = new CommandExecutor<TOptions & SharedOptions>({\n args: processedArgs,\n options,\n execute,\n programOptions: this._programOptions,\n verb,\n discoverAppPaths: this._discoverAppPaths,\n });\n await commandExecutor.execute();\n });\n }\n}\n\nclass CloudpackHelp extends Help {\n visibleOptions(cmd: Command): Option[] {\n const options = super.visibleOptions(cmd);\n\n if (cmd.name() !== 'cloudpack') {\n // Remove --version from help except at the top level (it's not very useful)\n return options.filter((option) => option.name() !== 'version');\n }\n\n return options;\n }\n}\n"]}
|
|
@@ -15,6 +15,20 @@ import { TaskRunner } from '@ms-cloudpack/api-server';
|
|
|
15
15
|
*/
|
|
16
16
|
// 'app' is an optional reused option
|
|
17
17
|
export class CommandExecutor {
|
|
18
|
+
_options;
|
|
19
|
+
_execute;
|
|
20
|
+
_programOptions;
|
|
21
|
+
_verb;
|
|
22
|
+
_discoverAppPaths;
|
|
23
|
+
_reporter;
|
|
24
|
+
_autoDisposableList;
|
|
25
|
+
_hasCalledExit = false;
|
|
26
|
+
_args;
|
|
27
|
+
_sigintCount = 0;
|
|
28
|
+
_onInterrupt;
|
|
29
|
+
_getMessageOnInterrupt;
|
|
30
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- options type isn't used
|
|
31
|
+
static _activeInstances = new Set();
|
|
18
32
|
static async exitAll(params) {
|
|
19
33
|
// There should only be one instance at a time, but we assume multiple instances for safety.
|
|
20
34
|
for (const instance of CommandExecutor._activeInstances) {
|
|
@@ -24,21 +38,6 @@ export class CommandExecutor {
|
|
|
24
38
|
CommandExecutor._activeInstances = new Set();
|
|
25
39
|
}
|
|
26
40
|
constructor(params) {
|
|
27
|
-
this._hasCalledExit = false;
|
|
28
|
-
this._sigintCount = 0;
|
|
29
|
-
this._sigintHandler = () => {
|
|
30
|
-
this._sigintCount++;
|
|
31
|
-
if (this._sigintCount > 1) {
|
|
32
|
-
console.debug('Forcing exit');
|
|
33
|
-
// We are forcing the process to exit.
|
|
34
|
-
// No clean-up is needed because user pressed Ctrl+C twice.
|
|
35
|
-
// eslint-disable-next-line no-restricted-properties -- top-level cleanup
|
|
36
|
-
process.exit(1);
|
|
37
|
-
}
|
|
38
|
-
this._onInterrupt?.();
|
|
39
|
-
// We are trying to exit gracefully.
|
|
40
|
-
void this._exit({ isInterrupted: true, message: '' });
|
|
41
|
-
};
|
|
42
41
|
this._args = params.args;
|
|
43
42
|
this._options = params.options;
|
|
44
43
|
this._execute = params.execute;
|
|
@@ -283,6 +282,19 @@ export class CommandExecutor {
|
|
|
283
282
|
});
|
|
284
283
|
return telemetryClient;
|
|
285
284
|
}
|
|
285
|
+
_sigintHandler = () => {
|
|
286
|
+
this._sigintCount++;
|
|
287
|
+
if (this._sigintCount > 1) {
|
|
288
|
+
console.debug('Forcing exit');
|
|
289
|
+
// We are forcing the process to exit.
|
|
290
|
+
// No clean-up is needed because user pressed Ctrl+C twice.
|
|
291
|
+
// eslint-disable-next-line no-restricted-properties -- top-level cleanup
|
|
292
|
+
process.exit(1);
|
|
293
|
+
}
|
|
294
|
+
this._onInterrupt?.();
|
|
295
|
+
// We are trying to exit gracefully.
|
|
296
|
+
void this._exit({ isInterrupted: true, message: '' });
|
|
297
|
+
};
|
|
286
298
|
/**
|
|
287
299
|
* Exit function called with the result returned by the command's execute function,
|
|
288
300
|
* or manually via `CommandExecutor.exitAll()` in tests.
|
|
@@ -316,6 +328,4 @@ export class CommandExecutor {
|
|
|
316
328
|
process.exit(exitCode);
|
|
317
329
|
}
|
|
318
330
|
}
|
|
319
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- options type isn't used
|
|
320
|
-
CommandExecutor._activeInstances = new Set();
|
|
321
331
|
//# sourceMappingURL=CommandExecutor.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CommandExecutor.js","sourceRoot":"","sources":["../../src/utilities/CommandExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAA0B,MAAM,sBAAsB,CAAC;AAE1E,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EACf,GAAG,EACH,oBAAoB,EACpB,MAAM,GACP,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,yBAAyB,CAAC;AACtF,OAAO,IAAI,MAAM,MAAM,CAAC;AAIxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAGvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AA6BtD;;GAEG;AACH,qCAAqC;AACrC,MAAM,OAAO,eAAe;IAgBnB,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAyB;QACnD,4FAA4F;QAC5F,KAAK,MAAM,QAAQ,IAAI,eAAe,CAAC,gBAAgB,EAAE,CAAC;YACxD,MAAM,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC7B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,QAAQ,C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C,OAAO;gBAC3C,QAAQ,EAAE,QAAQ,KAAK,CAAC;aACzB,CAAC,CAAC;QACL,CAAC;QAED,eAAe,CAAC,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC9C,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAE3C,yEAAyE;QACzE,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;;AAvVD,yFAAyF;AAC1E,gCAAgB,GAAG,IAAI,GAAG,EAAwB,AAAlC,CAAmC","sourcesContent":["import { readConfig, type ReadConfigOptions } from '@ms-cloudpack/config';\nimport type { CloudpackConfig, PackageJson } from '@ms-cloudpack/common-types';\nimport { readJson } from '@ms-cloudpack/json-utilities';\nimport {\n TaskReporter,\n bold,\n debugLoggingConfig,\n defaultLoggingConfig,\n noLoggingConfig,\n red,\n verboseLoggingConfig,\n yellow,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient, type TelemetryClient } from '@ms-cloudpack/telemetry';\nimport path from 'path';\nimport type { CommandAction, CommandExitParams, AppCommandContext } from '../types/CommandAction.js';\nimport type { ProgramOptions } from '../types/ProgramOptions.js';\nimport type { SharedOptions } from '../types/SharedOptions.js';\nimport { AutoDisposableList } from './AutoDisposableList.js';\nimport { getVersion } from '@ms-cloudpack/package-utilities';\nimport { environmentInfo } from '@ms-cloudpack/environment';\nimport { getCliStartTime } from './getCliStartTime.js';\nimport type { ReusedOptions } from '../types/ReusedOptions.js';\nimport type { AppPathDiscoveryMode } from '../types/AppPathDiscoveryMode.js';\nimport { discoverRemoteAppPaths } from './discoverRemoteAppPaths.js';\nimport { discoverLocalAppPaths } from './discoverLocalAppPaths.js';\nimport { TaskRunner } from '@ms-cloudpack/api-server';\n\nexport type BaseCommandExecutorOptions = SharedOptions & Pick<ReusedOptions, 'app'>;\n\nexport interface CommandExecutorParams<TOptions extends BaseCommandExecutorOptions = BaseCommandExecutorOptions> {\n /** Command-specific arguments */\n args: string[];\n\n /** Command-specific and shared options. */\n options: TOptions;\n\n /** Function to execute the command. */\n execute: CommandAction<TOptions>;\n\n /** Shared program-level configuration. */\n programOptions: ProgramOptions;\n\n /** Verb being run, e.g. `bundle` or `cache clean`. */\n verb: string;\n\n /**\n * By default, the command will run against `cwd` (usually `process.cwd()`).\n * If this option is set, attempt to discover app path(s) instead.\n * (`cwd` will still be preferred if it has a `cloudpack.config.json`.)\n * See {@link AppPathDiscoveryMode} for details.\n */\n discoverAppPaths?: AppPathDiscoveryMode;\n}\n\n/**\n * This class manages orchestration and shared state while executing a command.\n */\n// 'app' is an optional reused option\nexport class CommandExecutor<TOptions extends BaseCommandExecutorOptions> {\n private _options: TOptions;\n private _execute: CommandAction<TOptions>;\n private _programOptions: ProgramOptions;\n private _verb: string;\n private _discoverAppPaths: AppPathDiscoveryMode | undefined;\n private _reporter: TaskReporter;\n private _autoDisposableList: AutoDisposableList;\n private _hasCalledExit = false;\n private _args: string[];\n private _sigintCount = 0;\n private _onInterrupt?: () => void;\n private _getMessageOnInterrupt?: () => string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- options type isn't used\n private static _activeInstances = new Set<CommandExecutor<any>>();\n\n public static async exitAll(params: CommandExitParams): Promise<void> {\n // There should only be one instance at a time, but we assume multiple instances for safety.\n for (const instance of CommandExecutor._activeInstances) {\n await instance._exit(params);\n process.off('SIGINT', instance._sigintHandler);\n }\n CommandExecutor._activeInstances = new Set();\n }\n\n constructor(params: CommandExecutorParams<TOptions>) {\n this._args = params.args;\n this._options = params.options;\n this._execute = params.execute;\n this._programOptions = params.programOptions;\n this._verb = params.verb;\n this._discoverAppPaths = params.discoverAppPaths;\n this._reporter = new TaskReporter();\n this._autoDisposableList = new AutoDisposableList();\n }\n\n /** Run the command. */\n // This has to be a separate method because constructors can't be async.\n public async execute(): Promise<void> {\n CommandExecutor._activeInstances.add(this);\n try {\n // Handle SIGINT (Ctrl+C) gracefully.\n if (!environmentInfo.isJest) {\n process.on('SIGINT', this._sigintHandler);\n }\n\n const contexts = await this._initializeContexts();\n\n if (!Array.isArray(contexts)) {\n await this._exit(contexts);\n return;\n }\n\n const spanName = `${this._verb.toUpperCase().replace(/ /g, '_')}_EXECUTE`;\n const results: CommandExitParams[] = [];\n\n for (const context of contexts) {\n // Call the execute function which is the real command logic\n // (ie: real init command logic, real start command logic, etc.)\n const result = await context.telemetryClient.tracer.startActiveSpan(spanName, async (span) => {\n this._onInterrupt = () => {\n span.setAttribute('isInterrupted', true);\n span.end();\n };\n\n return this._execute({\n ...context,\n span,\n isMultiApp: contexts.length > 1,\n args: this._args,\n options: this._options,\n autoDispose: (disposable) => this._autoDisposableList.add(disposable),\n setInterruptMessageHandler: (getMessage) => {\n this._getMessageOnInterrupt = getMessage;\n },\n });\n });\n if (result?.isInterrupted) {\n return await this._exit(result);\n }\n if (result) {\n results.push(result);\n } else if ((result as unknown) !== null) {\n // If the command returned null, this means it should keep running (e.g. start).\n // We disallow returning undefined to avoid accidents.\n throw new Error('Command executor must return exit options or null');\n }\n this._onInterrupt = undefined;\n }\n\n if (results.length) {\n // If one or more apps returned a result, exit.\n await this._exit({\n message: results.map((r) => r.message).join('\\n'),\n hasErrors: results.some((r) => r.hasErrors),\n // If any app returned a non-zero exit code, use that.\n exitCode: results.find(({ exitCode }) => !!exitCode)?.exitCode,\n });\n }\n } catch (error) {\n // If an error occurs, exit the process with a non-zero exit code.\n await this._exit({\n hasErrors: true,\n message: (error as Error).stack || (error as Error).message || String(error),\n });\n }\n }\n\n /**\n * Determine the app paths and initialize the context for each app.\n * @returns Context(s), or an exit options object if there was an error. (might also throw on error)\n */\n private async _initializeContexts(): Promise<AppCommandContext[] | CommandExitParams> {\n let appPaths: string[];\n\n if (this._discoverAppPaths) {\n // Search for cloudpack configs to determine the app path(s)\n const appPathsResult =\n this._discoverAppPaths === 'remote'\n ? await discoverRemoteAppPaths({\n options: {\n login: (this._options as unknown as Pick<ReusedOptions, 'login'>).login,\n cachePath: this._options.cachePath,\n desiredApp: this._options.app,\n },\n context: {\n reporter: this._reporter,\n },\n })\n : await discoverLocalAppPaths({\n cwd: this._programOptions.cwd,\n discover: this._discoverAppPaths,\n desiredApp: this._options.app,\n });\n if (!Array.isArray(appPathsResult)) {\n // This means there was an error (or the user cancelled) while getting app paths.\n return appPathsResult;\n }\n appPaths = appPathsResult;\n } else {\n // Just use the cwd\n appPaths = [this._programOptions.cwd];\n }\n\n const configOptions = this._getConfigOptionsFromCliOptions();\n\n // The task runner is shared between all apps so that task results can potentially be reused.\n const taskRunner = new TaskRunner();\n\n const contexts: AppCommandContext[] = [];\n\n const helpMessages = new Set<string>();\n\n const configs: Record<string, CloudpackConfig> = {};\n for (const appPath of appPaths) {\n let config: CloudpackConfig;\n\n try {\n config = await readConfig(appPath, {\n ...configOptions,\n extraFeatures: this._options.features,\n });\n } catch (err) {\n await this._exit({\n message: `Invalid cloudpack config: ${(err as Error).message || err}`,\n hasErrors: true,\n });\n // eslint-disable-next-line no-restricted-properties -- this will never be reached, but TypeScript doesn't know that\n process.exit(1);\n }\n if (config.helpMessage) {\n helpMessages.add(config.helpMessage);\n }\n\n configs[appPath] = config;\n }\n\n // Set reporter options and print the product info header\n this._reporter.setOptions({\n productName: 'Cloudpack',\n version: this._programOptions.version,\n description: () => `Running \"${bold(this._programOptions.argv.slice(2).join(' '))}\"`,\n helpMessage: [...helpMessages].join('\\n'),\n plainTextMode: !this._options.color,\n ...(this._options.debug\n ? debugLoggingConfig\n : this._options.verbose\n ? verboseLoggingConfig\n : this._options.quiet\n ? noLoggingConfig\n : defaultLoggingConfig),\n });\n\n for (const appPath of appPaths) {\n const config = configs[appPath];\n const definition = await readJson<PackageJson>(path.join(appPath, 'package.json'));\n const { name = path.basename(appPath) } = definition || {};\n\n const telemetryClient = await this._initTelemetry(name, config);\n // Dispose the telemetry client when the app is closing\n this._autoDisposableList.add({\n dispose: () => telemetryClient.shutdown(),\n });\n\n contexts.push({\n appPath,\n cachePath: this._options.cachePath,\n config,\n reporter: this._reporter,\n telemetryClient,\n taskRunner,\n });\n }\n\n return contexts;\n }\n\n /** Translate certain CLI options into options for `readConfig()`. */\n private _getConfigOptionsFromCliOptions(): ReadConfigOptions {\n // These options don't exist for all commands, but that's fine.\n const options = this._options as Partial<ReusedOptions & SharedOptions>;\n return {\n mode: options.mode,\n logBundleInfo: options.logBundleInfo,\n // Handle --bundler by passing it as a universal package override, which will be appended\n // to any user-provided packageSettings so that it takes precedence.\n extraPackageSettings: options.bundler ? [{ match: '*', bundler: options.bundler }] : undefined,\n };\n }\n\n private async _initTelemetry(appName: string | undefined, config: CloudpackConfig): Promise<TelemetryClient> {\n // Mark the start time for telemetry.\n const startTime = performance.now();\n\n const programOptions = this._programOptions;\n const options = this._options;\n\n const connectionString =\n programOptions.disableTelemetry || environmentInfo.isJest\n ? undefined\n : config.telemetry?.connectionString || environmentInfo.cloudpack.telemetryConnectionString;\n\n const logLevel = options.verbose ? 'VERBOSE' : options.debug ? 'DEBUG' : undefined;\n if (!options.debug) {\n this._reporter.ignoreLogMessage('ApplicationInsights:');\n }\n\n const telemetryClient = await createTelemetryClient({\n productVersion: getVersion(import.meta.url),\n connectionString,\n logLevel,\n serviceNamespace: 'cloudpack',\n serviceName: 'cli',\n });\n\n void telemetryClient.tracer.startActiveSpan('CLI_ENTRY', { startTime: getCliStartTime() }, () => {\n // Retrieve the current telemetry context\n const activeContext = telemetryClient.context.active();\n\n /**\n * Sets the current context as the root context. This ensures that all spans created during this CLI execution\n * will be children of this root span, even though the root span is closed immediately. This helps group all\n * spans under a single root span for better traceability.\n *\n * Typically, the root span should remain open until the CLI exits. However, in environments like Codespaces,\n * the CLI might run indefinitely, which could leave the root span open indefinitely.\n *\n * To prevent this, the root span is closed immediately after it is set as the root context.\n */\n telemetryClient.setRootContext(activeContext);\n });\n\n await telemetryClient.tracer.startActiveSpan('INIT_TELEMETRY', { startTime }, (span) => {\n const enabledFeatureNames = Object.entries(config.features || {})\n .filter(([, value]) => value)\n .map(([key]) => key);\n\n if (enabledFeatureNames.length) {\n console.log(`Enabled features: ${enabledFeatureNames.map((f) => yellow(f)).join(', ')}`);\n }\n\n const telemetryAttributes = {\n verb: this._verb,\n arguments: programOptions.argv.slice(3).join(' '),\n environment: environmentInfo.isCI ? 'ci' : environmentInfo.isCodespaces ? 'codespaces' : 'local',\n appName: appName || '<unknown>',\n mode: config.mode,\n features: enabledFeatureNames,\n externalCorrelationId: environmentInfo.cloudpack.telemetryExternalCorrelationId,\n // Azure DevOps build attributes\n ...environmentInfo.ado,\n };\n\n for (const [key, value] of Object.entries(telemetryAttributes)) {\n if (value) {\n span.setAttribute(key, value);\n }\n }\n });\n\n return telemetryClient;\n }\n\n protected _sigintHandler = (): void => {\n this._sigintCount++;\n\n if (this._sigintCount > 1) {\n console.debug('Forcing exit');\n\n // We are forcing the process to exit.\n // No clean-up is needed because user pressed Ctrl+C twice.\n // eslint-disable-next-line no-restricted-properties -- top-level cleanup\n process.exit(1);\n }\n\n this._onInterrupt?.();\n\n // We are trying to exit gracefully.\n void this._exit({ isInterrupted: true, message: '' });\n };\n\n /**\n * Exit function called with the result returned by the command's execute function,\n * or manually via `CommandExecutor.exitAll()` in tests.\n */\n protected async _exit(params: CommandExitParams): Promise<never> {\n const { hasErrors = this._reporter.hasErrors(), exitCode = hasErrors ? 1 : 0 } = params;\n const message = params.isInterrupted ? this._getMessageOnInterrupt?.() || 'Interrupted by user' : params.message;\n\n if (this._hasCalledExit) {\n // Skip most of the operations if exit() was called multiple times.\n // But only use the error message if not in a test, due to the way we're mocking process.exit.\n if (!environmentInfo.isJest) {\n const prettyParams = Object.entries(params)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(', ');\n console.warn(`exit() was called multiple times. This call's options: ${prettyParams}.`);\n }\n } else {\n this._hasCalledExit = true;\n\n // Dispose all registered disposables.\n await this._autoDisposableList.dispose();\n\n // Show the summary message (this will throw if called twice).\n this._reporter.complete({\n summary: hasErrors ? red(message) : message,\n showHelp: exitCode !== 0,\n });\n }\n\n CommandExecutor._activeInstances.delete(this);\n process.off('SIGINT', this._sigintHandler);\n\n // eslint-disable-next-line no-restricted-properties -- top-level cleanup\n process.exit(exitCode);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CommandExecutor.js","sourceRoot":"","sources":["../../src/utilities/CommandExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAA0B,MAAM,sBAAsB,CAAC;AAE1E,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EACf,GAAG,EACH,oBAAoB,EACpB,MAAM,GACP,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,yBAAyB,CAAC;AACtF,OAAO,IAAI,MAAM,MAAM,CAAC;AAIxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAGvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AA6BtD;;GAEG;AACH,qCAAqC;AACrC,MAAM,OAAO,eAAe;IAClB,QAAQ,CAAW;IACnB,QAAQ,CAA0B;IAClC,eAAe,CAAiB;IAChC,KAAK,CAAS;IACd,iBAAiB,CAAmC;IACpD,SAAS,CAAe;IACxB,mBAAmB,CAAqB;IACxC,cAAc,GAAG,KAAK,CAAC;IACvB,KAAK,CAAW;IAChB,YAAY,GAAG,CAAC,CAAC;IACjB,YAAY,CAAc;IAC1B,sBAAsB,CAAg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Ac,GAAG,IAAI,CAAC;YAE3B,sCAAsC;YACtC,MAAM,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,CAAC;YAEzC,8DAA8D;YAC9D,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;gBACtB,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO;gBAC3C,QAAQ,EAAE,QAAQ,KAAK,CAAC;aACzB,CAAC,CAAC;QACL,CAAC;QAED,eAAe,CAAC,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC9C,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAE3C,yEAAyE;QACzE,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC","sourcesContent":["import { readConfig, type ReadConfigOptions } from '@ms-cloudpack/config';\nimport type { CloudpackConfig, PackageJson } from '@ms-cloudpack/common-types';\nimport { readJson } from '@ms-cloudpack/json-utilities';\nimport {\n TaskReporter,\n bold,\n debugLoggingConfig,\n defaultLoggingConfig,\n noLoggingConfig,\n red,\n verboseLoggingConfig,\n yellow,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient, type TelemetryClient } from '@ms-cloudpack/telemetry';\nimport path from 'path';\nimport type { CommandAction, CommandExitParams, AppCommandContext } from '../types/CommandAction.js';\nimport type { ProgramOptions } from '../types/ProgramOptions.js';\nimport type { SharedOptions } from '../types/SharedOptions.js';\nimport { AutoDisposableList } from './AutoDisposableList.js';\nimport { getVersion } from '@ms-cloudpack/package-utilities';\nimport { environmentInfo } from '@ms-cloudpack/environment';\nimport { getCliStartTime } from './getCliStartTime.js';\nimport type { ReusedOptions } from '../types/ReusedOptions.js';\nimport type { AppPathDiscoveryMode } from '../types/AppPathDiscoveryMode.js';\nimport { discoverRemoteAppPaths } from './discoverRemoteAppPaths.js';\nimport { discoverLocalAppPaths } from './discoverLocalAppPaths.js';\nimport { TaskRunner } from '@ms-cloudpack/api-server';\n\nexport type BaseCommandExecutorOptions = SharedOptions & Pick<ReusedOptions, 'app'>;\n\nexport interface CommandExecutorParams<TOptions extends BaseCommandExecutorOptions = BaseCommandExecutorOptions> {\n /** Command-specific arguments */\n args: string[];\n\n /** Command-specific and shared options. */\n options: TOptions;\n\n /** Function to execute the command. */\n execute: CommandAction<TOptions>;\n\n /** Shared program-level configuration. */\n programOptions: ProgramOptions;\n\n /** Verb being run, e.g. `bundle` or `cache clean`. */\n verb: string;\n\n /**\n * By default, the command will run against `cwd` (usually `process.cwd()`).\n * If this option is set, attempt to discover app path(s) instead.\n * (`cwd` will still be preferred if it has a `cloudpack.config.json`.)\n * See {@link AppPathDiscoveryMode} for details.\n */\n discoverAppPaths?: AppPathDiscoveryMode;\n}\n\n/**\n * This class manages orchestration and shared state while executing a command.\n */\n// 'app' is an optional reused option\nexport class CommandExecutor<TOptions extends BaseCommandExecutorOptions> {\n private _options: TOptions;\n private _execute: CommandAction<TOptions>;\n private _programOptions: ProgramOptions;\n private _verb: string;\n private _discoverAppPaths: AppPathDiscoveryMode | undefined;\n private _reporter: TaskReporter;\n private _autoDisposableList: AutoDisposableList;\n private _hasCalledExit = false;\n private _args: string[];\n private _sigintCount = 0;\n private _onInterrupt?: () => void;\n private _getMessageOnInterrupt?: () => string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- options type isn't used\n private static _activeInstances = new Set<CommandExecutor<any>>();\n\n public static async exitAll(params: CommandExitParams): Promise<void> {\n // There should only be one instance at a time, but we assume multiple instances for safety.\n for (const instance of CommandExecutor._activeInstances) {\n await instance._exit(params);\n process.off('SIGINT', instance._sigintHandler);\n }\n CommandExecutor._activeInstances = new Set();\n }\n\n constructor(params: CommandExecutorParams<TOptions>) {\n this._args = params.args;\n this._options = params.options;\n this._execute = params.execute;\n this._programOptions = params.programOptions;\n this._verb = params.verb;\n this._discoverAppPaths = params.discoverAppPaths;\n this._reporter = new TaskReporter();\n this._autoDisposableList = new AutoDisposableList();\n }\n\n /** Run the command. */\n // This has to be a separate method because constructors can't be async.\n public async execute(): Promise<void> {\n CommandExecutor._activeInstances.add(this);\n try {\n // Handle SIGINT (Ctrl+C) gracefully.\n if (!environmentInfo.isJest) {\n process.on('SIGINT', this._sigintHandler);\n }\n\n const contexts = await this._initializeContexts();\n\n if (!Array.isArray(contexts)) {\n await this._exit(contexts);\n return;\n }\n\n const spanName = `${this._verb.toUpperCase().replace(/ /g, '_')}_EXECUTE`;\n const results: CommandExitParams[] = [];\n\n for (const context of contexts) {\n // Call the execute function which is the real command logic\n // (ie: real init command logic, real start command logic, etc.)\n const result = await context.telemetryClient.tracer.startActiveSpan(spanName, async (span) => {\n this._onInterrupt = () => {\n span.setAttribute('isInterrupted', true);\n span.end();\n };\n\n return this._execute({\n ...context,\n span,\n isMultiApp: contexts.length > 1,\n args: this._args,\n options: this._options,\n autoDispose: (disposable) => this._autoDisposableList.add(disposable),\n setInterruptMessageHandler: (getMessage) => {\n this._getMessageOnInterrupt = getMessage;\n },\n });\n });\n if (result?.isInterrupted) {\n return await this._exit(result);\n }\n if (result) {\n results.push(result);\n } else if ((result as unknown) !== null) {\n // If the command returned null, this means it should keep running (e.g. start).\n // We disallow returning undefined to avoid accidents.\n throw new Error('Command executor must return exit options or null');\n }\n this._onInterrupt = undefined;\n }\n\n if (results.length) {\n // If one or more apps returned a result, exit.\n await this._exit({\n message: results.map((r) => r.message).join('\\n'),\n hasErrors: results.some((r) => r.hasErrors),\n // If any app returned a non-zero exit code, use that.\n exitCode: results.find(({ exitCode }) => !!exitCode)?.exitCode,\n });\n }\n } catch (error) {\n // If an error occurs, exit the process with a non-zero exit code.\n await this._exit({\n hasErrors: true,\n message: (error as Error).stack || (error as Error).message || String(error),\n });\n }\n }\n\n /**\n * Determine the app paths and initialize the context for each app.\n * @returns Context(s), or an exit options object if there was an error. (might also throw on error)\n */\n private async _initializeContexts(): Promise<AppCommandContext[] | CommandExitParams> {\n let appPaths: string[];\n\n if (this._discoverAppPaths) {\n // Search for cloudpack configs to determine the app path(s)\n const appPathsResult =\n this._discoverAppPaths === 'remote'\n ? await discoverRemoteAppPaths({\n options: {\n login: (this._options as unknown as Pick<ReusedOptions, 'login'>).login,\n cachePath: this._options.cachePath,\n desiredApp: this._options.app,\n },\n context: {\n reporter: this._reporter,\n },\n })\n : await discoverLocalAppPaths({\n cwd: this._programOptions.cwd,\n discover: this._discoverAppPaths,\n desiredApp: this._options.app,\n });\n if (!Array.isArray(appPathsResult)) {\n // This means there was an error (or the user cancelled) while getting app paths.\n return appPathsResult;\n }\n appPaths = appPathsResult;\n } else {\n // Just use the cwd\n appPaths = [this._programOptions.cwd];\n }\n\n const configOptions = this._getConfigOptionsFromCliOptions();\n\n // The task runner is shared between all apps so that task results can potentially be reused.\n const taskRunner = new TaskRunner();\n\n const contexts: AppCommandContext[] = [];\n\n const helpMessages = new Set<string>();\n\n const configs: Record<string, CloudpackConfig> = {};\n for (const appPath of appPaths) {\n let config: CloudpackConfig;\n\n try {\n config = await readConfig(appPath, {\n ...configOptions,\n extraFeatures: this._options.features,\n });\n } catch (err) {\n await this._exit({\n message: `Invalid cloudpack config: ${(err as Error).message || err}`,\n hasErrors: true,\n });\n // eslint-disable-next-line no-restricted-properties -- this will never be reached, but TypeScript doesn't know that\n process.exit(1);\n }\n if (config.helpMessage) {\n helpMessages.add(config.helpMessage);\n }\n\n configs[appPath] = config;\n }\n\n // Set reporter options and print the product info header\n this._reporter.setOptions({\n productName: 'Cloudpack',\n version: this._programOptions.version,\n description: () => `Running \"${bold(this._programOptions.argv.slice(2).join(' '))}\"`,\n helpMessage: [...helpMessages].join('\\n'),\n plainTextMode: !this._options.color,\n ...(this._options.debug\n ? debugLoggingConfig\n : this._options.verbose\n ? verboseLoggingConfig\n : this._options.quiet\n ? noLoggingConfig\n : defaultLoggingConfig),\n });\n\n for (const appPath of appPaths) {\n const config = configs[appPath];\n const definition = await readJson<PackageJson>(path.join(appPath, 'package.json'));\n const { name = path.basename(appPath) } = definition || {};\n\n const telemetryClient = await this._initTelemetry(name, config);\n // Dispose the telemetry client when the app is closing\n this._autoDisposableList.add({\n dispose: () => telemetryClient.shutdown(),\n });\n\n contexts.push({\n appPath,\n cachePath: this._options.cachePath,\n config,\n reporter: this._reporter,\n telemetryClient,\n taskRunner,\n });\n }\n\n return contexts;\n }\n\n /** Translate certain CLI options into options for `readConfig()`. */\n private _getConfigOptionsFromCliOptions(): ReadConfigOptions {\n // These options don't exist for all commands, but that's fine.\n const options = this._options as Partial<ReusedOptions & SharedOptions>;\n return {\n mode: options.mode,\n logBundleInfo: options.logBundleInfo,\n // Handle --bundler by passing it as a universal package override, which will be appended\n // to any user-provided packageSettings so that it takes precedence.\n extraPackageSettings: options.bundler ? [{ match: '*', bundler: options.bundler }] : undefined,\n };\n }\n\n private async _initTelemetry(appName: string | undefined, config: CloudpackConfig): Promise<TelemetryClient> {\n // Mark the start time for telemetry.\n const startTime = performance.now();\n\n const programOptions = this._programOptions;\n const options = this._options;\n\n const connectionString =\n programOptions.disableTelemetry || environmentInfo.isJest\n ? undefined\n : config.telemetry?.connectionString || environmentInfo.cloudpack.telemetryConnectionString;\n\n const logLevel = options.verbose ? 'VERBOSE' : options.debug ? 'DEBUG' : undefined;\n if (!options.debug) {\n this._reporter.ignoreLogMessage('ApplicationInsights:');\n }\n\n const telemetryClient = await createTelemetryClient({\n productVersion: getVersion(import.meta.url),\n connectionString,\n logLevel,\n serviceNamespace: 'cloudpack',\n serviceName: 'cli',\n });\n\n void telemetryClient.tracer.startActiveSpan('CLI_ENTRY', { startTime: getCliStartTime() }, () => {\n // Retrieve the current telemetry context\n const activeContext = telemetryClient.context.active();\n\n /**\n * Sets the current context as the root context. This ensures that all spans created during this CLI execution\n * will be children of this root span, even though the root span is closed immediately. This helps group all\n * spans under a single root span for better traceability.\n *\n * Typically, the root span should remain open until the CLI exits. However, in environments like Codespaces,\n * the CLI might run indefinitely, which could leave the root span open indefinitely.\n *\n * To prevent this, the root span is closed immediately after it is set as the root context.\n */\n telemetryClient.setRootContext(activeContext);\n });\n\n await telemetryClient.tracer.startActiveSpan('INIT_TELEMETRY', { startTime }, (span) => {\n const enabledFeatureNames = Object.entries(config.features || {})\n .filter(([, value]) => value)\n .map(([key]) => key);\n\n if (enabledFeatureNames.length) {\n console.log(`Enabled features: ${enabledFeatureNames.map((f) => yellow(f)).join(', ')}`);\n }\n\n const telemetryAttributes = {\n verb: this._verb,\n arguments: programOptions.argv.slice(3).join(' '),\n environment: environmentInfo.isCI ? 'ci' : environmentInfo.isCodespaces ? 'codespaces' : 'local',\n appName: appName || '<unknown>',\n mode: config.mode,\n features: enabledFeatureNames,\n externalCorrelationId: environmentInfo.cloudpack.telemetryExternalCorrelationId,\n // Azure DevOps build attributes\n ...environmentInfo.ado,\n };\n\n for (const [key, value] of Object.entries(telemetryAttributes)) {\n if (value) {\n span.setAttribute(key, value);\n }\n }\n });\n\n return telemetryClient;\n }\n\n protected _sigintHandler = (): void => {\n this._sigintCount++;\n\n if (this._sigintCount > 1) {\n console.debug('Forcing exit');\n\n // We are forcing the process to exit.\n // No clean-up is needed because user pressed Ctrl+C twice.\n // eslint-disable-next-line no-restricted-properties -- top-level cleanup\n process.exit(1);\n }\n\n this._onInterrupt?.();\n\n // We are trying to exit gracefully.\n void this._exit({ isInterrupted: true, message: '' });\n };\n\n /**\n * Exit function called with the result returned by the command's execute function,\n * or manually via `CommandExecutor.exitAll()` in tests.\n */\n protected async _exit(params: CommandExitParams): Promise<never> {\n const { hasErrors = this._reporter.hasErrors(), exitCode = hasErrors ? 1 : 0 } = params;\n const message = params.isInterrupted ? this._getMessageOnInterrupt?.() || 'Interrupted by user' : params.message;\n\n if (this._hasCalledExit) {\n // Skip most of the operations if exit() was called multiple times.\n // But only use the error message if not in a test, due to the way we're mocking process.exit.\n if (!environmentInfo.isJest) {\n const prettyParams = Object.entries(params)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(', ');\n console.warn(`exit() was called multiple times. This call's options: ${prettyParams}.`);\n }\n } else {\n this._hasCalledExit = true;\n\n // Dispose all registered disposables.\n await this._autoDisposableList.dispose();\n\n // Show the summary message (this will throw if called twice).\n this._reporter.complete({\n summary: hasErrors ? red(message) : message,\n showHelp: exitCode !== 0,\n });\n }\n\n CommandExecutor._activeInstances.delete(this);\n process.off('SIGINT', this._sigintHandler);\n\n // eslint-disable-next-line no-restricted-properties -- top-level cleanup\n process.exit(exitCode);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ms-cloudpack/cli",
|
|
3
|
-
"version": "0.72.
|
|
3
|
+
"version": "0.72.63",
|
|
4
4
|
"description": "The Cloudpack command line interface - a tool for managing fast inner and outer looping in web apps.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,14 +10,14 @@
|
|
|
10
10
|
"cloudpack": "./bin/cloudpack.js"
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@ms-cloudpack/api-server": "^0.61.
|
|
14
|
-
"@ms-cloudpack/app-server": "^0.17.
|
|
15
|
-
"@ms-cloudpack/bundler": "^0.24.
|
|
13
|
+
"@ms-cloudpack/api-server": "^0.61.6",
|
|
14
|
+
"@ms-cloudpack/app-server": "^0.17.58",
|
|
15
|
+
"@ms-cloudpack/bundler": "^0.24.5",
|
|
16
16
|
"@ms-cloudpack/common-types": "^0.24.10",
|
|
17
17
|
"@ms-cloudpack/config": "^0.33.19",
|
|
18
18
|
"@ms-cloudpack/environment": "^0.1.1",
|
|
19
19
|
"@ms-cloudpack/json-utilities": "^0.1.10",
|
|
20
|
-
"@ms-cloudpack/overlay": "^0.17.
|
|
20
|
+
"@ms-cloudpack/overlay": "^0.17.139",
|
|
21
21
|
"@ms-cloudpack/package-utilities": "^12.0.0",
|
|
22
22
|
"@ms-cloudpack/path-string-parsing": "^1.2.6",
|
|
23
23
|
"@ms-cloudpack/path-utilities": "^3.0.7",
|