// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { IPCOperationRunner } from './IPCOperationRunner';
import { OperationStatus } from './OperationStatus';
import { PLUGIN_NAME as ShellOperationPluginName, formatCommand, getCustomParameterValuesByOperation, getDisplayName } from './ShellOperationRunnerPlugin';
const PLUGIN_NAME = 'IPCOperationRunnerPlugin';
/**
 * Plugin that implements compatible phases via IPC to a long-lived watch process.
 */
export class IPCOperationRunnerPlugin {
    apply(hooks) {
        // Workaround until the operation graph persists for the lifetime of the watch process
        const runnerCache = new Map();
        const operationStatesByRunner = new WeakMap();
        let currentContext;
        hooks.createOperations.tapPromise({
            name: PLUGIN_NAME,
            before: ShellOperationPluginName
        }, async (operations, context) => {
            var _a, _b;
            const { isWatch, isInitial } = context;
            if (!isWatch) {
                return operations;
            }
            currentContext = context;
            const getCustomParameterValues = getCustomParameterValuesByOperation();
            for (const operation of operations) {
                const { associatedPhase: phase, associatedProject: project, runner } = operation;
                if (runner) {
                    continue;
                }
                const { scripts } = project.packageJson;
                if (!scripts) {
                    continue;
                }
                const { name: phaseName } = phase;
                const rawScript = (_a = (!isInitial ? scripts[`${phaseName}:incremental:ipc`] : undefined)) !== null && _a !== void 0 ? _a : scripts[`${phaseName}:ipc`];
                if (!rawScript) {
                    continue;
                }
                // This is the command that will be used to identify the cache entry for this operation, to allow
                // for this operation (or downstream operations) to be restored from the build cache.
                const commandForHash = (_b = phase.shellCommand) !== null && _b !== void 0 ? _b : scripts === null || scripts === void 0 ? void 0 : scripts[phaseName];
                const { parameterValues: customParameterValues, ignoredParameterValues } = getCustomParameterValues(operation);
                const commandToRun = formatCommand(rawScript, customParameterValues);
                const operationName = getDisplayName(phase, project);
                let maybeIpcOperationRunner = runnerCache.get(operationName);
                if (!maybeIpcOperationRunner) {
                    const ipcOperationRunner = (maybeIpcOperationRunner = new IPCOperationRunner({
                        phase,
                        project,
                        name: operationName,
                        commandToRun,
                        commandForHash,
                        persist: true,
                        ignoredParameterValues,
                        requestRun: (requestor, detail) => {
                            var _a;
                            const operationState = operationStatesByRunner.get(ipcOperationRunner);
                            if (!operationState) {
                                return;
                            }
                            const status = operationState.status;
                            if (status === OperationStatus.Waiting ||
                                status === OperationStatus.Ready ||
                                status === OperationStatus.Queued) {
                                // Already pending. No-op.
                                return;
                            }
                            (_a = currentContext === null || currentContext === void 0 ? void 0 : currentContext.invalidateOperation) === null || _a === void 0 ? void 0 : _a.call(currentContext, operation, detail ? `${requestor}: ${detail}` : requestor);
                        }
                    }));
                    runnerCache.set(operationName, ipcOperationRunner);
                }
                operation.runner = maybeIpcOperationRunner;
            }
            return operations;
        });
        hooks.beforeExecuteOperations.tap(PLUGIN_NAME, (records, context) => {
            currentContext = context;
            for (const [{ runner }, result] of records) {
                if (runner instanceof IPCOperationRunner) {
                    operationStatesByRunner.set(runner, result);
                }
            }
        });
        hooks.shutdownAsync.tapPromise(PLUGIN_NAME, async () => {
            await Promise.all(Array.from(runnerCache.values(), (runner) => runner.shutdownAsync()));
        });
    }
}
//# sourceMappingURL=IPCOperationRunnerPlugin.js.map