import Kink from '@termsurf/kink';
import { fetchWithTimeout, getRemote, postRemote, } from './request.js';
import { wait } from './timer.js';
export async function requestAndWaitForWorkToComplete(request, controller) {
    const workResponse = await postRemote(request, controller);
    if (workResponse.status >= 400) {
        const error = await workResponse.json();
        throw new Kink(error);
    }
    const work = (await workResponse.json());
    while (true) {
        await wait(1200);
        const stepResponse = await getRemote(`/work/${work.id}`, controller);
        if (stepResponse.status >= 400) {
            const error = await stepResponse.json();
            throw new Kink(error);
        }
        const step = await stepResponse.json();
        if (step.status === 'complete') {
            return step.output;
        }
        else if (step.status === 'error') {
            throw new Kink(step.output);
        }
    }
}
export async function resolveAsArrayBuffer(request) {
    const response = await postRemote(request);
    return await response.arrayBuffer();
}
export async function resolveWorkFileAsBlob(request, controller) {
    const output = await requestAndWaitForWorkToComplete(request);
    const fileResponse = await fetchWithTimeout(output.file.path, {
        method: 'GET',
        controller,
    });
    const arrayBuffer = await fileResponse.arrayBuffer();
    return new Blob([arrayBuffer]);
}
//# sourceMappingURL=work.js.map