import zlib from 'zlib';
/**
 * Decompresses received body if `content-encoding` header is set.
 * When multiple encodings are present, they are decoded in reverse order
 * (last applied encoding is decoded first).
 */
export async function decompress(body, options = {}) {
    const { aborted, headers } = options;
    if (aborted || !headers || !body) {
        return;
    }
    const ce = headers.get('content-encoding');
    if (!ce) {
        return body;
    }
    // Parse encodings from the header - they are listed in the order they were applied
    const encodings = ce
        .split(',')
        .map((enc) => enc.trim().toLowerCase())
        .filter((enc) => enc.length > 0);
    if (encodings.length === 0) {
        return body;
    }
    // Decode in reverse order (last applied encoding first)
    let currentBody = body;
    for (let i = encodings.length - 1; i >= 0; i--) {
        const encoding = encodings[i];
        if (encoding === 'deflate') {
            currentBody = await inflate(currentBody);
        }
        else if (encoding === 'gzip') {
            currentBody = await gunzip(currentBody);
        }
        else if (encoding === 'br' || encoding === 'brotli') {
            currentBody = await brotli(currentBody);
        }
        // If encoding is unknown, we continue with the current body unchanged
    }
    return currentBody;
}
/**
 * Decompress body with Inflate.
 */
export function inflate(body) {
    const buff = Buffer.from(body);
    return new Promise((resolve, reject) => {
        zlib.inflate(buff, (err, buffer) => {
            if (err) {
                reject(new Error(err.message || String(err)));
            }
            else {
                resolve(buffer);
            }
        });
    });
}
/**
 * Decompress body with ZLib.
 */
export function gunzip(body) {
    const buff = Buffer.from(body);
    return new Promise((resolve, reject) => {
        zlib.gunzip(buff, (err, buffer) => {
            if (err) {
                reject(new Error(err.message || String(err)));
            }
            else {
                resolve(buffer);
            }
        });
    });
}
/**
 * Decompress Brotli.
 */
export function brotli(body) {
    const buff = Buffer.from(body);
    return new Promise((resolve, reject) => {
        zlib.brotliDecompress(buff, (err, buffer) => {
            if (err) {
                reject(err);
            }
            else {
                resolve(buffer);
            }
        });
    });
}
//# sourceMappingURL=CompressionManager.js.map