UNPKG

schemind

Version:

Read and write to messages serialized as arrays (indexed keys) by defining a schema, enabling smaller message size when using protocols such as msgpack or JSON.

2 lines (1 loc) 1.68 kB
(function(c,r){typeof exports=="object"&&typeof module<"u"?r(exports):typeof define=="function"&&define.amd?define(["exports"],r):(c=typeof globalThis<"u"?globalThis:c||self,r(c.Schemind={}))})(this,function(c){"use strict";function r(e,t){const o=t[a];let s=e;for(let i=t[a].length-1;i>=1;i--)s=s[o[i]];const d=o[0];return s[d]}function u(e,t,o){const s=t[a];let d=e;for(let n=t[a].length-1;n>=1;n--)d[s[n]]===void 0&&(d[s[n]]=[]),d=d[s[n]];const i=s[0];d[i]=o}const a=Symbol("indexesPathReversed"),g=Symbol("fieldType"),S=Symbol("isSchemaLeaf");class h extends Error{constructor(){super("Invalid schema. Make sure there are no duplicate indexes, and that nested objects are also wrapped with withIndex."),this.name="InvalidSchemaError"}}function y(e){return b(e,e,[],0),e}function b(e,t,o,s){for(const[d,i]of Object.entries(t)){const n=i;f(n)?(p(n,o,s),n.get=l=>r(l,n),n.set=(l,O)=>u(l,n,O)):b(e,n,o,s+1)}}function p(e,t,o){if(t.some(i=>i.length===e[a].length&&i.every((n,l)=>n===e[a][l])))throw new h;if(t.push(e[a]),e[a].length!==o+1)throw new h}function x(e){return t=>t?(v(t,e),t):{[a]:[e],[g]:void 0,[S]:!0}}function f(e){return Object.hasOwn(e,S)}function v(e,t){for(const[o,s]of Object.entries(e)){const d=s;f(d)?d[a].push(t):v(d,t)}}function I(e,t){const o={};for(const[s,d]of Object.entries(t)){const i=d;let n;f(i)?n=r(e,i):n=I(e,i),o[s]=n}return o}function j(e,t){const o=[];return m(o,e,t),o}function m(e,t,o){for(const[s,d]of Object.entries(o)){const i=d,n=t[s];f(i)?u(e,i,n):m(e,n,i)}}c.InvalidSchemaError=h,c.buildSchema=y,c.get=r,c.set=u,c.toIndexedKeysMessage=j,c.toPlainObject=I,c.withIndex=x,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});