UNPKG

lnp

Version:

A compact and deterministic length-prefixed serialization format with a minimal, unambiguous grammar.

2 lines 1.8 kB
var a=new TextEncoder,u=class{encode(r){return this.encodeLNP(r)}pack(r,e){return Buffer.concat([Buffer.from(r),Buffer.from(String(e.length)),Buffer.from(":"),Buffer.from(e)])}encodeLNP(r){if(r===null)return this.pack("N",Buffer.alloc(0));switch(typeof r){case"string":return this.pack("s",a.encode(r));case"number":return this.pack("n",Buffer.from(String(r)));case"boolean":return this.pack("b",Buffer.from(r?"t":"f"));case"object":return Array.isArray(r)?this.pack("a",this.encodeLNPArray(r)):this.pack("o",this.encodeLNPObject(r));default:throw new Error("Unsupported type in LNP")}}encodeLNPArray(r){return Buffer.concat(r.map(e=>this.encodeLNP(e)))}encodeLNPObject(r){let e=[];for(let[t,s]of Object.entries(r)){let c=a.encode(t);e.push(Buffer.from(String(c.length)+":")),e.push(Buffer.from(c)),e.push(this.encodeLNP(s))}return Buffer.concat(e)}},i=class{parse(r){let[e,t]=this.parseValue(r);return e}parseValue(r,e=0){let t=String.fromCharCode(r[e]);e++;let s="";for(;r[e]!==58;)s+=String.fromCharCode(r[e]),e++;e++;let c=parseInt(s,10),n=e+c,o=r.subarray(e,n);switch(t){case"s":return[new TextDecoder().decode(o),n];case"n":return[Number(new TextDecoder().decode(o)),n];case"b":return[o[0]===116,n];case"N":return[null,n];case"B":return[Buffer.from(o.toString(),"base64"),n];case"a":return[this.parseArray(o),n];case"o":return[this.parseObject(o),n];default:throw new Error("Unknown type: "+t)}}parseArray(r){let e=0,t=[];for(;e<r.length;){let[s,c]=this.parseValue(r,e);t.push(s),e=c}return t}parseObject(r){let e=0,t={};for(;e<r.length;){let s="";for(;r[e]!==58;)s+=String.fromCharCode(r[e]),e++;e++;let c=parseInt(s,10),n=new TextDecoder().decode(r.subarray(e,e+c));e+=c;let[o,p]=this.parseValue(r,e);t[n]=o,e=p}return t}};export{u as LNPEncoder,i as LNPParser}; //# sourceMappingURL=index.mjs.map