Comparing version 5.18.1 to 5.18.2
# typeson CHANGES | ||
## 5.18.2 | ||
- Fix: Avoid treating recurring primitive values as cyclic | ||
- Linting (ESLint): As per latest ash-nazg | ||
- npm: Bump devDeps, peerDeps | ||
## 5.18.1 | ||
@@ -4,0 +10,0 @@ |
@@ -1,1 +0,1 @@ | ||
"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _iterableToArrayLimit(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var n=[],r=!0,o=!1,i=void 0;try{for(var a,s=e[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==s.return||s.return()}finally{if(o)throw i}}return n}}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}var TypesonPromise=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};TypesonPromise.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(TypesonPromise.prototype[Symbol.toStringTag]="TypesonPromise"),TypesonPromise.prototype.then=function(e,t){var n=this;return new TypesonPromise((function(r,o){n.p.then((function(t){r(e?e(t):t)})).catch((function(e){return t?t(e):Promise.reject(e)})).then(r,o)}))},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise((function(t){t(e)}))},TypesonPromise.reject=function(e){return new TypesonPromise((function(t,n){n(e)}))},["all","race"].forEach((function(e){TypesonPromise[e]=function(t){return new TypesonPromise((function(n,r){Promise[e](t.map((function(e){return e.p}))).then(n,r)}))}}));var _ref={},toStr=_ref.toString,hasOwn={}.hasOwnProperty,getProto=Object.getPrototypeOf,fnToString=hasOwn.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return toStr.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var n=getProto(e);if(!n)return null===t;var r=hasOwn.call(n,"constructor")&&n.constructor;return"function"!=typeof r?null===t:t===r||(null!==t&&fnToString.call(r)===fnToString.call(t)||"function"==typeof t&&"string"==typeof r.__typeson__type__&&r.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!getProto(e)||hasConstructorOf(e,Object))}function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=getProto(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)}var keys=Object.keys,isArray=Array.isArray,hasOwn$1={}.hasOwnProperty,internalStateObjPropsToIgnore=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g)||0,r=t.keypath.match(/\./g)||0;return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var Typeson=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return _createClass(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var o=this.encapsulate(e,null,r);return isArray(o)?JSON.stringify(o[0],t,n):o.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(e,t,n){var r=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,o=this,i={},a=[],s=[],c=[],u=!("cyclic"in n)||n.cyclic,p=n.encapsulateObserver,y=_encapsulate("",e,u,t||{},c);function finish(e){var t=Object.values(i);if(n.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!hasOwn$1.call(e,"$types")?e.$types=i:e={$:e,$types:{$:i}}}else isObject(e)&&hasOwn$1.call(e,"$types")&&(e={$:e,$types:!0});return!n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=internalStateObjPropsToIgnore.map((function(t){var n=e[t];return delete e[t],n}));n(),internalStateObjPropsToIgnore.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(e,t,r,c,u,y,l){var f,h={},v=_typeof(t),d=p?function(n){var o=l||c.type||Typeson.getJSONType(t);p(Object.assign(n||h,{keypath:e,value:t,cyclic:r,stateObj:c,promisesData:u,resolvingTypesonPromise:y,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},{type:o}))}:null;if(["string","boolean","number","undefined"].includes(v))return void 0===t||"number"===v&&(isNaN(t)||t===-1/0||t===1/0)?(f=replace(e,t,c,u,!1,y,d))!==t&&(h={replaced:f}):f=t,d&&d(),f;if(null===t)return d&&d(),t;if(r&&!c.iterateIn&&!c.iterateUnsetNumeric){var b=a.indexOf(t);if(!(b<0))return i[e]="#",d&&d({cyclicKeypath:s[b]}),"#"+s[b];!0===r&&(a.push(t),s.push(e))}var O,m=isPlainObject(t),T=isArray(t),P=(m||T)&&(!o.plainObjectReplacers.length||c.replaced)||c.iterateIn?t:replace(e,t,c,u,m||T,null,d);if(P!==t?(f=P,h={replaced:P}):T&&"object"!==c.iterateIn||"array"===c.iterateIn?(O=new Array(t.length),h={clone:O}):""===e&&hasConstructorOf(t,TypesonPromise)?(u.push([e,t,r,c,void 0,void 0,c.type]),f=t):(["function","symbol"].includes(_typeof(t))||"toJSON"in t||hasConstructorOf(t,TypesonPromise)||hasConstructorOf(t,Promise)||hasConstructorOf(t,ArrayBuffer))&&!m&&"object"!==c.iterateIn?f=t:(O={},c.addLength&&(O.length=t.length),h={clone:O}),d&&d(),n.iterateNone)return O||f;if(!O)return f;if(c.iterateIn){var g=function _loop(n){var o={ownKeys:hasOwn$1.call(t,n)};_adaptBuiltinStateObjectProperties(c,o,(function(){var o=e+(e?".":"")+escapeKeyPathComponent(n),i=_encapsulate(o,t[n],Boolean(r),c,u,y);hasConstructorOf(i,TypesonPromise)?u.push([o,i,Boolean(r),c,O,n,c.type]):void 0!==i&&(O[n]=i)}))};for(var _ in t)g(_);d&&d({endIterateIn:!0,end:!0})}else keys(t).forEach((function(n){var o=e+(e?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},(function(){var e=_encapsulate(o,t[n],Boolean(r),c,u,y);hasConstructorOf(e,TypesonPromise)?u.push([o,e,Boolean(r),c,O,n,c.type]):void 0!==e&&(O[n]=e)}))})),d&&d({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var j=t.length,S=function _loop2(n){if(!(n in t)){var o=e+(e?".":"")+n;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},(function(){var e=_encapsulate(o,void 0,Boolean(r),c,u,y);hasConstructorOf(e,TypesonPromise)?u.push([o,e,Boolean(r),c,O,n,c.type]):void 0!==e&&(O[n]=e)}))}},w=0;w<j;w++)S(w);d&&d({endIterateUnsetNumeric:!0,end:!0})}return O}function replace(e,t,n,a,s,c,p){for(var y=s?o.plainObjectReplacers:o.nonplainObjectReplacers,l=y.length;l--;){var f=y[l];if(f.test(t,n)){var h=f.type;if(o.revivers[h]){var v=i[e];i[e]=v?[h].concat(v):h}return Object.assign(n,{type:h,replaced:!0}),!r&&f.replaceAsync||f.replace?(p&&p({replacing:!0}),_encapsulate(e,f[r||!f.replaceAsync?"replace":"replaceAsync"](t,n),u&&"readonly",n,a,c,h)):(p&&p({typeDetected:!0}),_encapsulate(e,t,u&&"readonly",n,a,c,h))}}return t}return c.length?r&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(e,t){var n;return regeneratorRuntime.async((function checkPromises$(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,regeneratorRuntime.awrap(Promise.all(t.map((function(e){return e[1].p}))));case 2:return n=r.sent,r.next=5,regeneratorRuntime.awrap(Promise.all(n.map((function _callee(n){var r,o,i,a,s,c,u,p,y,l,f,h,v,d;return regeneratorRuntime.async((function _callee$(b){for(;;)switch(b.prev=b.next){case 0:if(r=[],o=t.splice(0,1),i=_slicedToArray(o,1),a=i[0],s=_slicedToArray(a,7),c=s[0],u=s[2],p=s[3],y=s[4],l=s[5],f=s[6],h=_encapsulate(c,n,u,p,r,!0,f),v=hasConstructorOf(h,TypesonPromise),!c||!v){b.next=11;break}return b.next=8,regeneratorRuntime.awrap(h.p);case 8:return d=b.sent,y[l]=d,b.abrupt("return",checkPromises(e,r));case 11:return c?y[l]=h:e=v?h.p:h,b.abrupt("return",checkPromises(e,r));case 13:case"end":return b.stop()}}))}))));case 5:return r.abrupt("return",e);case 6:case"end":return r.stop()}}))}(y,c)).then(finish):!r&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&r?[finish(y)]:r?finish(y):Promise.resolve(finish(y))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(e,t){var n=e&&e.$types;if(!n)return e;if(!0===n)return e.$;var r=(t=_objectSpread2({sync:!0},this.options,{},t)).sync,o=[],i={},a=!0;n.$&&isPlainObject(n.$)&&(e=e.$,n=n.$,a=!1);var s=this;function executeReviver(e,t,n){if(hasConstructorOf(t,TypesonPromise))return t.then((function(t){return n(t,e)}));var o=_slicedToArray(s.revivers[e]||[],1)[0];if(!o)throw new Error("Unregistered type: "+e);return!r||"revive"in o?o[r&&o.revive?"revive":!r&&o.reviveAsync?"reviveAsync":"revive"](t,i):t}function _revive(e,t,r,i,s){if(!a||"$types"!==e){var c=n[e];if(isArray(t)||isPlainObject(t)){var u=isArray(t)?new Array(t.length):{};for(keys(t).forEach((function(n){var o=_revive(e+(e?".":"")+escapeKeyPathComponent(n),t[n],r||u,u,n);hasConstructorOf(o,Undefined)?u[n]=void 0:void 0!==o&&(u[n]=o)})),t=u;o.length;){var p=_slicedToArray(o[0],4),y=p[0],l=p[1],f=p[2],h=p[3],v=getByKeyPath(y,l);if(hasConstructorOf(v,Undefined))f[h]=void 0;else{if(void 0===v)break;f[h]=v}o.splice(0,1)}}if(!c)return t;if("#"===c){var d=getByKeyPath(r,t.slice(1));return void 0===d&&o.push([r,t.slice(1),i,s]),d}return[].concat(c).reduce((function reducer(e,t){return executeReviver(t,e,reducer)}),t)}}function checkUndefined(e){return hasConstructorOf(e,Undefined)?void 0:e}var c,u=function revivePlainObjects(){var t=[];if(Object.entries(n).forEach((function(e){var r=_slicedToArray(e,2),o=r[0],i=r[1];"#"!==i&&[].concat(i).forEach((function(e){_slicedToArray(s.revivers[e]||[null,{}],2)[1].plain&&(t.push({keypath:o,type:e}),delete n[o])}))})),t.length)return t.sort(nestedPathsFirst).reduce((function reducer(t,n){var r=n.keypath,o=n.type;if(hasConstructorOf(t,TypesonPromise))return t.then((function(e){return reducer(e,o)}));var i=getByKeyPath(e,r);void 0!==(i=executeReviver(o,i,reducer))&&(hasConstructorOf(i,Undefined)&&(i=void 0),setAtKeyPath(e,r,i)===i&&(e=i))}),void 0)}();return isThenable(c=hasConstructorOf(u,TypesonPromise)?u.then((function(){return _revive("",e,null)})):_revive("",e,null))?r&&t.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(c,TypesonPromise)?c.p.then(checkUndefined):c:!r&&t.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r?checkUndefined(c):Promise.resolve(checkUndefined(c))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(isArray(e))return e.map((function(e){return R.call(n,e)}));e&&keys(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],o=r&&r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,i=o.filter((function(e){return e.type===n}));if(i.length&&(o.splice(o.indexOf(i[0]),1),delete this.revivers[n],delete this.types[n]),"function"==typeof r){var a=r;r={test:function test(e){return e&&e.constructor===a},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(a.prototype),e)}}}else if(isArray(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}if(r&&r.test){var c={type:n,test:r.test.bind(r)};r.replace&&(c.replace=r.replace.bind(r)),r.replaceAsync&&(c.replaceAsync=r.replaceAsync.bind(r));var u="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(u,0,c):this.nonplainObjectReplacers.splice(u,0,c),r.revive||r.reviveAsync){var p={};r.revive&&(p.revive=r.revive.bind(r)),r.reviveAsync&&(p.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[p,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),Undefined=function Undefined(){_classCallCheck(this,Undefined)};Undefined.__typeson__type__="TypesonUndefined",Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=isUserObject,Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=getJSONType,Typeson.JSON_TYPES=["null","boolean","number","string","array","object"],module.exports=Typeson; | ||
"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function asyncGeneratorStep(e,t,n,r,o,a,i){try{var c=e[a](i),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(r,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function _next(e){asyncGeneratorStep(a,r,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(a,r,o,_next,_throw,"throw",e)}_next(void 0)}))}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,o=!1,a=void 0;try{for(var i,c=e[Symbol.iterator]();!(r=(i=c.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,a=e}finally{try{r||null==c.return||c.return()}finally{if(o)throw a}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,o){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,o)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,o=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var a=r(e);if(!a)return null===t;var i=n.call(a,"constructor")&&a.constructor;return"function"!=typeof i?null===t:t===i||(null!==t&&o.call(i)===o.call(t)||"function"==typeof t&&"string"==typeof i.__typeson__type__&&i.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}var a=Object.keys,i=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){if(""===e.keypath)return-1;var n=e.keypath.match(/\./g)||0,r=t.keypath.match(/\./g)||0;return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var o=this.encapsulate(e,null,r);return i(o)?JSON.stringify(o[0],t,n):o.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var o=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function checkPromises(e,t){return _checkPromises.apply(this,arguments)}function _checkPromises(){return(_checkPromises=_asyncToGenerator(regeneratorRuntime.mark((function _callee2(t,n){var r;return regeneratorRuntime.wrap((function _callee2$(o){for(;;)switch(o.prev=o.next){case 0:return o.next=2,Promise.all(n.map((function(e){return e[1].p})));case 2:return r=o.sent,o.next=5,Promise.all(r.map(function(){var r=_asyncToGenerator(regeneratorRuntime.mark((function _callee(r){var o,a,i,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.wrap((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(o=[],a=n.splice(0,1),i=_slicedToArray(a,1),c=i[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,o,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,v.p;case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,o));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,o));case 13:case"end":return O.stop()}}),_callee)})));return function(e){return r.apply(this,arguments)}}()));case 5:return o.abrupt("return",t);case 6:case"end":return o.stop()}}),_callee2)})))).apply(this,arguments)}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,o,s,f,h,d){var b,O={},_=_typeof(n),m=v?function(r){var a=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:o,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},{type:a}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=s.replaced?n:replace(t,n,s,f,!1,h,m))!==n&&(O={replaced:b}):b=n,m&&m(),b;if(null===n)return m&&m(),n;if(o&&!s.iterateIn&&!s.iterateUnsetNumeric&&n&&"object"===_typeof(n)){var g=y.indexOf(n);if(!(g<0))return p[t]="#",m&&m({cyclicKeypath:l[g]}),"#"+l[g];!0===o&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=i(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,m);if(T!==n?(b=T,O={replaced:T}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,o,s,void 0,void 0,s.type]),b=n):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):(["function","symbol"].includes(_typeof(n))||"toJSON"in n||hasConstructorOf(n,e)||hasConstructorOf(n,Promise)||hasConstructorOf(n,ArrayBuffer))&&!P&&"object"!==s.iterateIn?b=n:(j={},s.addLength&&(j.length=n.length),O={clone:j}),m&&m(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var a={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,a,(function(){var a=t+(t?".":"")+escapeKeyPathComponent(r),i=_encapsulate(a,n[r],Boolean(o),s,f,h);hasConstructorOf(i,e)?f.push([a,i,Boolean(o),s,j,r,s.type]):void 0!==i&&(j[r]=i)}))};for(var A in n)w(A);m&&m({endIterateIn:!0,end:!0})}else a(n).forEach((function(r){var a=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(a,n[r],Boolean(o),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(o),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),m&&m({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var k=n.length,C=function _loop2(r){if(!(r in n)){var a=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(o),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(o),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},K=0;K<k;K++)C(K);m&&m({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,a,i,c){for(var s=a?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!o&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[o||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,i,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,i,f))}}return t}return f.length?o&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(checkPromises(d,f)).then(finish):!o&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&o?[finish(d)]:o?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var o=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function executeReviver(e,t){var n=_slicedToArray(y.revivers[e]||[],1)[0];if(!n)throw new Error("Unregistered type: "+e);return!o||"revive"in n?n[o&&n.revive?"revive":!o&&n.reviveAsync?"reviveAsync":"revive"](t,s):t}var l=[];function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var f,h=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),o=t[0],a=t[1];"#"!==a&&[].concat(a).forEach((function(e){_slicedToArray(y.revivers[e]||[null,{}],2)[1].plain&&(n.push({keypath:o,type:e}),delete r[o])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var o=r.keypath,a=r.type;if(isThenable(n))return n.then((function(e){return reducer(e,{keypath:o,type:a})}));var i=getByKeyPath(t,o);if(hasConstructorOf(i=executeReviver(a,i),e))return i.then((function(e){var n=setAtKeyPath(t,o,e);n===e&&(t=n)}));var c=setAtKeyPath(t,o,i);c===i&&(t=c)}),void 0)}();return hasConstructorOf(h,e)?f=h.then((function(){return t})):(f=function _revive(t,n,o,s,y){if(!u||"$types"!==t){var f=r[t],h=i(n);if(h||isPlainObject(n)){var v=h?new Array(n.length):{};for(a(n).forEach((function(r){var a=_revive(t+(t?".":"")+escapeKeyPathComponent(r),n[r],o||v,v,r),i=function set(e){return hasConstructorOf(e,p)?v[r]=void 0:void 0!==e&&(v[r]=e),e};hasConstructorOf(a,e)?l.push(a.then((function(e){return i(e)}))):i(a)})),n=v;c.length;){var d=_slicedToArray(c[0],4),b=d[0],O=d[1],_=d[2],m=d[3],g=getByKeyPath(b,O);if(void 0===g)break;_[m]=g,c.splice(0,1)}}if(!f)return n;if("#"===f){var j=getByKeyPath(o,n.slice(1));return void 0===j&&c.push([o,n.slice(1),s,y]),j}return[].concat(f).reduce((function reducer(t,n){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,n)})):executeReviver(n,t)}),n)}}("",t,null),l.length&&(f=e.resolve(f).then((function(t){return e.all([t].concat(l))})).then((function(e){return _slicedToArray(e,1)[0]})))),isThenable(f)?o&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(f,e)?f.p.then(checkUndefined):f:!o&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():o?checkUndefined(f):Promise.resolve(checkUndefined(f))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(i(e))return e.map((function(e){return R.call(n,e)}));e&&a(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],o=r&&r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,a=o.filter((function(e){return e.type===n}));if(a.length&&(o.splice(o.indexOf(a[0]),1),delete this.revivers[n],delete this.types[n]),"function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(i(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}if(r&&r.test){var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"],module.exports=u; |
@@ -15,2 +15,38 @@ function _typeof(obj) { | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function () { | ||
var self = this, | ||
args = arguments; | ||
return new Promise(function (resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -154,3 +190,3 @@ if (!(instance instanceof Constructor)) { | ||
* With ES6 classes, we may be able to simply use `class TypesonPromise | ||
* extends Promise` and add a string tag for detection | ||
* extends Promise` and add a string tag for detection. | ||
* @param {function} f | ||
@@ -242,3 +278,3 @@ */ | ||
Promise[meth](promArr.map(function (prom) { | ||
return prom.p; | ||
return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom; | ||
})).then(typesonResolve, typesonReject); | ||
@@ -458,2 +494,6 @@ }); | ||
function nestedPathsFirst(a, b) { | ||
if (a.keypath === '') { | ||
return -1; | ||
} | ||
var as = a.keypath.match(/\./g) || 0; | ||
@@ -497,3 +537,3 @@ var bs = b.keypath.match(/\./g) || 0; | ||
this.revivers = {}; | ||
/** Types registered via register() */ | ||
/** Types registered via `register()`. */ | ||
@@ -755,88 +795,107 @@ this.types = {}; | ||
function checkPromises(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.async(function checkPromises$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return regeneratorRuntime.awrap(Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
}))); | ||
function checkPromises(_x, _x2) { | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return regeneratorRuntime.awrap(Promise.all(promResults.map(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
return regeneratorRuntime.async(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
function _checkPromises() { | ||
_checkPromises = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee2(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
})); | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return Promise.all(promResults.map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
_context.next = 8; | ||
return regeneratorRuntime.awrap(encaps.p); | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
_context.next = 8; | ||
return encaps.p; | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
} | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee); | ||
})); | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
return function (_x3) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}); | ||
}))); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
} | ||
}); | ||
}, _callee2); | ||
})); | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { | ||
@@ -891,3 +950,7 @@ Object.assign(stateObj, ownKeysObj); | ||
if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) { | ||
ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); | ||
if (stateObj.replaced) { | ||
ret = value; | ||
} else { | ||
ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); | ||
} | ||
@@ -918,3 +981,3 @@ if (ret !== value) { | ||
if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric) { | ||
if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') { | ||
// Options set to detect cyclic references and be able | ||
@@ -958,3 +1021,6 @@ // to rewrite them. | ||
// eslint-disable-next-line no-lonely-if | ||
if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { | ||
if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { | ||
promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); | ||
ret = value; | ||
} else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { | ||
clone = new Array(value.length); | ||
@@ -964,5 +1030,2 @@ observerData = { | ||
}; | ||
} else if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { | ||
promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); | ||
ret = value; | ||
} else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') { | ||
@@ -1262,18 +1325,10 @@ clone = {}; | ||
* @param {Any} val | ||
* @param {RevivalReducer} reducer [description] | ||
* @returns {[type]} [description] | ||
*/ | ||
function executeReviver(type, val, reducer) { | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
return val.then(function (v) { | ||
// TypesonPromise here too | ||
return reducer(v, type); | ||
}); | ||
} | ||
function executeReviver(type, val) { | ||
var _ref2 = that.revivers[type] || [], | ||
_ref3 = _slicedToArray(_ref2, 1), | ||
reviver = _ref3[0]; | ||
var _ref = that.revivers[type] || [], | ||
_ref2 = _slicedToArray(_ref, 1), | ||
reviver = _ref2[0]; | ||
if (!reviver) { | ||
@@ -1304,6 +1359,6 @@ throw new Error('Unregistered type: ' + type); | ||
var plainObjectTypes = []; | ||
Object.entries(types).forEach(function (_ref3) { | ||
var _ref4 = _slicedToArray(_ref3, 2), | ||
keypath = _ref4[0], | ||
type = _ref4[1]; | ||
Object.entries(types).forEach(function (_ref4) { | ||
var _ref5 = _slicedToArray(_ref4, 2), | ||
keypath = _ref5[0], | ||
type = _ref5[1]; | ||
@@ -1321,5 +1376,5 @@ if (type === '#') { | ||
[].concat(type).forEach(function (type) { | ||
var _ref5 = that.revivers[type] || [null, {}], | ||
_ref6 = _slicedToArray(_ref5, 2), | ||
plain = _ref6[1].plain; | ||
var _ref6 = that.revivers[type] || [null, {}], | ||
_ref7 = _slicedToArray(_ref6, 2), | ||
plain = _ref7[1].plain; | ||
@@ -1341,3 +1396,4 @@ if (!plain) { | ||
return undefined; | ||
} | ||
} // console.log(plainObjectTypes.sort(nestedPathsFirst)); | ||
/** | ||
@@ -1350,22 +1406,29 @@ * @typedef {PlainObject} PlainObjectType | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref7) { | ||
var keypath = _ref7.keypath, | ||
type = _ref7.type; | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) { | ||
var keypath = _ref8.keypath, | ||
type = _ref8.type; | ||
if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { | ||
// TypesonPromise here too | ||
return possibleTypesonPromise.then(function (v) { | ||
return reducer(v, type); | ||
if (isThenable(possibleTypesonPromise)) { | ||
return possibleTypesonPromise.then(function (val) { | ||
return reducer(val, { | ||
keypath: keypath, | ||
type: type | ||
}); | ||
}); | ||
} | ||
} // console.log('obj', JSON.stringify(keypath), obj); | ||
var val = getByKeyPath(obj, keypath); | ||
val = executeReviver(type, val, reducer); | ||
val = executeReviver(type, val); | ||
if (val === undefined) { | ||
return undefined; | ||
} | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
return val.then(function (v) { | ||
var newVal = setAtKeyPath(obj, keypath, v); | ||
if (hasConstructorOf(val, Undefined)) { | ||
val = undefined; | ||
if (newVal === v) { | ||
obj = newVal; | ||
} | ||
return undefined; | ||
}); | ||
} | ||
@@ -1376,3 +1439,3 @@ | ||
if (newVal === val) { | ||
obj = val; | ||
obj = newVal; | ||
} | ||
@@ -1385,2 +1448,4 @@ | ||
} | ||
var revivalPromises = []; | ||
/** | ||
@@ -1396,3 +1461,2 @@ * | ||
function _revive(keypath, value, target, clone, key) { | ||
@@ -1404,5 +1468,6 @@ if (ignore$Types && keypath === '$types') { | ||
var type = types[keypath]; | ||
var isArr = isArray(value); | ||
if (isArray(value) || isPlainObject(value)) { | ||
var _clone = isArray(value) ? new Array(value.length) : {}; // Iterate object or array | ||
if (isArr || isPlainObject(value)) { | ||
var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array | ||
@@ -1413,6 +1478,18 @@ | ||
if (hasConstructorOf(val, Undefined)) { | ||
_clone[k] = undefined; | ||
} else if (val !== undefined) { | ||
_clone[k] = val; | ||
var set = function set(v) { | ||
if (hasConstructorOf(v, Undefined)) { | ||
_clone[k] = undefined; | ||
} else if (v !== undefined) { | ||
_clone[k] = v; | ||
} | ||
return v; | ||
}; | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
revivalPromises.push(val.then(function (ret) { | ||
return set(ret); | ||
})); | ||
} else { | ||
set(val); | ||
} | ||
@@ -1429,7 +1506,6 @@ }); | ||
var val = getByKeyPath(_target, keyPath); | ||
var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or | ||
// `undefined` | ||
if (hasConstructorOf(val, Undefined)) { | ||
_clone2[k] = undefined; | ||
} else if (val !== undefined) { | ||
if (val !== undefined) { | ||
_clone2[k] = val; | ||
@@ -1457,6 +1533,14 @@ } else { | ||
return _ret; | ||
} | ||
} // `type` can be an array here | ||
return [].concat(type).reduce(function reducer(val, type) { | ||
return executeReviver(type, val, reducer); | ||
return [].concat(type).reduce(function reducer(val, typ) { | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
return val.then(function (v) { | ||
// TypesonPromise here too | ||
return reducer(v, typ); | ||
}); | ||
} | ||
return executeReviver(typ, val); | ||
}, value); | ||
@@ -1480,6 +1564,19 @@ } | ||
ret = possibleTypesonPromise.then(function () { | ||
return _revive('', obj, null); | ||
return obj; | ||
}); | ||
} else { | ||
ret = _revive('', obj, null); | ||
if (revivalPromises.length) { | ||
// Ensure children resolved | ||
ret = TypesonPromise.resolve(ret).then(function (r) { | ||
return TypesonPromise.all([// May be a TypesonPromise or not | ||
r].concat(revivalPromises)); | ||
}).then(function (_ref9) { | ||
var _ref10 = _slicedToArray(_ref9, 1), | ||
r = _ref10[0]; | ||
return r; | ||
}); | ||
} | ||
} | ||
@@ -1486,0 +1583,0 @@ |
@@ -1,1 +0,1 @@ | ||
function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,i=!1,a=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,a=e}finally{try{r||null==c.return||c.return()}finally{if(i)throw a}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,i){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,i)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e.p}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,i=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var a=r(e);if(!a)return null===t;var o=n.call(a,"constructor")&&a.constructor;return"function"!=typeof o?null===t:t===o||(null!==t&&i.call(o)===i.call(t)||"function"==typeof t&&"string"==typeof o.__typeson__type__&&o.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}var a=Object.keys,o=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g)||0,r=t.keypath.match(/\./g)||0;return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var i=this.encapsulate(e,null,r);return o(i)?JSON.stringify(i[0],t,n):i.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var i=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,i,s,f,h,d){var b,O={},_=_typeof(n),g=v?function(r){var a=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:i,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},{type:a}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=replace(t,n,s,f,!1,h,g))!==n&&(O={replaced:b}):b=n,g&&g(),b;if(null===n)return g&&g(),n;if(i&&!s.iterateIn&&!s.iterateUnsetNumeric){var m=y.indexOf(n);if(!(m<0))return p[t]="#",g&&g({cyclicKeypath:l[m]}),"#"+l[m];!0===i&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=o(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,g);if(T!==n?(b=T,O={replaced:T}):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,i,s,void 0,void 0,s.type]),b=n):(["function","symbol"].includes(_typeof(n))||"toJSON"in n||hasConstructorOf(n,e)||hasConstructorOf(n,Promise)||hasConstructorOf(n,ArrayBuffer))&&!P&&"object"!==s.iterateIn?b=n:(j={},s.addLength&&(j.length=n.length),O={clone:j}),g&&g(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var a={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,a,(function(){var a=t+(t?".":"")+escapeKeyPathComponent(r),o=_encapsulate(a,n[r],Boolean(i),s,f,h);hasConstructorOf(o,e)?f.push([a,o,Boolean(i),s,j,r,s.type]):void 0!==o&&(j[r]=o)}))};for(var A in n)w(A);g&&g({endIterateIn:!0,end:!0})}else a(n).forEach((function(r){var a=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(a,n[r],Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),g&&g({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=n.length,k=function _loop2(r){if(!(r in n)){var a=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},B=0;B<C;B++)k(B);g&&g({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,a,o,c){for(var s=a?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!i&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[i||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,o,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,o,f))}}return t}return f.length?i&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(t,n){var r;return regeneratorRuntime.async((function checkPromises$(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,regeneratorRuntime.awrap(Promise.all(n.map((function(e){return e[1].p}))));case 2:return r=i.sent,i.next=5,regeneratorRuntime.awrap(Promise.all(r.map((function _callee(r){var i,a,o,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.async((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(i=[],a=n.splice(0,1),o=_slicedToArray(a,1),c=o[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,i,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,regeneratorRuntime.awrap(v.p);case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,i));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,i));case 13:case"end":return O.stop()}}))}))));case 5:return i.abrupt("return",t);case 6:case"end":return i.stop()}}))}(d,f)).then(finish):!i&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&i?[finish(d)]:i?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var i=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function executeReviver(t,n,r){if(hasConstructorOf(n,e))return n.then((function(e){return r(e,t)}));var a=_slicedToArray(y.revivers[t]||[],1)[0];if(!a)throw new Error("Unregistered type: "+t);return!i||"revive"in a?a[i&&a.revive?"revive":!i&&a.reviveAsync?"reviveAsync":"revive"](n,s):n}function _revive(e,t,n,i,s){if(!u||"$types"!==e){var y=r[e];if(o(t)||isPlainObject(t)){var l=o(t)?new Array(t.length):{};for(a(t).forEach((function(r){var i=_revive(e+(e?".":"")+escapeKeyPathComponent(r),t[r],n||l,l,r);hasConstructorOf(i,p)?l[r]=void 0:void 0!==i&&(l[r]=i)})),t=l;c.length;){var f=_slicedToArray(c[0],4),h=f[0],v=f[1],d=f[2],b=f[3],O=getByKeyPath(h,v);if(hasConstructorOf(O,p))d[b]=void 0;else{if(void 0===O)break;d[b]=O}c.splice(0,1)}}if(!y)return t;if("#"===y){var _=getByKeyPath(n,t.slice(1));return void 0===_&&c.push([n,t.slice(1),i,s]),_}return[].concat(y).reduce((function reducer(e,t){return executeReviver(t,e,reducer)}),t)}}function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var l,f=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),i=t[0],a=t[1];"#"!==a&&[].concat(a).forEach((function(e){_slicedToArray(y.revivers[e]||[null,{}],2)[1].plain&&(n.push({keypath:i,type:e}),delete r[i])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var i=r.keypath,a=r.type;if(hasConstructorOf(n,e))return n.then((function(e){return reducer(e,a)}));var o=getByKeyPath(t,i);void 0!==(o=executeReviver(a,o,reducer))&&(hasConstructorOf(o,p)&&(o=void 0),function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}(t,i,o)===o&&(t=o))}),void 0)}();return isThenable(l=hasConstructorOf(f,e)?f.then((function(){return _revive("",t,null)})):_revive("",t,null))?i&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(l,e)?l.p.then(checkUndefined):l:!i&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():i?checkUndefined(l):Promise.resolve(checkUndefined(l))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(o(e))return e.map((function(e){return R.call(n,e)}));e&&a(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],i=r&&r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,a=i.filter((function(e){return e.type===n}));if(a.length&&(i.splice(i.indexOf(a[0]),1),delete this.revivers[n],delete this.types[n]),"function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(o(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}if(r&&r.test){var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"];export default u; | ||
function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function asyncGeneratorStep(e,t,n,r,o,a,i){try{var c=e[a](i),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(r,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function _next(e){asyncGeneratorStep(a,r,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(a,r,o,_next,_throw,"throw",e)}_next(void 0)}))}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,o=!1,a=void 0;try{for(var i,c=e[Symbol.iterator]();!(r=(i=c.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,a=e}finally{try{r||null==c.return||c.return()}finally{if(o)throw a}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,o){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,o)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,o=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var a=r(e);if(!a)return null===t;var i=n.call(a,"constructor")&&a.constructor;return"function"!=typeof i?null===t:t===i||(null!==t&&o.call(i)===o.call(t)||"function"==typeof t&&"string"==typeof i.__typeson__type__&&i.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}var a=Object.keys,i=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){if(""===e.keypath)return-1;var n=e.keypath.match(/\./g)||0,r=t.keypath.match(/\./g)||0;return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var o=this.encapsulate(e,null,r);return i(o)?JSON.stringify(o[0],t,n):o.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var o=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function checkPromises(e,t){return _checkPromises.apply(this,arguments)}function _checkPromises(){return(_checkPromises=_asyncToGenerator(regeneratorRuntime.mark((function _callee2(t,n){var r;return regeneratorRuntime.wrap((function _callee2$(o){for(;;)switch(o.prev=o.next){case 0:return o.next=2,Promise.all(n.map((function(e){return e[1].p})));case 2:return r=o.sent,o.next=5,Promise.all(r.map(function(){var r=_asyncToGenerator(regeneratorRuntime.mark((function _callee(r){var o,a,i,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.wrap((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(o=[],a=n.splice(0,1),i=_slicedToArray(a,1),c=i[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,o,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,v.p;case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,o));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,o));case 13:case"end":return O.stop()}}),_callee)})));return function(e){return r.apply(this,arguments)}}()));case 5:return o.abrupt("return",t);case 6:case"end":return o.stop()}}),_callee2)})))).apply(this,arguments)}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,o,s,f,h,d){var b,O={},_=_typeof(n),m=v?function(r){var a=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:o,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},{type:a}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=s.replaced?n:replace(t,n,s,f,!1,h,m))!==n&&(O={replaced:b}):b=n,m&&m(),b;if(null===n)return m&&m(),n;if(o&&!s.iterateIn&&!s.iterateUnsetNumeric&&n&&"object"===_typeof(n)){var g=y.indexOf(n);if(!(g<0))return p[t]="#",m&&m({cyclicKeypath:l[g]}),"#"+l[g];!0===o&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=i(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,m);if(T!==n?(b=T,O={replaced:T}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,o,s,void 0,void 0,s.type]),b=n):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):(["function","symbol"].includes(_typeof(n))||"toJSON"in n||hasConstructorOf(n,e)||hasConstructorOf(n,Promise)||hasConstructorOf(n,ArrayBuffer))&&!P&&"object"!==s.iterateIn?b=n:(j={},s.addLength&&(j.length=n.length),O={clone:j}),m&&m(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var a={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,a,(function(){var a=t+(t?".":"")+escapeKeyPathComponent(r),i=_encapsulate(a,n[r],Boolean(o),s,f,h);hasConstructorOf(i,e)?f.push([a,i,Boolean(o),s,j,r,s.type]):void 0!==i&&(j[r]=i)}))};for(var A in n)w(A);m&&m({endIterateIn:!0,end:!0})}else a(n).forEach((function(r){var a=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(a,n[r],Boolean(o),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(o),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),m&&m({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var k=n.length,C=function _loop2(r){if(!(r in n)){var a=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(o),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(o),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},K=0;K<k;K++)C(K);m&&m({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,a,i,c){for(var s=a?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!o&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[o||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,i,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,i,f))}}return t}return f.length?o&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(checkPromises(d,f)).then(finish):!o&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&o?[finish(d)]:o?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var o=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function executeReviver(e,t){var n=_slicedToArray(y.revivers[e]||[],1)[0];if(!n)throw new Error("Unregistered type: "+e);return!o||"revive"in n?n[o&&n.revive?"revive":!o&&n.reviveAsync?"reviveAsync":"revive"](t,s):t}var l=[];function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var f,h=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),o=t[0],a=t[1];"#"!==a&&[].concat(a).forEach((function(e){_slicedToArray(y.revivers[e]||[null,{}],2)[1].plain&&(n.push({keypath:o,type:e}),delete r[o])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var o=r.keypath,a=r.type;if(isThenable(n))return n.then((function(e){return reducer(e,{keypath:o,type:a})}));var i=getByKeyPath(t,o);if(hasConstructorOf(i=executeReviver(a,i),e))return i.then((function(e){var n=setAtKeyPath(t,o,e);n===e&&(t=n)}));var c=setAtKeyPath(t,o,i);c===i&&(t=c)}),void 0)}();return hasConstructorOf(h,e)?f=h.then((function(){return t})):(f=function _revive(t,n,o,s,y){if(!u||"$types"!==t){var f=r[t],h=i(n);if(h||isPlainObject(n)){var v=h?new Array(n.length):{};for(a(n).forEach((function(r){var a=_revive(t+(t?".":"")+escapeKeyPathComponent(r),n[r],o||v,v,r),i=function set(e){return hasConstructorOf(e,p)?v[r]=void 0:void 0!==e&&(v[r]=e),e};hasConstructorOf(a,e)?l.push(a.then((function(e){return i(e)}))):i(a)})),n=v;c.length;){var d=_slicedToArray(c[0],4),b=d[0],O=d[1],_=d[2],m=d[3],g=getByKeyPath(b,O);if(void 0===g)break;_[m]=g,c.splice(0,1)}}if(!f)return n;if("#"===f){var j=getByKeyPath(o,n.slice(1));return void 0===j&&c.push([o,n.slice(1),s,y]),j}return[].concat(f).reduce((function reducer(t,n){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,n)})):executeReviver(n,t)}),n)}}("",t,null),l.length&&(f=e.resolve(f).then((function(t){return e.all([t].concat(l))})).then((function(e){return _slicedToArray(e,1)[0]})))),isThenable(f)?o&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(f,e)?f.p.then(checkUndefined):f:!o&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():o?checkUndefined(f):Promise.resolve(checkUndefined(f))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(i(e))return e.map((function(e){return R.call(n,e)}));e&&a(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],o=r&&r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,a=o.filter((function(e){return e.type===n}));if(a.length&&(o.splice(o.indexOf(a[0]),1),delete this.revivers[n],delete this.types[n]),"function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(i(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}if(r&&r.test){var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"];export default u; |
@@ -21,2 +21,38 @@ (function (global, factory) { | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function () { | ||
var self = this, | ||
args = arguments; | ||
return new Promise(function (resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -160,3 +196,3 @@ if (!(instance instanceof Constructor)) { | ||
* With ES6 classes, we may be able to simply use `class TypesonPromise | ||
* extends Promise` and add a string tag for detection | ||
* extends Promise` and add a string tag for detection. | ||
* @param {function} f | ||
@@ -248,3 +284,3 @@ */ | ||
Promise[meth](promArr.map(function (prom) { | ||
return prom.p; | ||
return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom; | ||
})).then(typesonResolve, typesonReject); | ||
@@ -464,2 +500,6 @@ }); | ||
function nestedPathsFirst(a, b) { | ||
if (a.keypath === '') { | ||
return -1; | ||
} | ||
var as = a.keypath.match(/\./g) || 0; | ||
@@ -503,3 +543,3 @@ var bs = b.keypath.match(/\./g) || 0; | ||
this.revivers = {}; | ||
/** Types registered via register() */ | ||
/** Types registered via `register()`. */ | ||
@@ -761,88 +801,107 @@ this.types = {}; | ||
function checkPromises(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.async(function checkPromises$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return regeneratorRuntime.awrap(Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
}))); | ||
function checkPromises(_x, _x2) { | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return regeneratorRuntime.awrap(Promise.all(promResults.map(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
return regeneratorRuntime.async(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
function _checkPromises() { | ||
_checkPromises = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee2(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
})); | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return Promise.all(promResults.map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
_context.next = 8; | ||
return regeneratorRuntime.awrap(encaps.p); | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
_context.next = 8; | ||
return encaps.p; | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
} | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee); | ||
})); | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
return function (_x3) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}); | ||
}))); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
} | ||
}); | ||
}, _callee2); | ||
})); | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { | ||
@@ -897,3 +956,7 @@ Object.assign(stateObj, ownKeysObj); | ||
if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) { | ||
ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); | ||
if (stateObj.replaced) { | ||
ret = value; | ||
} else { | ||
ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); | ||
} | ||
@@ -924,3 +987,3 @@ if (ret !== value) { | ||
if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric) { | ||
if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') { | ||
// Options set to detect cyclic references and be able | ||
@@ -964,3 +1027,6 @@ // to rewrite them. | ||
// eslint-disable-next-line no-lonely-if | ||
if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { | ||
if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { | ||
promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); | ||
ret = value; | ||
} else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { | ||
clone = new Array(value.length); | ||
@@ -970,5 +1036,2 @@ observerData = { | ||
}; | ||
} else if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { | ||
promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); | ||
ret = value; | ||
} else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') { | ||
@@ -1268,18 +1331,10 @@ clone = {}; | ||
* @param {Any} val | ||
* @param {RevivalReducer} reducer [description] | ||
* @returns {[type]} [description] | ||
*/ | ||
function executeReviver(type, val, reducer) { | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
return val.then(function (v) { | ||
// TypesonPromise here too | ||
return reducer(v, type); | ||
}); | ||
} | ||
function executeReviver(type, val) { | ||
var _ref2 = that.revivers[type] || [], | ||
_ref3 = _slicedToArray(_ref2, 1), | ||
reviver = _ref3[0]; | ||
var _ref = that.revivers[type] || [], | ||
_ref2 = _slicedToArray(_ref, 1), | ||
reviver = _ref2[0]; | ||
if (!reviver) { | ||
@@ -1310,6 +1365,6 @@ throw new Error('Unregistered type: ' + type); | ||
var plainObjectTypes = []; | ||
Object.entries(types).forEach(function (_ref3) { | ||
var _ref4 = _slicedToArray(_ref3, 2), | ||
keypath = _ref4[0], | ||
type = _ref4[1]; | ||
Object.entries(types).forEach(function (_ref4) { | ||
var _ref5 = _slicedToArray(_ref4, 2), | ||
keypath = _ref5[0], | ||
type = _ref5[1]; | ||
@@ -1327,5 +1382,5 @@ if (type === '#') { | ||
[].concat(type).forEach(function (type) { | ||
var _ref5 = that.revivers[type] || [null, {}], | ||
_ref6 = _slicedToArray(_ref5, 2), | ||
plain = _ref6[1].plain; | ||
var _ref6 = that.revivers[type] || [null, {}], | ||
_ref7 = _slicedToArray(_ref6, 2), | ||
plain = _ref7[1].plain; | ||
@@ -1347,3 +1402,4 @@ if (!plain) { | ||
return undefined; | ||
} | ||
} // console.log(plainObjectTypes.sort(nestedPathsFirst)); | ||
/** | ||
@@ -1356,22 +1412,29 @@ * @typedef {PlainObject} PlainObjectType | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref7) { | ||
var keypath = _ref7.keypath, | ||
type = _ref7.type; | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) { | ||
var keypath = _ref8.keypath, | ||
type = _ref8.type; | ||
if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { | ||
// TypesonPromise here too | ||
return possibleTypesonPromise.then(function (v) { | ||
return reducer(v, type); | ||
if (isThenable(possibleTypesonPromise)) { | ||
return possibleTypesonPromise.then(function (val) { | ||
return reducer(val, { | ||
keypath: keypath, | ||
type: type | ||
}); | ||
}); | ||
} | ||
} // console.log('obj', JSON.stringify(keypath), obj); | ||
var val = getByKeyPath(obj, keypath); | ||
val = executeReviver(type, val, reducer); | ||
val = executeReviver(type, val); | ||
if (val === undefined) { | ||
return undefined; | ||
} | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
return val.then(function (v) { | ||
var newVal = setAtKeyPath(obj, keypath, v); | ||
if (hasConstructorOf(val, Undefined)) { | ||
val = undefined; | ||
if (newVal === v) { | ||
obj = newVal; | ||
} | ||
return undefined; | ||
}); | ||
} | ||
@@ -1382,3 +1445,3 @@ | ||
if (newVal === val) { | ||
obj = val; | ||
obj = newVal; | ||
} | ||
@@ -1391,2 +1454,4 @@ | ||
} | ||
var revivalPromises = []; | ||
/** | ||
@@ -1402,3 +1467,2 @@ * | ||
function _revive(keypath, value, target, clone, key) { | ||
@@ -1410,5 +1474,6 @@ if (ignore$Types && keypath === '$types') { | ||
var type = types[keypath]; | ||
var isArr = isArray(value); | ||
if (isArray(value) || isPlainObject(value)) { | ||
var _clone = isArray(value) ? new Array(value.length) : {}; // Iterate object or array | ||
if (isArr || isPlainObject(value)) { | ||
var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array | ||
@@ -1419,6 +1484,18 @@ | ||
if (hasConstructorOf(val, Undefined)) { | ||
_clone[k] = undefined; | ||
} else if (val !== undefined) { | ||
_clone[k] = val; | ||
var set = function set(v) { | ||
if (hasConstructorOf(v, Undefined)) { | ||
_clone[k] = undefined; | ||
} else if (v !== undefined) { | ||
_clone[k] = v; | ||
} | ||
return v; | ||
}; | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
revivalPromises.push(val.then(function (ret) { | ||
return set(ret); | ||
})); | ||
} else { | ||
set(val); | ||
} | ||
@@ -1435,7 +1512,6 @@ }); | ||
var val = getByKeyPath(_target, keyPath); | ||
var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or | ||
// `undefined` | ||
if (hasConstructorOf(val, Undefined)) { | ||
_clone2[k] = undefined; | ||
} else if (val !== undefined) { | ||
if (val !== undefined) { | ||
_clone2[k] = val; | ||
@@ -1463,6 +1539,14 @@ } else { | ||
return _ret; | ||
} | ||
} // `type` can be an array here | ||
return [].concat(type).reduce(function reducer(val, type) { | ||
return executeReviver(type, val, reducer); | ||
return [].concat(type).reduce(function reducer(val, typ) { | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
return val.then(function (v) { | ||
// TypesonPromise here too | ||
return reducer(v, typ); | ||
}); | ||
} | ||
return executeReviver(typ, val); | ||
}, value); | ||
@@ -1486,6 +1570,19 @@ } | ||
ret = possibleTypesonPromise.then(function () { | ||
return _revive('', obj, null); | ||
return obj; | ||
}); | ||
} else { | ||
ret = _revive('', obj, null); | ||
if (revivalPromises.length) { | ||
// Ensure children resolved | ||
ret = TypesonPromise.resolve(ret).then(function (r) { | ||
return TypesonPromise.all([// May be a TypesonPromise or not | ||
r].concat(revivalPromises)); | ||
}).then(function (_ref9) { | ||
var _ref10 = _slicedToArray(_ref9, 1), | ||
r = _ref10[0]; | ||
return r; | ||
}); | ||
} | ||
} | ||
@@ -1492,0 +1589,0 @@ |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Typeson=t()}(this,(function(){"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,i=!1,o=void 0;try{for(var a,c=e[Symbol.iterator]();!(r=(a=c.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{r||null==c.return||c.return()}finally{if(i)throw o}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,i){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,i)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e.p}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,i=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var o=r(e);if(!o)return null===t;var a=n.call(o,"constructor")&&o.constructor;return"function"!=typeof a?null===t:t===a||(null!==t&&i.call(a)===i.call(t)||"function"==typeof t&&"string"==typeof a.__typeson__type__&&a.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}var o=Object.keys,a=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g)||0,r=t.keypath.match(/\./g)||0;return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var i=this.encapsulate(e,null,r);return a(i)?JSON.stringify(i[0],t,n):i.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var i=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,i,s,f,h,d){var b,O={},_=_typeof(n),g=v?function(r){var o=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:i,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},{type:o}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=replace(t,n,s,f,!1,h,g))!==n&&(O={replaced:b}):b=n,g&&g(),b;if(null===n)return g&&g(),n;if(i&&!s.iterateIn&&!s.iterateUnsetNumeric){var m=y.indexOf(n);if(!(m<0))return p[t]="#",g&&g({cyclicKeypath:l[m]}),"#"+l[m];!0===i&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=a(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,g);if(T!==n?(b=T,O={replaced:T}):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,i,s,void 0,void 0,s.type]),b=n):(["function","symbol"].includes(_typeof(n))||"toJSON"in n||hasConstructorOf(n,e)||hasConstructorOf(n,Promise)||hasConstructorOf(n,ArrayBuffer))&&!P&&"object"!==s.iterateIn?b=n:(j={},s.addLength&&(j.length=n.length),O={clone:j}),g&&g(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var o={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,o,(function(){var o=t+(t?".":"")+escapeKeyPathComponent(r),a=_encapsulate(o,n[r],Boolean(i),s,f,h);hasConstructorOf(a,e)?f.push([o,a,Boolean(i),s,j,r,s.type]):void 0!==a&&(j[r]=a)}))};for(var A in n)w(A);g&&g({endIterateIn:!0,end:!0})}else o(n).forEach((function(r){var o=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(o,n[r],Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([o,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),g&&g({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=n.length,k=function _loop2(r){if(!(r in n)){var o=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(o,void 0,Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([o,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},B=0;B<C;B++)k(B);g&&g({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,o,a,c){for(var s=o?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!i&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[i||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,a,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,a,f))}}return t}return f.length?i&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(t,n){var r;return regeneratorRuntime.async((function checkPromises$(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,regeneratorRuntime.awrap(Promise.all(n.map((function(e){return e[1].p}))));case 2:return r=i.sent,i.next=5,regeneratorRuntime.awrap(Promise.all(r.map((function _callee(r){var i,o,a,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.async((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(i=[],o=n.splice(0,1),a=_slicedToArray(o,1),c=a[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,i,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,regeneratorRuntime.awrap(v.p);case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,i));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,i));case 13:case"end":return O.stop()}}))}))));case 5:return i.abrupt("return",t);case 6:case"end":return i.stop()}}))}(d,f)).then(finish):!i&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&i?[finish(d)]:i?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var i=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function executeReviver(t,n,r){if(hasConstructorOf(n,e))return n.then((function(e){return r(e,t)}));var o=_slicedToArray(y.revivers[t]||[],1)[0];if(!o)throw new Error("Unregistered type: "+t);return!i||"revive"in o?o[i&&o.revive?"revive":!i&&o.reviveAsync?"reviveAsync":"revive"](n,s):n}function _revive(e,t,n,i,s){if(!u||"$types"!==e){var y=r[e];if(a(t)||isPlainObject(t)){var l=a(t)?new Array(t.length):{};for(o(t).forEach((function(r){var i=_revive(e+(e?".":"")+escapeKeyPathComponent(r),t[r],n||l,l,r);hasConstructorOf(i,p)?l[r]=void 0:void 0!==i&&(l[r]=i)})),t=l;c.length;){var f=_slicedToArray(c[0],4),h=f[0],v=f[1],d=f[2],b=f[3],O=getByKeyPath(h,v);if(hasConstructorOf(O,p))d[b]=void 0;else{if(void 0===O)break;d[b]=O}c.splice(0,1)}}if(!y)return t;if("#"===y){var _=getByKeyPath(n,t.slice(1));return void 0===_&&c.push([n,t.slice(1),i,s]),_}return[].concat(y).reduce((function reducer(e,t){return executeReviver(t,e,reducer)}),t)}}function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var l,f=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),i=t[0],o=t[1];"#"!==o&&[].concat(o).forEach((function(e){_slicedToArray(y.revivers[e]||[null,{}],2)[1].plain&&(n.push({keypath:i,type:e}),delete r[i])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var i=r.keypath,o=r.type;if(hasConstructorOf(n,e))return n.then((function(e){return reducer(e,o)}));var a=getByKeyPath(t,i);void 0!==(a=executeReviver(o,a,reducer))&&(hasConstructorOf(a,p)&&(a=void 0),function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}(t,i,a)===a&&(t=a))}),void 0)}();return isThenable(l=hasConstructorOf(f,e)?f.then((function(){return _revive("",t,null)})):_revive("",t,null))?i&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(l,e)?l.p.then(checkUndefined):l:!i&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():i?checkUndefined(l):Promise.resolve(checkUndefined(l))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(a(e))return e.map((function(e){return R.call(n,e)}));e&&o(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],i=r&&r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,o=i.filter((function(e){return e.type===n}));if(o.length&&(i.splice(i.indexOf(o[0]),1),delete this.revivers[n],delete this.types[n]),"function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(a(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}if(r&&r.test){var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};return p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"],u})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Typeson=t()}(this,(function(){"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function asyncGeneratorStep(e,t,n,r,o,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(r,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var i=e.apply(t,n);function _next(e){asyncGeneratorStep(i,r,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(i,r,o,_next,_throw,"throw",e)}_next(void 0)}))}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var a,c=e[Symbol.iterator]();!(r=(a=c.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==c.return||c.return()}finally{if(o)throw i}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,o){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,o)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,o=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var i=r(e);if(!i)return null===t;var a=n.call(i,"constructor")&&i.constructor;return"function"!=typeof a?null===t:t===a||(null!==t&&o.call(a)===o.call(t)||"function"==typeof t&&"string"==typeof a.__typeson__type__&&a.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}var i=Object.keys,a=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){if(""===e.keypath)return-1;var n=e.keypath.match(/\./g)||0,r=t.keypath.match(/\./g)||0;return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var o=this.encapsulate(e,null,r);return a(o)?JSON.stringify(o[0],t,n):o.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var o=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function checkPromises(e,t){return _checkPromises.apply(this,arguments)}function _checkPromises(){return(_checkPromises=_asyncToGenerator(regeneratorRuntime.mark((function _callee2(t,n){var r;return regeneratorRuntime.wrap((function _callee2$(o){for(;;)switch(o.prev=o.next){case 0:return o.next=2,Promise.all(n.map((function(e){return e[1].p})));case 2:return r=o.sent,o.next=5,Promise.all(r.map(function(){var r=_asyncToGenerator(regeneratorRuntime.mark((function _callee(r){var o,i,a,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.wrap((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(o=[],i=n.splice(0,1),a=_slicedToArray(i,1),c=a[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,o,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,v.p;case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,o));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,o));case 13:case"end":return O.stop()}}),_callee)})));return function(e){return r.apply(this,arguments)}}()));case 5:return o.abrupt("return",t);case 6:case"end":return o.stop()}}),_callee2)})))).apply(this,arguments)}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,o,s,f,h,d){var b,O={},_=_typeof(n),m=v?function(r){var i=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:o,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},{type:i}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=s.replaced?n:replace(t,n,s,f,!1,h,m))!==n&&(O={replaced:b}):b=n,m&&m(),b;if(null===n)return m&&m(),n;if(o&&!s.iterateIn&&!s.iterateUnsetNumeric&&n&&"object"===_typeof(n)){var g=y.indexOf(n);if(!(g<0))return p[t]="#",m&&m({cyclicKeypath:l[g]}),"#"+l[g];!0===o&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=a(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,m);if(T!==n?(b=T,O={replaced:T}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,o,s,void 0,void 0,s.type]),b=n):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):(["function","symbol"].includes(_typeof(n))||"toJSON"in n||hasConstructorOf(n,e)||hasConstructorOf(n,Promise)||hasConstructorOf(n,ArrayBuffer))&&!P&&"object"!==s.iterateIn?b=n:(j={},s.addLength&&(j.length=n.length),O={clone:j}),m&&m(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var i={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,i,(function(){var i=t+(t?".":"")+escapeKeyPathComponent(r),a=_encapsulate(i,n[r],Boolean(o),s,f,h);hasConstructorOf(a,e)?f.push([i,a,Boolean(o),s,j,r,s.type]):void 0!==a&&(j[r]=a)}))};for(var A in n)w(A);m&&m({endIterateIn:!0,end:!0})}else i(n).forEach((function(r){var i=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(i,n[r],Boolean(o),s,f,h);hasConstructorOf(t,e)?f.push([i,t,Boolean(o),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),m&&m({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var k=n.length,C=function _loop2(r){if(!(r in n)){var i=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(i,void 0,Boolean(o),s,f,h);hasConstructorOf(t,e)?f.push([i,t,Boolean(o),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},K=0;K<k;K++)C(K);m&&m({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,i,a,c){for(var s=i?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!o&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[o||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,a,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,a,f))}}return t}return f.length?o&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(checkPromises(d,f)).then(finish):!o&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&o?[finish(d)]:o?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var o=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function executeReviver(e,t){var n=_slicedToArray(y.revivers[e]||[],1)[0];if(!n)throw new Error("Unregistered type: "+e);return!o||"revive"in n?n[o&&n.revive?"revive":!o&&n.reviveAsync?"reviveAsync":"revive"](t,s):t}var l=[];function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var f,h=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),o=t[0],i=t[1];"#"!==i&&[].concat(i).forEach((function(e){_slicedToArray(y.revivers[e]||[null,{}],2)[1].plain&&(n.push({keypath:o,type:e}),delete r[o])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var o=r.keypath,i=r.type;if(isThenable(n))return n.then((function(e){return reducer(e,{keypath:o,type:i})}));var a=getByKeyPath(t,o);if(hasConstructorOf(a=executeReviver(i,a),e))return a.then((function(e){var n=setAtKeyPath(t,o,e);n===e&&(t=n)}));var c=setAtKeyPath(t,o,a);c===a&&(t=c)}),void 0)}();return hasConstructorOf(h,e)?f=h.then((function(){return t})):(f=function _revive(t,n,o,s,y){if(!u||"$types"!==t){var f=r[t],h=a(n);if(h||isPlainObject(n)){var v=h?new Array(n.length):{};for(i(n).forEach((function(r){var i=_revive(t+(t?".":"")+escapeKeyPathComponent(r),n[r],o||v,v,r),a=function set(e){return hasConstructorOf(e,p)?v[r]=void 0:void 0!==e&&(v[r]=e),e};hasConstructorOf(i,e)?l.push(i.then((function(e){return a(e)}))):a(i)})),n=v;c.length;){var d=_slicedToArray(c[0],4),b=d[0],O=d[1],_=d[2],m=d[3],g=getByKeyPath(b,O);if(void 0===g)break;_[m]=g,c.splice(0,1)}}if(!f)return n;if("#"===f){var j=getByKeyPath(o,n.slice(1));return void 0===j&&c.push([o,n.slice(1),s,y]),j}return[].concat(f).reduce((function reducer(t,n){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,n)})):executeReviver(n,t)}),n)}}("",t,null),l.length&&(f=e.resolve(f).then((function(t){return e.all([t].concat(l))})).then((function(e){return _slicedToArray(e,1)[0]})))),isThenable(f)?o&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(f,e)?f.p.then(checkUndefined):f:!o&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():o?checkUndefined(f):Promise.resolve(checkUndefined(f))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(a(e))return e.map((function(e){return R.call(n,e)}));e&&i(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],o=r&&r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,i=o.filter((function(e){return e.type===n}));if(i.length&&(o.splice(o.indexOf(i[0]),1),delete this.revivers[n],delete this.types[n]),"function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(a(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}if(r&&r.test){var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};return p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"],u})); |
{ | ||
"name": "typeson", | ||
"version": "5.18.1", | ||
"version": "5.18.2", | ||
"description": "Preserves types over JSON, BSON or socket.io", | ||
@@ -50,6 +50,6 @@ "main": "./dist/typeson-commonjs2.min.js", | ||
"engines": { | ||
"node": ">=0.1.14" | ||
"node": ">=0.1.14" | ||
}, | ||
"peerDependencies": { | ||
"core-js-bundle": "^3.5.0", | ||
"core-js-bundle": "^3.6.4", | ||
"regenerator-runtime": "^0.13.3" | ||
@@ -59,38 +59,41 @@ }, | ||
"devDependencies": { | ||
"@babel/core": "^7.7.5", | ||
"@babel/preset-env": "^7.7.6", | ||
"@babel/core": "^7.8.3", | ||
"@babel/preset-env": "^7.8.3", | ||
"@mysticatea/eslint-plugin": "^13.0.0", | ||
"@rollup/plugin-replace": "^2.2.1", | ||
"@rollup/plugin-replace": "^2.3.0", | ||
"base64-arraybuffer-es6": "^0.5.0", | ||
"chai": "^4.2.0", | ||
"core-js-bundle": "^3.5.0", | ||
"eslint": "^6.7.2", | ||
"eslint-config-ash-nazg": "^13.1.0", | ||
"core-js-bundle": "^3.6.4", | ||
"eslint": "^6.8.0", | ||
"eslint-config-ash-nazg": "16.5.0", | ||
"eslint-config-standard": "^14.1.0", | ||
"eslint-plugin-array-func": "^3.1.3", | ||
"eslint-plugin-chai-expect": "^2.1.0", | ||
"eslint-plugin-chai-friendly": "^0.5.0", | ||
"eslint-plugin-compat": "^3.3.0", | ||
"eslint-plugin-eslint-comments": "^3.1.2", | ||
"eslint-plugin-html": "^6.0.0", | ||
"eslint-plugin-import": "^2.19.1", | ||
"eslint-plugin-jsdoc": "^18.4.3", | ||
"eslint-plugin-import": "^2.20.0", | ||
"eslint-plugin-jsdoc": "^20.3.1", | ||
"eslint-plugin-markdown": "^1.0.1", | ||
"eslint-plugin-no-unsanitized": "^3.0.2", | ||
"eslint-plugin-no-use-extend-native": "^0.4.1", | ||
"eslint-plugin-node": "^10.0.0", | ||
"eslint-plugin-node": "^11.0.0", | ||
"eslint-plugin-promise": "^4.2.1", | ||
"eslint-plugin-sonarjs": "^0.5.0", | ||
"eslint-plugin-standard": "^4.0.1", | ||
"eslint-plugin-unicorn": "^14.0.1", | ||
"eslint-plugin-unicorn": "^15.0.1", | ||
"esm": "^3.2.25", | ||
"mocha": "^6.2.2", | ||
"mocha": "^7.0.0", | ||
"node-static": "0.7.11", | ||
"nyc": "^14.1.1", | ||
"nyc": "^15.0.0", | ||
"open-cli": "^5.0.0", | ||
"regenerator-runtime": "^0.13.3", | ||
"rollup": "1.27.13", | ||
"rollup": "1.29.1", | ||
"rollup-plugin-babel": "^4.3.3", | ||
"rollup-plugin-re": "^1.0.7", | ||
"rollup-plugin-terser": "^5.1.3", | ||
"typescript": "^3.7.3" | ||
"rollup-plugin-terser": "^5.2.0", | ||
"typescript": "^3.7.5" | ||
}, | ||
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/presets/builtin'));\n\nTSON.stringify({foo: new Date()}, null, 2);" | ||
} |
/* eslint-disable no-shadow */ | ||
/** | ||
* Typeson - JSON with types | ||
* @file Typeson - JSON with types | ||
* @license The MIT License (MIT) | ||
@@ -75,3 +75,3 @@ * @copyright (c) 2016-2018 David Fahlander, Brett Zamir | ||
/** Types registered via register() */ | ||
/** Types registered via `register()`. */ | ||
this.types = {}; | ||
@@ -425,3 +425,4 @@ } | ||
if (cyclic && !stateObj.iterateIn && | ||
!stateObj.iterateUnsetNumeric | ||
!stateObj.iterateUnsetNumeric && value && | ||
typeof value === 'object' | ||
) { | ||
@@ -428,0 +429,0 @@ // Options set to detect cyclic references and be able |
@@ -6,3 +6,3 @@ /** | ||
* With ES6 classes, we may be able to simply use `class TypesonPromise | ||
* extends Promise` and add a string tag for detection | ||
* extends Promise` and add a string tag for detection. | ||
* @param {function} f | ||
@@ -9,0 +9,0 @@ */ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
257224
4507
37