All files mqtt-plus-codec.ts

99.19% Statements 123/124
70.83% Branches 34/48
95.23% Functions 20/21
99.19% Lines 123/124

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 1251x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x    
/*
**  MQTT+ -- MQTT Communication Patterns
**  Copyright (c) 2018-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
/*  external requirements  */
import { Buffer }                         from "node:buffer"
import * as CBOR                          from "cbor2"
 
/*  internal requirements  */
import type { APISchema }                 from "./mqtt-plus-api"
import { type APIOptions, OptionsTrait }  from "./mqtt-plus-options"
 
/*  JSON encode/decode with Uint8Array support  */
export class JSONX {
    private static uint8ArrayToBase64 (arr: Uint8Array): string {
        return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength).toString("base64")
    }
    private static base64ToUint8Array (base64: string): Uint8Array {
        return new Uint8Array(Buffer.from(base64, "base64"))
    }
    static stringify (obj: unknown): string {
        return JSON.stringify(obj, (_, value) =>
            value instanceof Uint8Array
                ? { __Uint8Array: this.uint8ArrayToBase64(value) }
                : value
        )
    }
    static parse (json: string): unknown {
        return JSON.parse(json, (_, value) =>
            typeof value?.__Uint8Array === "string"
                ? this.base64ToUint8Array(value.__Uint8Array)
                : value
        )
    }
}
 
/*  the encoder/decoder abstraction  */
class Codec {
    private types = new CBOR.TypeEncoderMap()
    private tags: CBOR.TagDecoderMap = new Map<CBOR.TagNumber, CBOR.TagDecoder>()
    constructor (
        private format: "cbor" | "json"
    ) {
        /*  support direct encoding/decoding of Buffer  */
        const TAG_BUFFER = 64000
        this.types.registerEncoder(Buffer, (buffer: Buffer) => {
            return [ TAG_BUFFER, new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) ]
        })
        this.tags.set(TAG_BUFFER, (tag: CBOR.ITag) => {
            return Buffer.from(tag.contents as Uint8Array)
        })
    }
    encode (data: unknown): Uint8Array | string {
        let result: Uint8Array | string
        if (this.format === "cbor") {
            try { result = CBOR.encode(data, { types: this.types }) }
            catch (err: unknown) { throw new Error("failed to encode CBOR format", { cause: err }) }
        }
        else if (this.format === "json") {
            try { result = JSONX.stringify(data) }
            catch (err: unknown) { throw new Error("failed to encode JSON format", { cause: err }) }
        }
        else
            throw new Error(`invalid format "${this.format}"`)
        return result
    }
    decode (data: Uint8Array | string): unknown {
        let result: unknown
        if (this.format === "cbor") {
            if (!(data instanceof Uint8Array))
                throw new Error("failed to decode CBOR format (data type is not Uint8Array)")
            if (data.byteLength === 0)
                throw new Error("failed to decode CBOR format (data is empty)")
            try { result = CBOR.decode(data, { tags: this.tags }) }
            catch (err: unknown) { throw new Error("failed to decode CBOR format", { cause: err }) }
        }
        else if (this.format === "json") {
            if (typeof data !== "string")
                throw new Error("failed to decode JSON format (data type is not string)")
            if (data.length === 0)
                throw new Error("failed to decode JSON format (data is empty)")
            try { result = JSONX.parse(data) }
            catch (err: unknown) { throw new Error("failed to decode JSON format", { cause: err }) }
        }
        else
            throw new Error(`invalid format "${this.format}"`)
        return result
    }
}
 
/*  Codec trait  */
export class CodecTrait<T extends APISchema = APISchema> extends OptionsTrait<T> {
    protected codec: Codec
 
    /*  construct API class  */
    constructor (
        options: Partial<APIOptions> = {}
    ) {
        super(options)
 
        /*  establish a codec  */
        this.codec = new Codec(this.options.codec)
    }
}