function serializeBindings(config) {
    const serialized = {};
    for (const [key, binding] of Object.entries(config)) {
        if (binding !== undefined)
            serialized[key] = Array.isArray(binding) ? [...binding] : binding;
    }
    return serialized;
}
/**
 * Serializes the full keybinding/session reload transaction for one shared
 * manager. The queue survives rejection, mutates the manager in place, and
 * publishes only state from a committed successful reload.
 */
export class KeybindingsReloadCoordinator {
    constructor(keybindings, onCommitted, resolveShortcuts) {
        this.tail = Promise.resolve();
        this.keybindings = keybindings;
        this.onCommitted = onCommitted;
        this.resolveShortcuts = resolveShortcuts;
    }
    reload(session) {
        const transaction = this.tail.then(() => this.runTransaction(session), () => this.runTransaction(session));
        this.tail = transaction.then(() => { }, () => { });
        return transaction;
    }
    publishCurrentState(session) {
        if (!this.keybindings)
            return undefined;
        const state = this.createState(session);
        this.onCommitted?.(state);
        return state;
    }
    createState(session) {
        const effectiveBindings = this.keybindings.getEffectiveConfig();
        return {
            userBindings: serializeBindings(this.keybindings.getUserBindings()),
            effectiveBindings: serializeBindings(effectiveBindings),
            shortcuts: this.resolveShortcuts?.(session, effectiveBindings) ?? [],
        };
    }
    async runTransaction(session) {
        if (!this.keybindings) {
            await session.reload();
            return undefined;
        }
        const previousUserBindings = this.keybindings.getUserBindings();
        let keybindingsApplied = false;
        try {
            await session.reload({
                beforeSessionStart: () => {
                    this.keybindings.reload();
                    keybindingsApplied = true;
                },
            });
            return this.publishCurrentState(session);
        }
        catch (error) {
            if (keybindingsApplied)
                this.keybindings.setUserBindings(previousUserBindings);
            throw error;
        }
    }
}
/** Compatibility helper for callers that do not share a longer-lived queue. */
export async function reloadSessionWithKeybindings(session, keybindings, onKeybindingsReloaded) {
    const coordinator = new KeybindingsReloadCoordinator(keybindings, onKeybindingsReloaded ? () => onKeybindingsReloaded() : undefined);
    await coordinator.reload(session);
}
//# sourceMappingURL=rpc-keybindings-reload.js.map