"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withDeserializedCallbackBuffers = exports.withSerializedCallbackBuffers = exports.withDeserializedBodyReader = exports.withSerializedBodyReader = void 0;
const _ = require("lodash");
const base64_arraybuffer_1 = require("base64-arraybuffer");
const buffer_utils_1 = require("../util/buffer-utils");
const request_utils_1 = require("../util/request-utils");
const serialization_1 = require("./serialization");
function withSerializedBodyReader(input) {
    return {
        ...input,
        body: (0, buffer_utils_1.asBuffer)(input.body.buffer).toString('base64')
    };
}
exports.withSerializedBodyReader = withSerializedBodyReader;
function withDeserializedBodyReader(input) {
    return {
        ...input,
        body: (0, request_utils_1.buildBodyReader)((0, serialization_1.deserializeBuffer)(input.body), input.headers)
    };
}
exports.withDeserializedBodyReader = withDeserializedBodyReader;
/**
 * Serialize a callback result (callback handlers, BeforeRequest/Response etc)
 * to transform all the many possible buffer formats into either base64-encoded
 * buffer data, or undefined.
 */
function withSerializedCallbackBuffers(input) {
    let serializedBody;
    if (!input.body) {
        serializedBody = undefined;
    }
    else if (_.isString(input.body)) {
        serializedBody = (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(input.body));
    }
    else if (_.isBuffer(input.body)) {
        serializedBody = (0, serialization_1.serializeBuffer)(input.body);
    }
    else if (_.isArrayBuffer(input.body) || _.isTypedArray(input.body)) {
        serializedBody = (0, base64_arraybuffer_1.encode)(input.body);
    }
    else if ((0, request_utils_1.isMockttpBody)(input.body)) {
        serializedBody = (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(input.body.buffer));
    }
    return {
        ...input,
        body: serializedBody,
        rawBody: input.rawBody
            ? (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(input.rawBody))
            : undefined
    };
}
exports.withSerializedCallbackBuffers = withSerializedCallbackBuffers;
/**
 * Deserialize a callback result (callback handlers, BeforeRequest/Response etc)
 * to build buffer data (or undefined) from the base64-serialized data
 * produced by withSerializedCallbackBuffers
 */
function withDeserializedCallbackBuffers(input) {
    return {
        ...input,
        body: input.body !== undefined
            ? Buffer.from(input.body, 'base64')
            : undefined,
        rawBody: input.rawBody !== undefined
            ? Buffer.from(input.rawBody, 'base64')
            : undefined
    };
}
exports.withDeserializedCallbackBuffers = withDeserializedCallbackBuffers;
//# sourceMappingURL=body-serialization.js.map