@ldclabs/cose-ts
Version:
Implemented Keys, Algorithms (RFC9053), COSE (RFC9052) and CWT (RFC8392) in TypeScript.
112 lines • 3.22 kB
JavaScript
// (c) 2023-present, LDC Labs. All rights reserved.
// See the file LICENSE for licensing terms.
import { encodeCBOR, decodeCBOR } from './utils';
export function assertText(value, name) {
if (typeof value === 'string') {
return value;
}
throw new TypeError(`${name} must be a string, but got ${String(value)}`);
}
export function assertInt(value, name) {
if (Number.isSafeInteger(value)) {
return value;
}
throw new TypeError(`${name} must be a integer, but got ${String(value)}`);
}
export function assertIntOrText(value, name) {
if (typeof value === 'string') {
return value;
}
if (Number.isSafeInteger(value)) {
return value;
}
throw new TypeError(`${name} must be a integer or string, but got ${String(value)}`);
}
export function assertBytes(value, name) {
if (value instanceof Uint8Array) {
return value;
}
throw new TypeError(`${name} must be a Uint8Array, but got ${String(value)}`);
}
export function assertBool(value, name) {
if (typeof value === 'boolean') {
return value;
}
throw new TypeError(`${name} must be a Boolean, but got ${String(value)}`);
}
export function assertMap(value, name) {
if (value instanceof Map) {
return value;
}
throw new TypeError(`${name} must be a Map, but got ${String(value)}`);
}
export class KVMap {
_raw;
static fromBytes(data) {
return new KVMap(decodeCBOR(data));
}
constructor(kv = new Map()) {
if (!(kv instanceof Map)) {
throw new TypeError('key/value must be a Map');
}
this._raw = kv;
}
has(key) {
return this._raw.has(key);
}
delete(key) {
return this._raw.delete(key);
}
getInt(key, name) {
return assertInt(this._raw.get(key), name ?? String(key));
}
getText(key, name) {
return assertText(this._raw.get(key), name ?? String(key));
}
getBytes(key, name) {
return assertBytes(this._raw.get(key), name ?? String(key));
}
getBool(key, name) {
return assertBool(this._raw.get(key), name ?? String(key));
}
getType(key, assertFn, name) {
return assertFn(this._raw.get(key), name ?? String(key));
}
getArray(key, assertFn, name) {
const na = name ? name : String(key);
const arr = this._raw.get(key);
if (!Array.isArray(arr)) {
throw new TypeError(`${na} must be an array, but got ${String(arr)}`);
}
for (const item of arr) {
assertFn(item, na);
}
return arr;
}
getParam(key) {
return this._raw.get(key);
}
setParam(key, value) {
this._raw.set(key, value);
return this;
}
getCBORParam(key) {
return this._raw.has(key)
? decodeCBOR(assertBytes(this._raw.get(key), String(key)))
: undefined;
}
setCBORParam(key, value) {
this._raw.set(key, encodeCBOR(value));
return this;
}
clone() {
return new Map(this._raw);
}
toRaw() {
return this._raw;
}
toBytes() {
return encodeCBOR(this._raw);
}
}
//# sourceMappingURL=map.js.map