"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initTasksRunner = initTasksRunner;
exports.runDiscreteTasks = runDiscreteTasks;
exports.runContinuousTasks = runContinuousTasks;
const configuration_1 = require("../config/configuration");
const project_graph_1 = require("../project-graph/project-graph");
const run_command_1 = require("./run-command");
const invoke_runner_terminal_output_life_cycle_1 = require("./life-cycles/invoke-runner-terminal-output-life-cycle");
const perf_hooks_1 = require("perf_hooks");
const utils_1 = require("./utils");
const dotenv_1 = require("../utils/dotenv");
const task_orchestrator_1 = require("./task-orchestrator");
const hash_task_1 = require("../hasher/hash-task");
const create_task_hasher_1 = require("../hasher/create-task-hasher");
const client_1 = require("../daemon/client/client");
async function initTasksRunner(nxArgs) {
    perf_hooks_1.performance.mark('init-local');
    (0, dotenv_1.loadRootEnvFiles)();
    const nxJson = (0, configuration_1.readNxJson)();
    if (nxArgs.verbose) {
        process.env.NX_VERBOSE_LOGGING = 'true';
    }
    const projectGraph = await (0, project_graph_1.createProjectGraphAsync)({ exitOnError: true });
    return {
        invoke: async (opts) => {
            perf_hooks_1.performance.mark('code-loading:end');
            // TODO: This polyfills the outputs if someone doesn't pass a task with outputs. Remove this in Nx 20
            opts.tasks.forEach((t) => {
                if (!t.outputs) {
                    t.outputs = (0, utils_1.getOutputs)(projectGraph.nodes, t.target, t.overrides);
                }
            });
            const lifeCycle = new invoke_runner_terminal_output_life_cycle_1.InvokeRunnerTerminalOutputLifeCycle(opts.tasks);
            const taskGraph = {
                roots: opts.tasks.map((task) => task.id),
                tasks: opts.tasks.reduce((acc, task) => {
                    acc[task.id] = task;
                    return acc;
                }, {}),
                dependencies: opts.tasks.reduce((acc, task) => {
                    acc[task.id] = [];
                    return acc;
                }, {}),
                continuousDependencies: opts.tasks.reduce((acc, task) => {
                    acc[task.id] = [];
                    return acc;
                }, {}),
            };
            const taskResults = await (0, run_command_1.invokeTasksRunner)({
                tasks: opts.tasks,
                projectGraph,
                taskGraph,
                lifeCycle,
                nxJson,
                nxArgs: { ...nxArgs, parallel: opts.parallel },
                loadDotEnvFiles: true,
                initiatingProject: null,
            });
            return {
                status: Object.values(taskResults).some((taskResult) => taskResult.status === 'failure' || taskResult.status === 'skipped')
                    ? 1
                    : 0,
                taskGraph,
                taskResults,
            };
        },
    };
}
async function createOrchestrator(tasks, projectGraph, taskGraphForHashing, nxJson) {
    (0, dotenv_1.loadRootEnvFiles)();
    // this needs to be done before we start to run the tasks
    const taskDetails = (0, hash_task_1.getTaskDetails)();
    const { runnerOptions: options } = (0, run_command_1.getRunner)({}, nxJson);
    let hasher = (0, create_task_hasher_1.createTaskHasher)(projectGraph, nxJson, options);
    const taskGraph = {
        roots: tasks.map((task) => task.id),
        tasks: tasks.reduce((acc, task) => {
            acc[task.id] = task;
            return acc;
        }, {}),
        dependencies: tasks.reduce((acc, task) => {
            acc[task.id] = [];
            return acc;
        }, {}),
        continuousDependencies: tasks.reduce((acc, task) => {
            acc[task.id] = [];
            return acc;
        }, {}),
    };
    // this is used for two reasons: to fetch all remote cache hits AND
    // to submit everything that is known in advance to Nx Cloud to run in
    // a distributed fashion
    await (0, hash_task_1.hashTasksThatDoNotDependOnOutputsOfOtherTasks)(hasher, projectGraph, taskGraphForHashing, nxJson, taskDetails);
    return new task_orchestrator_1.TaskOrchestrator(hasher, null, projectGraph, taskGraph, nxJson, { ...options, parallel: tasks.length }, false, client_1.daemonClient, undefined, taskGraphForHashing);
}
async function runDiscreteTasks(tasks, projectGraph, taskGraph, nxJson) {
    const orchestrator = await createOrchestrator(tasks, projectGraph, taskGraph, nxJson);
    return tasks.map((task) => orchestrator.applyFromCacheOrRunTask(true, task, 0));
}
async function runContinuousTasks(tasks, projectGraph, taskGraph, nxJson) {
    const orchestrator = await createOrchestrator(tasks, projectGraph, taskGraph, nxJson);
    return tasks.map((task) => orchestrator.startContinuousTask(task, 0));
}
