import { randomUUID } from 'node:crypto';
import { broadcastToWorkspace } from '../ws/connection-manager.js';
const pendingRequests = new Map();
export function requestMiniAppClient(projectId, type, payload, timeoutMs = 5000) {
    const requestId = randomUUID();
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
            pendingRequests.delete(requestId);
            reject(new Error(`Mini-app client request timed out: ${type}`));
        }, timeoutMs);
        pendingRequests.set(requestId, { resolve, reject, timer });
        broadcastToWorkspace(projectId, 'miniApp.clientRequest', { requestId, type, payload });
    });
}
export function handleMiniAppClientResponse(data) {
    if (!data || typeof data !== 'object' || Array.isArray(data))
        return;
    const response = data;
    if (typeof response.requestId !== 'string')
        return;
    const pending = pendingRequests.get(response.requestId);
    if (!pending)
        return;
    pendingRequests.delete(response.requestId);
    clearTimeout(pending.timer);
    if (response.ok === false) {
        pending.reject(new Error(typeof response.error === 'string' ? response.error : 'Mini-app client request failed'));
        return;
    }
    pending.resolve(response.result);
}
//# sourceMappingURL=mini-app-client-rpc.js.map