"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeControlledPromise = void 0;
function makeControlledPromise() {
    let promise;
    let resolve;
    let reject;
    let result;
    function getPromise() {
        if (!promise) {
            promise = new Promise((...args) => ([resolve, reject] = args));
            if (result) {
                if (result.status === 'fulfilled')
                    resolve(result.value);
                else
                    reject(result.reason);
            }
        }
        return promise;
    }
    return {
        then(onFulfilled, onRejected) {
            return getPromise().then(onFulfilled, onRejected);
        },
        catch(onRejected) {
            return getPromise().catch(onRejected);
        },
        finally(onFinally) {
            return getPromise().finally(onFinally);
        },
        get [Symbol.toStringTag]() {
            return 'ControlledPromise';
        },
        get settled() {
            return !!result;
        },
        resolve(value) {
            if (resolve)
                resolve(value);
            else
                result !== null && result !== void 0 ? result : (result = { status: 'fulfilled', value });
        },
        reject(reason) {
            if (reject)
                reject(reason);
            else
                result !== null && result !== void 0 ? result : (result = { status: 'rejected', reason });
        },
    };
}
exports.makeControlledPromise = makeControlledPromise;
