typescript-json-serializer
Version:
Typescript library to serialize classes into json and deserialize json into classes.
2 lines (1 loc) • 13.7 kB
JavaScript
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");require("reflect-metadata");var t=function(){function e(){}return e.getBaseClass=function(e){return e?Reflect.getPrototypeOf(e):void 0},e.getJsonPropertiesMetadata=function(t,r){if(t){var i=""+e.apiMap+(r||t.constructor.name);return Reflect.getMetadata(i,t)}},e.getParamTypes=function(t){return t?Reflect.getMetadata(e.designParamTypes,t):void 0},e.getJsonObjectMetadata=function(t){return t?Reflect.getMetadata(e.apiMapJsonObject,t):void 0},e.getType=function(t,r){return t?Reflect.getMetadata(e.designType,t,r):void 0},e.isJsonObject=function(t){return!!t&&Reflect.hasOwnMetadata(e.apiMapJsonObject,t)},e.setJsonPropertiesMetadata=function(t,r){if(r){var i=""+e.apiMap+r.constructor.name;Reflect.defineMetadata(i,t,r)}},e.setJsonObject=function(t,r){r&&Reflect.defineMetadata(e.apiMapJsonObject,t,r)},e.setType=function(t,r,i){r&&t&&Reflect.defineMetadata(e.designType,t,r,i)},e.apiMap="api:map:",e.apiMapJsonObject=e.apiMap+"jsonObject",e.designType="design:type",e.designParamTypes="design:paramtypes",e}(),r=function(e){return"string"==typeof e},i=function(e){return null!==e&&"object"==typeof e&&!o(e)},o=function(e){return Array.isArray(e)},n=function(e){return"[object Date]"===toString.call(e)},a=function(e){return t.isJsonObject(e)},s=function(e){return[null,void 0].includes(e)},l=function(e){return e instanceof Set},u=function(e){try{var t=JSON.parse(e);return"object"==typeof t?t:e}catch(t){return e}},c=function(e,t){return e.filter((function(e){return!t.some((function(t){return e===t}))}))},p=function(){this.errorCallback=d,this.nullishPolicy={undefined:"remove",null:"allow"},this.additionalPropertiesPolicy="remove"},d=function(e){console.error(e)},y=function(){function d(t){this.options=new p,this.options=e.__assign(e.__assign({},this.options),t)}return d.prototype.deserialize=function(e,t){return r(e)&&(e=u(e)),o(e)?this.deserializeObjectArray(e,t):i(e)?this.deserializeObject(e,t):void this.error("Fail to deserialize: value is not an Array nor an Object.\nReceived: "+JSON.stringify(e)+".")},d.prototype.deserializeObject=function(o,n){var a,l=this;if(null===o)return"disallow"===this.options.nullishPolicy.null&&this.error("Fail to deserialize: null is not assignable to type Object."),null;if(void 0!==o){if(r(o)&&(o=u(o)),i(o)){var p;if(function(e){if("function"!=typeof e)return!1;try{Reflect.construct(String,[],e)}catch(e){return!1}return!0}(n)){var d=Object.create(n.prototype),y=t.getJsonObjectMetadata(d.constructor),f=null!==(a=null==y?void 0:y.constructorParams)&&void 0!==a?a:[];p=new(n.bind.apply(n,e.__spreadArray([void 0],f)))}else p=n;var v=this.getJsonPropertiesMetadata(p);if(!v)return p;var h=Object.keys(v);if(h.forEach((function(e){var t=v[e],r=l.deserializeProperty(p,e,o,t);l.checkRequiredProperty(t,p,e,r,o,!1);var i=p[e];r===i||(null!==r||void 0!==i)&&s(r)||(i=r),l.isAllowedProperty(e,i)&&(p[e]=i)})),"remove"===this.options.additionalPropertiesPolicy)return p;var g=c(Object.keys(o),h);return g.length?("disallow"===this.options.additionalPropertiesPolicy?this.error("Additional properties detected in "+JSON.stringify(o)+": "+g+"."):"allow"===this.options.additionalPropertiesPolicy&&g.forEach((function(e){return p[e]=o[e]})),p):p}this.error("Fail to deserialize: type '"+typeof o+"' is not assignable to type 'Object'.\nReceived: "+JSON.stringify(o))}else"disallow"===this.options.nullishPolicy.undefined&&this.error("Fail to deserialize: undefined is not assignable to type Object.")},d.prototype.deserializeObjectArray=function(e,t){var i=this;if(null===e)return"disallow"===this.options.nullishPolicy.null&&this.error("Fail to deserialize: null is not assignable to type Array."),null;if(void 0!==e){if(r(e)&&(e=u(e)),o(e))return e.reduce((function(e,r){var o=i.deserializeObject(r,t);return(!s(o)||null===o&&"remove"!==i.options.nullishPolicy.null||void 0===o&&"remove"!==i.options.nullishPolicy.undefined)&&e.push(o),e}),[]);this.error("Fail to deserialize: type '"+typeof e+"' is not assignable to type 'Array'.\nReceived: "+JSON.stringify(e))}else"disallow"===this.options.nullishPolicy.undefined&&this.error("Fail to deserialize: undefined is not assignable to type Array.")},d.prototype.serialize=function(e){return o(e)?this.serializeObjectArray(e):i(e)?this.serializeObject(e):void this.error("Fail to serialize: value is not an Array nor an Object.\nReceived: "+JSON.stringify(e)+".")},d.prototype.serializeObject=function(e){var t=this;if(null===e)return"disallow"===this.options.nullishPolicy.null&&this.error("Fail to serialize: null is not assignable to type Object."),null;if(void 0!==e){if(!i(e))return e;var r=this.getJsonPropertiesMetadata(e);if(!r)return e;var n={},a=Object.keys(e),s=Object.keys(r);if(s.forEach((function(i){var s=r[i];if(a.includes(i)){var l=void 0;s.beforeSerialize&&(l=e[i],e[i]=s.beforeSerialize(e[i],e));var u=t.serializeProperty(e,i,s);if(s.afterSerialize&&(u=s.afterSerialize(u,e)),e[i]=l||e[i],o(s.name))s.name.forEach((function(e){t.isAllowedProperty(e,u[e])&&(n[e]=u[e])}));else if(t.checkRequiredProperty(s,e,i,u,e),t.isAllowedProperty(i,u))if(s.isNameOverridden||void 0===t.options.formatPropertyName)n[s.name]=u;else{var c=t.options.formatPropertyName(s.name);n[c]=u}}else o(s.name)?s.name.forEach((function(e){t.isAllowedProperty(e,void 0)&&(n[e]=void 0)})):(t.checkRequiredProperty(s,e,i,void 0,e),t.isAllowedProperty(i,void 0)&&(n[s.name]=void 0))})),"remove"===this.options.additionalPropertiesPolicy)return n;var l=c(a,s);return l.length?("disallow"===this.options.additionalPropertiesPolicy?this.error("Additional properties detected in "+JSON.stringify(e)+": "+l+"."):"allow"===this.options.additionalPropertiesPolicy&&l.forEach((function(t){return n[t]=e[t]})),n):n}"disallow"===this.options.nullishPolicy.undefined&&this.error("Fail to serialize: undefined is not assignable to type Object.")},d.prototype.serializeObjectArray=function(e){var t=this;if(null===e)return"disallow"===this.options.nullishPolicy.null&&this.error("Fail to serialize: null is not assignable to type Array."),null;if(void 0!==e){if(o(e))return e.reduce((function(e,r){var i=t.serializeObject(r);return(!s(i)||null===i&&"remove"!==t.options.nullishPolicy.null||void 0===i&&"remove"!==t.options.nullishPolicy.undefined)&&e.push(i),e}),[]);this.error("Fail to serialize: type '"+typeof e+"' is not assignable to type 'Array'.\nReceived: "+JSON.stringify(e)+".")}else"disallow"===this.options.nullishPolicy.undefined&&this.error("Fail to serialize: undefined is not assignable to type Array.")},d.prototype.checkRequiredProperty=function(e,t,r,i,o,n){if(void 0===n&&(n=!0),e.required&&s(i)&&s(t[r])){var a=t.constructor.name;this.error("Fail to "+(n?"serialize":"deserialize")+": Property '"+r+"' is required in "+a+" "+JSON.stringify(o)+".")}},d.prototype.deserializeProperty=function(e,r,i,o){if(!s(i)){var n=this.getDataSource(i,o,this.options.formatPropertyName);if(s(n))return n;var l,u=t.getType(e,r),c=this.getDataStructureInformation(u,e[r],o),p=c.isArrayProperty,d=c.isSetProperty,y=c.isMapProperty,f=c.isDictionaryProperty,v=o.type||u;o.beforeDeserialize&&(n=o.beforeDeserialize(n,e));var h=o.predicate;return f||y?(l=this.deserializeDictionary(n,v,h),y&&(l=new Map(Object.entries(l)))):p||d?(l=this.deserializeArray(n,v,h),d&&(l=new Set(l))):!a(v)&&!h||h&&!h(n,i)?l=this.deserializePrimitive(n,v.name):(v=o.predicate?o.predicate(n,i):v,l=this.deserializeObject(n,v)),o.afterDeserialize&&(l=o.afterDeserialize(l,e)),l}},d.prototype.deserializePrimitive=function(e,t){if(s(t))return e;if(typeof e===(t=t.toLowerCase()))return e;var r="Fail to deserialize: type '"+typeof e+"' is not assignable to type '"+t+"'.\nReceived: "+JSON.stringify(e);switch(t){case"string":var i=e.toString();return"[object Object]"===i?void this.error(r):i;case"number":return function(e){return"number"==typeof e}(e)?+e:void this.error(r);case"boolean":return void this.error(r);case"date":return function(e){return!n(e)&&!o(e)&&!isNaN(Date.parse(e))}(e)?new Date(e):void this.error(r);default:return e}},d.prototype.deserializeDictionary=function(e,t,r){var n=this;if(i(e)){var a={};return Object.keys(e).forEach((function(i){var s=e[i];a[i]=o(s)?s.map((function(i){return n.deserializeDictionaryProperty(e,i,t,r)})):n.deserializeDictionaryProperty(e,s,t,r)})),a}this.error("Fail to deserialize: type '"+typeof e+"' is not assignable to type 'Dictionary'.\nReceived: "+JSON.stringify(e)+".")},d.prototype.deserializeDictionaryProperty=function(e,t,r,i){var o=i?i(t,e):void 0;return a(r)||o?this.deserializeObject(t,o||r):this.deserializePrimitive(t,typeof t)},d.prototype.deserializeArray=function(e,t,r){var i=this;if(o(e))return e.reduce((function(o,n){var l;return a(t)||r?(t=r?r(n,e):t,l=i.deserializeObject(n,t)):l=i.deserializePrimitive(n,typeof n),(!s(l)||null===l&&"remove"!==i.options.nullishPolicy.null||void 0===l&&"remove"!==i.options.nullishPolicy.undefined)&&o.push(l),o}),[]);this.error("Fail to deserialize: type '"+typeof e+"' is not assignable to type 'Array'.\nReceived: "+JSON.stringify(e))},d.prototype.error=function(e){this.options.errorCallback&&this.options.errorCallback(e)},d.prototype.getClassesJsonPropertiesMetadata=function(e,r){return e?e.reduce((function(e,i){var o=t.getJsonPropertiesMetadata(r,i);return o&&e.push(o),e}),[]):[]},d.prototype.getDataSource=function(e,t,r){var i=t.name,n=t.isNameOverridden;if(o(i)){var a={};return i.forEach((function(t){return a[t]=e[t]})),a}return!n&&r?(i=r(i),e[i]):e[i]},d.prototype.getDataStructureInformation=function(e,t,r){var i,n,a,s,u;if(r.dataStructure)return{isArrayProperty:null!==(i="array"===r.dataStructure)&&void 0!==i&&i,isDictionaryProperty:null!==(n="dictionary"===r.dataStructure)&&void 0!==n&&n,isMapProperty:null!==(a="map"===r.dataStructure)&&void 0!==a&&a,isSetProperty:null!==(s="set"===r.dataStructure)&&void 0!==s&&s};var c,p=null===(u=null==e?void 0:e.name)||void 0===u?void 0:u.toLowerCase();return"object"===p?{isArrayProperty:o(t),isDictionaryProperty:!1,isMapProperty:(c=t,c instanceof Map),isSetProperty:l(t)}:{isArrayProperty:"array"===p,isDictionaryProperty:!1,isMapProperty:"map"===p,isSetProperty:"set"===p}},d.prototype.getJsonPropertiesMetadata=function(r){var i,o=(null!==(i=t.getJsonObjectMetadata(r.constructor))&&void 0!==i?i:{}).baseClassNames,n=t.getJsonPropertiesMetadata(r);if(!(n||o&&o.length))return n;if(o&&o.length){var a=this.getClassesJsonPropertiesMetadata(o,r);return this.mergeJsonPropertiesMetadata.apply(this,e.__spreadArray(e.__spreadArray([],a),[n]))}return n},d.prototype.isAllowedProperty=function(e,t){if(s(t)){if("disallow"===this.options.nullishPolicy[""+t])return this.error("Disallowed "+t+" value detected: "+e+"."),!1;if("remove"===this.options.nullishPolicy[""+t])return!1}return!0},d.prototype.mergeJsonPropertiesMetadata=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i={};return t.forEach((function(t){t&&Object.keys(t).forEach((function(r){i[r]=e.__assign(e.__assign({},i[r]),t[r])}))})),i},d.prototype.serializeDictionary=function(e){var t=this;if(i(e))return Object.keys(e).reduce((function(r,i){var n=e[i];return r[i]=o(n)?t.serializeObjectArray(n):t.serializeObject(n),r}),{});this.error("Fail to serialize: type '"+typeof e+"' is not assignable to type 'Dictionary'.\nReceived: "+JSON.stringify(e)+".")},d.prototype.serializeProperty=function(e,i,o){var s,l=this,u=e[i],c=t.getType(e,i),p=this.getDataStructureInformation(c,u,o),d=p.isArrayProperty,y=p.isDictionaryProperty,f=p.isMapProperty,v=p.isSetProperty,h=o.predicate,g=o.type||c,P=a(g);if(u&&(P||h)){if(d||v){var b=v?Array.from(u):u;return this.serializeObjectArray(b)}if(y||f){if(!f)return this.serializeDictionary(u);var m={};return u.forEach((function(e,t){r(t)?m[t]=e:l.error("Fail to serialize: type of '"+typeof t+"' is not assignable to type 'string'.\nReceived: "+JSON.stringify(t)+".")})),this.serializeDictionary(m)}return this.serializeObject(u)}return"date"===(null===(s=null==g?void 0:g.name)||void 0===s?void 0:s.toLocaleLowerCase())&&n(u)?u.toISOString():u},d}(),f=function(r){var i=t.getBaseClass(r);return i&&i.name?e.__spreadArray(e.__spreadArray([],f(i)),[i.name]):[]},v=function(e){var t,r=e.toString().split("}")[0].replace(/(\/\*[\s\S]*?\*\/|\/\/.*$)/gm,"").replace(/[\r\t\n\v\f ]/g,""),i=r.length;","===r[i-2]&&(t=r[i-1]);var o=t?new RegExp("(?:(this|"+t+"|\\("+t+"=t.call\\(this(,.)*\\)\\))\\.)([^,;\n}]+)","gm"):new RegExp("(?:(this)\\.)([^,;\n}]+)","gm"),n=new Map,a=/(?:.*(?:constructor|function).*?(?=\())(?:\()(.+?(?=\)))/m.exec(r);if(!a||!a.length)return n;for(var s,l=a[1].split(","),u=function(){var e=s.length-1,t=s[e].split("="),r=l.findIndex((function(e){return e===t[1]}));r>-1&&n.set(r,t[0])};s=o.exec(r);)u();return n},h=function(o,n){var a={name:o.toString()};return n?r(n)?(a.name=n,a.isNameOverridden=!0,a):(i(n)&&(a=e.__assign(e.__assign({},a),n),n.name&&(a.name=n.name,a.isNameOverridden=!0),function(e){if(!e)return!1;var r=t.getParamTypes(e),i=e.length;return(1===i||2===i)&&!r}(n.type)&&(delete a.type,a.predicate=n.type)),a):a};exports.JsonObject=function(e){return function(r){var i,o=f(r),n=null!==(i=null==e?void 0:e.constructorParams)&&void 0!==i?i:[];t.setJsonObject({baseClassNames:o,constructorParams:n},r)}},exports.JsonProperty=function(e){return function(r,i,o){var n;if(void 0===i&&r.prototype){var a=t.getParamTypes(r)[o];i=v(r.prototype.constructor).get(o),r=r.prototype,t.setType(a,r,i)}var s=null!==(n=t.getJsonPropertiesMetadata(r))&&void 0!==n?n:{};s[i]=h(i,e),t.setJsonPropertiesMetadata(s,r)}},exports.JsonSerializer=y,exports.JsonSerializerOptions=p,exports.isNullish=s,exports.logError=d,exports.throwError=function(e){throw new Error(e)};