UNPKG

cesr

Version:

[![NPM Version](https://img.shields.io/npm/v/cesr.svg?style=flat)](https://www.npmjs.com/package/cesr) [![NPM License](https://img.shields.io/npm/l/cesr.svg?style=flat)](https://github.com/lenkan/cesr-js/blob/main/LICENSE) [![CI](https://github.com/lenkan

87 lines (86 loc) 2.43 kB
import { Attachments } from "./attachments.js"; import { decodeUtf8, encodeUtf8 } from "./encoding-utf8.js"; import { VersionString } from "./version-string.js"; function encode(init) { const { v, ...payload } = init; if (typeof v !== "string") { throw new Error(`Version field 'v' in payload must be a string, got ${typeof v}`); } const tmpversion = VersionString.parse(v); const tmp = encodeUtf8(JSON.stringify({ v: tmpversion.text, ...payload, })); const version = new VersionString({ protocol: tmpversion.protocol, major: tmpversion.major, minor: tmpversion.minor, kind: tmpversion.kind, legacy: tmpversion.legacy, size: tmp.length, }); const raw = encodeUtf8(JSON.stringify({ v: version.text, ...payload, })); return raw; } function read(input) { if (input.length === 0) { return null; } if (input[0] !== 0x7b) { const preview = decodeUtf8(input.slice(0, 20)); throw new Error(`Expected JSON starting with '{' (0x7b), got: "${preview}"`); } if (input.length < 25) { return null; } const version = VersionString.extract(input.slice(0, 24)); if (input.length < version.size) { return null; } const frame = input.slice(0, version.size); return JSON.parse(decodeUtf8(frame)); } export class Message { #attachments; #raw; body; constructor(body, attachments) { this.#raw = encode(body); this.body = JSON.parse(decodeUtf8(this.#raw)); this.#attachments = new Attachments(attachments ?? {}); } text() { return decodeUtf8(this.#raw); } get raw() { return this.#raw; } get version() { if (!this.body.v || typeof this.body.v !== "string") { throw new Error("Payload does not contain a valid version string 'v'"); } return VersionString.parse(this.body.v); } get attachments() { return this.#attachments; } set attachments(value) { this.#attachments = new Attachments(value); } static parse(input) { const body = read(input); if (body === null) { return null; } return new Message(body); } static encode(init) { return encode(init); } static from(body) { return new Message(body); } }