"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupInit = setupInit;
exports.setupOnInit = setupOnInit;
const util_1 = require("../util");
/**
 * Composes multiple init handlers into a single `ExpectedExports.init`-compatible function.
 * Handlers are executed sequentially in the order provided.
 *
 * @param inits - One or more init handlers to compose
 */
function setupInit(...inits) {
    return async (opts) => {
        for (const idx in inits) {
            const init = inits[idx];
            const fn = async () => {
                let res = () => { };
                const complete = new Promise((resolve) => {
                    res = resolve;
                });
                const e = opts.effects.child(`init_${idx}`);
                e.constRetry = (0, util_1.once)(() => complete.then(() => fn()).catch(console.error));
                try {
                    if ('init' in init)
                        await init.init(e, opts.kind);
                    else
                        await init(e, opts.kind);
                }
                finally {
                    res();
                }
            };
            await fn();
        }
    };
}
/** Normalizes an {@link InitScriptOrFn} into an {@link InitScript} object. */
function setupOnInit(onInit) {
    return 'init' in onInit
        ? onInit
        : {
            init: async (effects, kind) => {
                await onInit(effects, kind);
            },
        };
}
//# sourceMappingURL=setupInit.js.map