"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeHMRData = void 0;
const enum_1 = require("@/@types/enum");
const log_1 = require("@/utils/log");
const logger = new log_1.Logger('buffer-decoder', enum_1.WinstonColor.White);
const decodeHMRData = (buf) => {
    const { offset, emitJSON } = decodeEmitJSON(0, buf);
    const emitList = decodeEmitFiles(offset, buf);
    return Object.assign(Object.assign({}, emitJSON), { emitList });
};
exports.decodeHMRData = decodeHMRData;
const decodeEmitFiles = (offset, buf) => {
    const fileNum = buf.readUInt8(offset);
    offset += 1;
    const emitList = [];
    for (let i = 0; i < fileNum; i++) {
        const fnameLen = buf.readUInt8(offset);
        offset += 1;
        const name = buf.toString('utf8', offset, (offset += fnameLen));
        const lenOfLen = buf.readUInt8(offset);
        offset += 1;
        const fn = {
            1: 'readUInt8',
            2: 'readUInt16BE',
            4: 'readUInt32BE',
        }[lenOfLen];
        const fileLen = buf[fn](offset);
        offset += lenOfLen;
        const content = buf.slice(offset, (offset += fileLen));
        emitList.push({ name, content });
    }
    return emitList;
};
const decodeEmitJSON = (offset = 0, buf) => {
    const lenOfLen = buf.readUInt8(offset);
    offset += 1;
    const fn = {
        1: 'readUInt8',
        2: 'readUInt16BE',
        4: 'readUInt32BE',
    }[lenOfLen];
    const jsonLen = buf[fn](offset);
    offset += lenOfLen;
    const str = buf.toString('utf8', offset, offset + jsonLen);
    offset += jsonLen;
    try {
        const emitJSON = JSON.parse(str);
        return { emitJSON, offset };
    }
    catch (e) {
        logger.error('decodeEmitJSON error: %j', e.stack || e);
        throw e;
    }
};
