"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeHMRData = void 0;
const tslib_1 = require("tslib");
const buffer_1 = require("buffer");
const encodeHMRData = (data) => {
    const { emitList = [] } = data, emitJSON = tslib_1.__rest(data, ["emitList"]);
    emitJSON.performance = {
        pcToServer: Date.now(),
    };
    const fileBuffer = encodeEmitFiles(emitList);
    const jsonBuffer = encodeEmitJSON(emitJSON);
    return buffer_1.Buffer.concat([jsonBuffer, fileBuffer]);
};
exports.encodeHMRData = encodeHMRData;
const encodeEmitFiles = (emitList = []) => {
    const fileNumLen = 1;
    const headBuf = buffer_1.Buffer.alloc(fileNumLen);
    headBuf.writeUInt8(emitList.length);
    const fileBuffers = emitList.map(genFileBufferWithLen);
    return buffer_1.Buffer.concat([headBuf, ...fileBuffers]);
};
const encodeEmitJSON = (data) => {
    const dataStr = JSON.stringify(data);
    const dataBuf = buffer_1.Buffer.from(dataStr);
    return genBufferWithLen(dataBuf);
};
function genFileBufferWithLen({ name, content }) {
    const nameBuf = buffer_1.Buffer.from(name);
    const len = 1 + nameBuf.length;
    const headBuf = buffer_1.Buffer.alloc(len);
    let offset = 0;
    headBuf.writeUInt8(nameBuf.length, offset);
    offset += 1;
    nameBuf.copy(headBuf, offset, 0);
    const fileBufferWithLen = genBufferWithLen(content);
    return buffer_1.Buffer.concat([headBuf, fileBufferWithLen]);
}
function getLenOfLen(len) {
    let lenOfLen = 1;
    if (len > 0xffff)
        lenOfLen = 4;
    else if (len > 0xff)
        lenOfLen = 2;
    return lenOfLen;
}
function genBufferWithLen(buf) {
    const len = buf.length;
    const lenOfLen = getLenOfLen(len);
    const headBuf = buffer_1.Buffer.alloc(1 + lenOfLen);
    let offset = 0;
    headBuf.writeUInt8(lenOfLen, offset);
    const fn = {
        1: 'writeUInt8',
        2: 'writeUInt16BE',
        4: 'writeUInt32BE',
    }[lenOfLen];
    headBuf[fn](len, (offset += 1));
    return buffer_1.Buffer.concat([headBuf, buf]);
}
