import base64 from '@root/encoding/base64.js';
import cbor from 'cbor';
export const jose2cbor = async (obj) => {
    const clone = JSON.parse(JSON.stringify(obj));
    const convertJSON2CBOR = (o) => {
        for (const key in o) {
            if (key === 'header' || key === 'unprotected') {
                continue;
            }
            if (typeof o[key] === 'object' && !Array.isArray(o[key])) {
                convertJSON2CBOR(o[key]);
            }
            else if (Array.isArray(o[key])) {
                for (const x of obj[key]) {
                    convertJSON2CBOR(x);
                }
            }
            else {
                // The absence of a Buffer entity on web browsers has introduced the need to wrap the key properties with a UInt8Array
                o[key] = new Uint8Array(base64.base64ToBuf(o[key]));
            }
        }
        return o;
    };
    return cbor.encodeAsync(convertJSON2CBOR(clone));
};
// As a consequence a verification on the constructor name for key properties needs to be created.
const isUInt8Array = (element) => typeof element === 'object' && element.constructor && element.constructor.name === 'Uint8Array';
export const cbor2jose = async (buf) => {
    const obj = await cbor.decodeFirst(buf);
    const convertCBOR2JSON = (obj) => {
        for (const key in obj) {
            if (key === 'header' || key === 'unprotected') {
                continue;
            }
            else if (Array.isArray(obj[key])) {
                for (const x of obj[key]) {
                    convertCBOR2JSON(x);
                }
            }
            else if (isUInt8Array(obj[key])) {
                obj[key] = base64.bufToUrlBase64(obj[key]);
            }
        }
        return obj;
    };
    return convertCBOR2JSON(obj);
};
//# sourceMappingURL=cbor-jose.js.map