/** SDK-owned platform module. This implementation is maintained in goodvibes-sdk. */
export function createDeferredStartupCoordinator(scheduler = (callback) => {
    const timer = setTimeout(callback, 0);
    timer.unref?.();
}) {
    const pending = new Set();
    return {
        schedule(task) {
            let promise;
            promise = new Promise((resolve) => {
                scheduler(() => {
                    Promise.resolve()
                        .then(() => task.run())
                        .catch((error) => {
                        task.onError?.(error);
                    })
                        .finally(() => {
                        pending.delete(promise);
                        resolve();
                    });
                });
            });
            pending.add(promise);
            return promise;
        },
        async drain(timeoutMs) {
            const snapshot = [...pending];
            if (snapshot.length === 0)
                return;
            const settle = Promise.allSettled(snapshot).then(() => undefined);
            if (timeoutMs == null) {
                await settle;
                return;
            }
            await Promise.race([
                settle,
                new Promise((resolve) => {
                    const timer = setTimeout(resolve, timeoutMs);
                    timer.unref?.();
                }),
            ]);
        },
    };
}
