export const ATTEMPT_TRANSITIONS = Object.freeze({
    "preparing-workspace": Object.freeze(["running-step", "failed", "canceled"]),
    "running-step": Object.freeze(["running-step", "succeeded", "failed", "canceled"]),
    succeeded: Object.freeze([]),
    failed: Object.freeze([]),
    canceled: Object.freeze([]),
});
export function transitionPhase(current, next, ctx) {
    if (current === null) {
        if (next !== "preparing-workspace") {
            throw new Error(`Illegal attempt phase transition: null -> ${next}`);
        }
        return validatedState({ phase: next }, next, ctx);
    }
    if (!ATTEMPT_TRANSITIONS[current.phase].includes(next)) {
        throw new Error(`Illegal attempt phase transition: ${current.phase} -> ${next}`);
    }
    return validatedState({
        ...current,
        phase: next,
    }, next, ctx);
}
function validatedState(baseState, next, ctx) {
    const nextState = {
        ...baseState,
    };
    if (ctx.step !== undefined) {
        nextState.step = ctx.step;
    }
    if (ctx.failure !== undefined) {
        nextState.failure = ctx.failure;
    }
    if (ctx.failedStep !== undefined) {
        nextState.failedStep = ctx.failedStep;
    }
    if (ctx.error !== undefined) {
        nextState.error = ctx.error;
    }
    if (next === "failed" && nextState.failure === undefined) {
        throw new Error("Failure category is required for failed phase");
    }
    if ((next === "succeeded" || next === "canceled") && nextState.failure !== undefined) {
        throw new Error(`Failure category must be absent for ${next} phase`);
    }
    return nextState;
}
