UNPKG

typizator

Version:

Runtime types and metadata schemas for Typescript

2 lines (1 loc) 10.2 kB
"use strict";var ie=Object.create;var D=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var le=(t,a)=>{for(var e in a)D(t,e,{get:a[e],enumerable:!0})},k=(t,a,e,n)=>{if(a&&typeof a=="object"||typeof a=="function")for(let r of se(a))!de.call(t,r)&&r!==e&&D(t,r,{get:()=>a[r],enumerable:!(n=oe(a,r))||n.enumerable});return t};var ue=(t,a,e)=>(e=t!=null?ie(ce(t)):{},k(a||!t||!t.__esModule?D(e,"default",{value:t,enumerable:!0}):e,t)),me=t=>k(D({},"__esModule",{value:!0}),t);var Ee={};le(Ee,{FIELD_MISSING:()=>q,FieldMissingError:()=>T,INT_OUT_OF_BOUNDS:()=>X,INVALID_BOOLEAN:()=>Y,INVALID_DATE:()=>G,INVALID_NUMBER:()=>z,IntOutOfBoundsError:()=>g,InvalidBooleanError:()=>p,InvalidDateError:()=>x,InvalidNumberError:()=>h,JSONArrayNotFoundError:()=>b,JSON_ARRAY_NOT_FOUND:()=>H,NOT_IMPLEMENTED:()=>J,NULL_NOT_ALLOWED:()=>W,NotImplementedError:()=>A,NullNotAllowedError:()=>f,SOURCE_IS_NOT_OBJECT:()=>Q,SourceNotObjectError:()=>y,TypeSchema:()=>d,always:()=>Ae,apiS:()=>Me,arrayS:()=>Te,bigintS:()=>De,boolS:()=>Fe,dateS:()=>Be,dictionaryS:()=>ye,floatS:()=>we,getSchemaSignature:()=>m,intS:()=>Ne,literalS:()=>ve,objectS:()=>F,recursiveS:()=>fe,stringS:()=>Oe,tabularInput:()=>je,transformToArray:()=>re});module.exports=me(Ee);var J="Not implemented",A=class extends Error{constructor(){super(J)}},W="Null not allowed",f=class extends Error{constructor(){super(W)}},X="Integer out of bounds",g=class extends Error{constructor(){super(X)}},z="Invalid number",h=class extends Error{constructor(){super(z)}},G="Invalid date",x=class extends Error{constructor(){super(G)}},Y="Invalid boolean",p=class extends Error{constructor(){super(Y)}},q="Field missing",T=class extends Error{constructor(){super(q)}},H="JSON Array not found",b=class extends Error{constructor(){super(H)}},Q="The source is not an object",y=class extends Error{constructor(){super(Q)}};var u=ue(require("json-bigint")),O=class{constructor(a){this.definition=a;this.get=a=>this.definition[a];this.forEach=a=>{Object.keys(this.definition).forEach(e=>a(e,this.definition[e]))};this.map=a=>Object.keys(this.definition).map(e=>a(e,this.definition[e]));this.filter=a=>Object.keys(this.definition).filter(e=>a(e,this.definition[e])).map(e=>({key:e,schema:this.definition[e]}))}get size(){return Object.keys(this.definition).length}},M=class{constructor(a,e=!0){this.notNullFlag=e;this.unbox=(a,e)=>{if(a===null||e?.keepNullString!==!0&&a==="null")throw new f;return this.#t(a,e)};this.extend=a=>{if(this.#e.dataType!=="object")throw new Error("Cannot extend non-object schema");return F({...this.#e.fields.definition,...a})};this.#e={...a.metadata,notNull:!0,optional:!1},this.#t=a.unbox}#e;#t;get metadata(){return this.#e}},v=class{constructor(a,e=!0){this.optionalFlag=e;this.unbox=(a,e)=>{if(!(!this.#e.hasDefaultRule&&(a===void 0||e?.keepUndefinedString===!1&&a==="undefined")))try{return this.#t(a,e)}catch(n){if(a===void 0)return;throw n}};this.extend=a=>{if(this.#e.dataType!=="object")throw new Error("Cannot extend non-object schema");return F({...this.#e.fields.definition,...a})};this.#e={...a.metadata,notNull:!1,optional:!0},this.#t=a.unbox}#e;#t;get metadata(){return this.#e}},j=class{constructor(a,e,n){this.condition=n;this.#a=void 0;this.unbox=(a,e)=>this.condition(a)?this.targetCheck(a):this.#t(a,e);this.#e=this.#e={...a.metadata,hasDefaultRule:!0},this.#t=a.unbox,this.targetCheck=typeof e=="function"?this.targetCheck=e:e instanceof Error?this.targetCheck=r=>{throw e}:r=>e}#e;#t;get metadata(){return this.#e}#a;get optional(){return this.#a||(this.#a=new v(this)),this.#a}},d=class{constructor(){this.unbox=(a,e)=>{if(a===null||e?.keepNullString!==!0&&a==="null")return null;if(a===void 0||e?.keepUndefinedString===!1&&a==="undefined")throw new T;return this.convert(a,e)};this.#e=void 0;this.#t=void 0;this.byDefault=(a,e=n=>n==null)=>new j(this,a,e)}#e;get notNull(){return this.#e||(this.#e=new M(this)),this.#e}#t;get optional(){return this.#t||(this.#t=new v(this)),this.#t}},Z=t=>`{${t.map((a,e)=>`${a}:${m(e)}`).join(",")}}`,te=t=>t.metadata?.dataType!==void 0,Se=t=>t.metadata.dataType==="object",he=t=>t.metadata.dataType==="array",pe=t=>t.metadata.dataType==="dictionary",ee=t=>te(t)?Se(t)?Z(t.metadata.fields):he(t)?`${m(t.metadata.elements)}[]`:pe(t)?`{[string]:${m(t.metadata.values)}}`:t.metadata.dataType:Z(new O(t)),m=t=>te(t)?`${ee(t)}${t.metadata.notNull?".NN":t.metadata.optional?".OPT":""}${t.metadata.hasDefaultRule?".DEF":""}`:ee(t),fe={isRecursive:!0,metadata:{dataType:"recursive",notNull:!1,optional:!0},unbox:()=>{throw new Error("Recursive schema cannot be unboxed directly")}},N=class extends d{constructor(e){super();this.convert=(e,n)=>{let r=typeof e=="string"?u.default.parse(e):e,c={};return this._metadata.fields.forEach((i,s)=>{try{let o=r[i],l;if(s.metadata.dataType==="recursive"){if(o==null)return;l=this.unbox(o,n)}else l=s.unbox(o,n);if(l===void 0)return;c[i]=l}catch(o){let l=u.default.stringify(r[i]);throw new Error(`Unboxing ${i}, value: ${l}: ${o.message}`)}}),c};this.extend=e=>F({...this._metadata.fields.definition,...e});this._metadata={dataType:"object",fields:new O(e),notNull:!1,optional:!1}}get metadata(){return this._metadata}},E=class t{constructor(){this.#e={};this.getOrCreateObject=a=>{let e=m(a);return e.indexOf(".DEF")>0?new N(a):(this.#e[e]||(this.#e[e]=new N(a)),this.#e[e])}}#e;static#t=new t;static get instance(){return this.#t}},ge=E.instance,F=t=>ge.getOrCreateObject(t),w=class extends d{constructor(e){super();this.elements=e;this.convert=(e,n)=>{let r=typeof e=="string"?u.default.parse(e):e;if(!Array.isArray(r))throw new b;return r.map((c,i)=>{try{return this.elements.unbox(c,n)}catch(s){let o=u.default.stringify(c);throw new Error(`Unboxing array element ${i}, value: ${o}: ${s.message}`)}})}}get metadata(){return{dataType:"array",elements:this.elements,notNull:!1,optional:!1}}},I=class t{constructor(){this.#e={};this.getOrCreateArray=a=>{let e=m(a);return e.indexOf(".DEF")>0?new w(a):(this.#e[e]||(this.#e[e]=new w(a)),this.#e[e])}}#e;static#t=new t;static get instance(){return this.#t}},xe=I.instance,Te=t=>xe.getOrCreateArray(t),B=class extends d{constructor(e){super();this.values=e;this.convert=(e,n)=>{let r=typeof e=="string"?u.default.parse(e):e;if(typeof r!="object"||Array.isArray(r))throw new y;return Object.keys(r).reduce((c,i)=>{try{c[i]=this.values.unbox(r[i],n)}catch(s){let o=u.default.stringify(r[i]);throw new Error(`Unboxing dictionary element ${i}, value: ${o}: ${s.message}`)}return c},{})}}get metadata(){return{dataType:"dictionary",values:this.values,notNull:!1,optional:!1}}},$=class t{constructor(){this.#e={};this.getOrCreateDictionary=a=>{let e=m(a);return e.indexOf(".DEF")>0?new B(a):(this.#e[e]||(this.#e[e]=new B(a)),this.#e[e])}}#e;static#t=new t;static get instance(){return this.#t}},be=$.instance,ye=t=>be.getOrCreateDictionary(t);var ae=t=>t.replace(/[\.|,][0-9]*$/,""),S=t=>({dataType:t,notNull:!1,optional:!1}),_=class extends d{constructor(){super(...arguments);this._metadata=S("bigint");this.convert=e=>typeof e=="bigint"?e:BigInt(typeof e=="string"?ae(e):typeof e=="number"?Math.floor(e):ae(`${e}`))}get metadata(){return this._metadata}},De=new _,R=class extends d{constructor(){super(...arguments);this._metadata=S("string");this.convert=e=>typeof e=="string"?e:`${e}`}get metadata(){return this._metadata}},Oe=new R,K=class extends d{constructor(e){super();this.convert=e=>{if(!this.values.includes(e))throw new Error(`Invalid value for literal type: ${e}, must be one of ${this.values.join("|")}`);return e};this.values=e,this._metadata=S(`literal(${e.join("|")})`)}get metadata(){return this._metadata}},ve=(...t)=>new K(t),P=class extends d{constructor(){super(...arguments);this._metadata=S("int");this.convert=e=>{let n=Number(e);if(Number.isNaN(n))throw new h;let r=Number.isInteger(n)?n:Math.floor(n);if(!Number.isSafeInteger(r))throw new g;return r}}get metadata(){return this._metadata}},Ne=new P,V=class extends d{constructor(){super(...arguments);this._metadata=S("float");this.convert=e=>{let n=Number(e);if(Number.isNaN(n))throw new h;return n}}get metadata(){return this._metadata}},we=new V,C=class extends d{constructor(){super(...arguments);this._metadata=S("date");this.convert=e=>{if(typeof e=="string"){let n=e===""?Date.now():Date.parse(e);if(Number.isNaN(n))throw new x;return new Date(n)}return e}}get metadata(){return this._metadata}},Be=new C,U=class extends d{constructor(){super(...arguments);this._metadata=S("bool");this.convert=e=>{if(typeof e=="string"){if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;throw new p}if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1;throw new p}return e}}get metadata(){return this._metadata}},Fe=new U;var Ae=()=>!0;var L=class{constructor(a,e){this.extractMetadata=(a,e,n,r)=>{let c={};return Object.keys(a).forEach(i=>{let s=a[i];if(typeof s.args=="object")Object.keys(s).forEach(o=>{if(!["args","retVal","hidden"].includes(o))throw new Error(`Invalid field ${o} in ${e}/${i}`)}),c[i]={...a[i],name:i,path:`${n}${e}/${i}`,metadata:{dataType:"function",args:s.args,retVal:s.retVal,name:i,path:`${n}${e}/${i}`,hidden:s.hidden??r.hidden}};else{let o=this.extractMetadata(s,i,`${n}${e}/`,r);c[i]={...o.implementation,name:i,path:`${n}${e}/${i}`,metadata:o}}}),{dataType:"api",implementation:c,name:e,path:`${n}${e}`,hidden:r.hidden}};this._metadata=this.extractMetadata(a,"","",e)}get metadata(){return this._metadata}},Me=(t,a={})=>new L(t,a);var ne=t=>t.match(/(?:[^\s"']+|['"][^'"]*["'])+/g),re=(t,a)=>{let e=t.split(/[\r\n]+/);for(;e.length>0&&e[0].trim().length===0;)e.shift();if(e.length===0)throw new Error("Table must have at least a header");let n=ne(e[0]);return e.shift(),e.filter(r=>r.trim()!=="").map((r,c)=>{let i=ne(r);return n.reduce((s,o,l)=>{if(!i[l])throw console.table(i),new Error(`Table column ${l+1} missing in row ${c+1}`);return s[o]=i[l]==="null"?null:i[l]==="undefined"?void 0:i[l].replace(/(^")|("$)/g,""),s},structuredClone(a)??{})})},je=(t,a,e)=>re(a,e).map(n=>t.unbox(n,{keepNullString:!0,keepUndefinedString:!0}));