UNPKG

cbor2

Version:

Encode and parse data in the Concise Binary Object Representation (CBOR) data format (RFC8949).

2 lines (1 loc) 6.98 kB
import{TypeEncoderMap as L}from"./typeEncoderMap.js";import{DCBOR_INT as x,MT as f,NUMBYTES as d,SIMPLE as l,SYMS as m,TAG as I}from"./constants.js";import{sortCoreDeterministic as _}from"./sorts.js";import{Writer as O}from"./writer.js";import{box as G,getEncodedLength as C}from"./box.js";import{flushToZero as D,halfToUint as S}from"./float.js";import{Wtf8Encoder as M}from"@cto.af/wtf8";import{hexToU8 as W}from"./utils.js";const{ENCODED:se}=m,U=f.SIMPLE_FLOAT<<5|d.TWO,h=f.SIMPLE_FLOAT<<5|d.FOUR,B=f.SIMPLE_FLOAT<<5|d.EIGHT,j=f.SIMPLE_FLOAT<<5|l.TRUE,P=f.SIMPLE_FLOAT<<5|l.FALSE,$=f.SIMPLE_FLOAT<<5|l.UNDEFINED,q=f.SIMPLE_FLOAT<<5|l.NULL,z=new TextEncoder,K=new M,k={...O.defaultOptions,avoidInts:!1,cde:!1,collapseBigInts:!0,dcbor:!1,float64:!1,flushToZero:!1,forceEndian:null,ignoreOriginalEncoding:!1,largeNegativeAsBigInt:!1,reduceUnsafeNumbers:!1,rejectBigInts:!1,rejectCustomSimples:!1,rejectDuplicateKeys:!1,rejectFloats:!1,rejectUndefined:!1,simplifyNegativeZero:!1,sortKeys:null,stringNormalization:null,types:null,wtf8:!1},F={cde:!0,ignoreOriginalEncoding:!0,sortKeys:_},H={...F,dcbor:!0,largeNegativeAsBigInt:!0,reduceUnsafeNumbers:!0,rejectCustomSimples:!0,rejectDuplicateKeys:!0,rejectUndefined:!0,simplifyNegativeZero:!0,stringNormalization:"NFC"};function y(e){const n=e<0;return typeof e=="bigint"?[n?-e-1n:e,n]:[n?-e-1:e,n]}function T(e,n,t){if(t.rejectFloats)throw new Error(`Attempt to encode an unwanted floating point number: ${e}`);if(isNaN(e))n.writeUint8(U),n.writeUint16(32256);else if(!t.float64&&Math.fround(e)===e){const r=S(e);r===null?(n.writeUint8(h),n.writeFloat32(e)):(n.writeUint8(U),n.writeUint16(r))}else n.writeUint8(B),n.writeFloat64(e)}function a(e,n,t){const[r,i]=y(e);if(i&&t)throw new TypeError(`Negative size: ${e}`);t??=i?f.NEG_INT:f.POS_INT,t<<=5,r<24?n.writeUint8(t|r):r<=255?(n.writeUint8(t|d.ONE),n.writeUint8(r)):r<=65535?(n.writeUint8(t|d.TWO),n.writeUint16(r)):r<=4294967295?(n.writeUint8(t|d.FOUR),n.writeUint32(r)):(n.writeUint8(t|d.EIGHT),n.writeBigUint64(BigInt(r)))}function p(e,n,t){typeof e=="number"?a(e,n,f.TAG):typeof e=="object"&&!t.ignoreOriginalEncoding&&m.ENCODED in e?n.write(e[m.ENCODED]):e<=Number.MAX_SAFE_INTEGER?a(Number(e),n,f.TAG):(n.writeUint8(f.TAG<<5|d.EIGHT),n.writeBigUint64(BigInt(e)))}function N(e,n,t){const[r,i]=y(e);if(t.collapseBigInts&&(!t.largeNegativeAsBigInt||e>=-0x8000000000000000n)){if(r<=0xffffffffn){a(Number(e),n);return}if(r<=0xffffffffffffffffn){const E=(i?f.NEG_INT:f.POS_INT)<<5;n.writeUint8(E|d.EIGHT),n.writeBigUint64(r);return}}if(t.rejectBigInts)throw new Error(`Attempt to encode unwanted bigint: ${e}`);const o=i?I.NEG_BIGINT:I.POS_BIGINT,c=r.toString(16),s=c.length%2?"0":"";p(o,n,t);const u=W(s+c);a(u.length,n,f.BYTE_STRING),n.write(u)}function Y(e,n,t){t.flushToZero&&(e=D(e)),Object.is(e,-0)?t.simplifyNegativeZero?t.avoidInts?T(0,n,t):a(0,n):T(e,n,t):!t.avoidInts&&Number.isSafeInteger(e)?a(e,n):t.reduceUnsafeNumbers&&Math.floor(e)===e&&e>=x.MIN&&e<=x.MAX?N(BigInt(e),n,t):T(e,n,t)}function Z(e,n,t){const r=t.stringNormalization?e.normalize(t.stringNormalization):e;if(t.wtf8&&!e.isWellFormed()){const i=K.encode(r);p(I.WTF8,n,t),a(i.length,n,f.BYTE_STRING),n.write(i)}else{const i=z.encode(r);a(i.length,n,f.UTF8_STRING),n.write(i)}}function J(e,n,t){const r=e;R(r,r.length,f.ARRAY,n,t);for(const i of r)g(i,n,t)}function V(e,n){a(e.length,n,f.BYTE_STRING),n.write(e)}const b=new L;b.registerEncoder(Array,J),b.registerEncoder(Uint8Array,V);function ce(e,n){return b.registerEncoder(e,n)}function ue(e){const n=b.get(e);return b.delete(e),n}function R(e,n,t,r,i){const o=C(e);o&&!i.ignoreOriginalEncoding?r.write(o):a(n,r,t)}function X(e,n,t){if(e===null){n.writeUint8(q);return}if(!t.ignoreOriginalEncoding&&m.ENCODED in e){n.write(e[m.ENCODED]);return}const r=e.constructor;if(r){const o=t.types?.get(r)??b.get(r);if(o){const c=o(e,n,t);if(c!==void 0){if(!Array.isArray(c)||c.length!==2)throw new Error("Invalid encoder return value");(typeof c[0]=="bigint"||isFinite(Number(c[0])))&&p(c[0],n,t),g(c[1],n,t)}return}}if(typeof e.toCBOR=="function"){const o=e.toCBOR(n,t);o&&((typeof o[0]=="bigint"||isFinite(Number(o[0])))&&p(o[0],n,t),g(o[1],n,t));return}if(typeof e.toJSON=="function"){g(e.toJSON(),n,t);return}const i=Object.entries(e).map(o=>[o[0],o[1],Q(o[0],t)]);t.sortKeys&&i.sort(t.sortKeys),R(e,i.length,f.MAP,n,t);for(const[o,c,s]of i)n.write(s),g(c,n,t)}function g(e,n,t){switch(typeof e){case"number":Y(e,n,t);break;case"bigint":N(e,n,t);break;case"string":Z(e,n,t);break;case"boolean":n.writeUint8(e?j:P);break;case"undefined":if(t.rejectUndefined)throw new Error("Attempt to encode unwanted undefined.");n.writeUint8($);break;case"object":X(e,n,t);break;case"symbol":throw new TypeError(`Unknown symbol: ${e.toString()}`);default:throw new TypeError(`Unknown type: ${typeof e}, ${String(e)}`)}}function Q(e,n={}){const t={...k};n.dcbor?Object.assign(t,H):n.cde&&Object.assign(t,F),Object.assign(t,n);const r=new O(t);return g(e,r,t),r.read()}function de(e,n,t=f.POS_INT){n||(n="f");const r={...k,collapseBigInts:!1,chunkSize:10,simplifyNegativeZero:!1},i=new O(r),o=Number(e);function c(s){if(Object.is(e,-0))throw new Error("Invalid integer: -0");const[u,E]=y(e);if(E&&t!==f.POS_INT)throw new Error("Invalid major type combination");const w=typeof s=="number"&&isFinite(s);if(w&&!Number.isSafeInteger(o))throw new TypeError(`Unsafe number for ${n}: ${e}`);if(u>s)throw new TypeError(`Undersized encoding ${n} for: ${e}`);const A=(E?f.NEG_INT:t)<<5;return w?[A,Number(u)]:[A,u]}switch(n){case"bigint":if(Object.is(e,-0))throw new TypeError("Invalid bigint: -0");e=BigInt(e),N(e,i,r);break;case"f":T(o,i,r);break;case"f16":{const s=S(o);if(s===null)throw new TypeError(`Invalid f16: ${e}`);i.writeUint8(U),i.writeUint16(s);break}case"f32":if(!isNaN(o)&&Math.fround(o)!==o)throw new TypeError(`Invalid f32: ${e}`);i.writeUint8(h),i.writeFloat32(o);break;case"f64":i.writeUint8(B),i.writeFloat64(o);break;case"i":if(Object.is(e,-0))throw new Error("Invalid integer: -0");if(Number.isSafeInteger(o))a(o,i,e<0?void 0:t);else{const[s,u]=c(1/0);u>0xffffffffffffffffn?(e=BigInt(e),N(e,i,r)):(i.writeUint8(s|d.EIGHT),i.writeBigUint64(BigInt(u)))}break;case"i0":{const[s,u]=c(23);i.writeUint8(s|u);break}case"i8":{const[s,u]=c(255);i.writeUint8(s|d.ONE),i.writeUint8(u);break}case"i16":{const[s,u]=c(65535);i.writeUint8(s|d.TWO),i.writeUint16(u);break}case"i32":{const[s,u]=c(4294967295);i.writeUint8(s|d.FOUR),i.writeUint32(u);break}case"i64":{const[s,u]=c(0xffffffffffffffffn);i.writeUint8(s|d.EIGHT),i.writeBigUint64(BigInt(u));break}default:throw new TypeError(`Invalid number encoding: "${n}"`)}return G(e,i.read())}export{se as ENCODED,F as cdeEncodeOptions,ue as clearEncoder,H as dcborEncodeOptions,k as defaultEncodeOptions,Q as encode,de as encodedNumber,ce as registerEncoder,J as writeArray,N as writeBigInt,T as writeFloat,a as writeInt,R as writeLength,Y as writeNumber,Z as writeString,p as writeTag,V as writeUint8Array,g as writeUnknown};