"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timeout = void 0;
exports.thenOrTimeout = thenOrTimeout;
const node_timers_1 = __importDefault(require("node:timers"));
exports.Timeout = Symbol("timeout");
async function thenOrTimeout(p, timeoutMs) {
    // TODO: if timeoutMs is [1, 1000], it's probably a mistake. Should we do
    // something else in that case?
    return timeoutMs <= 1
        ? p
        : new Promise((resolve, reject) => {
            let pending = true;
            const t = node_timers_1.default.setTimeout(() => {
                if (pending) {
                    pending = false;
                    resolve(exports.Timeout);
                }
            }, timeoutMs);
            p.then((result) => {
                if (pending) {
                    pending = false;
                    clearTimeout(t);
                    resolve(result);
                }
            }, (err) => {
                if (pending) {
                    pending = false;
                    clearTimeout(t);
                    reject(err instanceof Error ? err : new Error(String(err)));
                }
            });
        });
}
//# sourceMappingURL=Timeout.js.map