import { renderMethodNotFoundError, renderMissingResponseError, renderUnexpectedResultError } from './error-renderers';
export const createMessageHandler = (receiver, workerImplementation) => {
    return async ({ data: { id, method, params } }) => {
        const messageHandler = workerImplementation[method];
        try {
            if (messageHandler === undefined) {
                throw renderMethodNotFoundError(method);
            }
            const response = params === undefined
                ? messageHandler()
                : messageHandler(params);
            if (response === undefined) {
                throw renderMissingResponseError(method);
            }
            const synchronousResponse = response instanceof Promise ? await response : response;
            if (id === null) {
                if (synchronousResponse.result !== undefined) {
                    throw renderUnexpectedResultError(method);
                }
            }
            else {
                if (synchronousResponse.result === undefined) {
                    throw renderUnexpectedResultError(method);
                }
                const { result, transferables = [] } = synchronousResponse;
                receiver.postMessage({ id, result }, transferables);
            }
        }
        catch (err) {
            const { message, status = -32603 } = err;
            receiver.postMessage({ error: { code: status, message }, id });
        }
    };
};
//# sourceMappingURL=create-message-handler.js.map