export var createMessagePasserReceiver = function (api, messageApi) {
    var sendResponse = function (identifier, data) {
        var response = {
            identifier: identifier,
            data: data,
        };
        messageApi.postMessage(response);
    };
    var sendErrorResponse = function (identifier, error) {
        var response = {
            identifier: identifier,
            error: {
                message: error.message,
                stack: error.stack,
                name: error.name,
            },
        };
        messageApi.postMessage(response);
    };
    messageApi.addEventListener("message", function (_a) {
        var _b = _a.data, method = _b.method, params = _b.params, identifier = _b.identifier;
        var targetMethod = api[method];
        if (typeof targetMethod !== "function") {
            return sendResponse(identifier, targetMethod);
        }
        try {
            var result = targetMethod.apply(api, params);
            if (typeof result === "object" &&
                typeof result["then"] === "function") {
                return result
                    .then(function (result) { return sendResponse(identifier, result); })
                    .catch(function (err) {
                    return sendErrorResponse(identifier, err);
                });
            }
            sendResponse(identifier, result);
        }
        catch (err) {
            sendErrorResponse(identifier, err);
        }
    });
};
