Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

typeson-registry

Package Overview
Dependencies
Maintainers
2
Versions
69
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

typeson-registry - npm Package Compare versions

Comparing version 1.0.0-alpha.39 to 2.0.0

dist/index.min.js

1205

dist/index.js

@@ -1,2 +0,1205 @@

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 r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var r=[],n=!0,a=!1,o=void 0;try{for(var i,s=e[Symbol.iterator]();!(n=(i=s.next()).done)&&(r.push(i.value),!t||r.length!==t);n=!0);}catch(e){a=!0,o=e}finally{try{n||null==s.return||s.return()}finally{if(a)throw o}}return r}(e,t)||_unsupportedIterableToArray(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}(e)||function _iterableToArray(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||_unsupportedIterableToArray(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}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,r){var n=this;return new e((function(e,a){n.p.then((function(r){e(t?t(r):r)})).catch((function(e){return r?r(e):Promise.reject(e)})).then(e,a)}))},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,r){r(t)}))},["all","race"].forEach((function(t){e[t]=function(r){return new e((function(e,n){Promise[t](r.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,n)}))}}));var t={}.toString,r={}.hasOwnProperty,n=Object.getPrototypeOf,a=r.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=n(e);if(!o)return null===t;var i=r.call(o,"constructor")&&o.constructor;return"function"!=typeof i?null===t:t===i||(null!==t&&a.call(i)===a.call(t)||"function"==typeof t&&"string"==typeof i.__typeson__type__&&i.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!n(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 r=t.indexOf(".");if(r>-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(""===t)return r;var n=t.indexOf(".");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function _await(e,t,r){return r?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}var o=Object.keys,i=Array.isArray,s={}.hasOwnProperty,c=["type","replaced","iterateIn","iterateUnsetNumeric"];function _async(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];try{return Promise.resolve(e.apply(this,t))}catch(e){return Promise.reject(e)}}}function nestedPathsFirst(e,t){if(""===e.keypath)return-1;var r=e.keypath.match(/\./g)||0,n=t.keypath.match(/\./g)||0;return r&&(r=r.length),n&&(n=n.length),r>n?-1:r<n?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,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(Typeson,[{key:"stringify",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var a=this.encapsulate(e,null,n);return i(a)?JSON.stringify(a[0],t,r):a.then((function(e){return JSON.stringify(e,t,r)}))}},{key:"stringifySync",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:"parse",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:"parseSync",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:"rootTypeName",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:"encapsulate",value:function encapsulate(t,r,n){var a=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var o=!1,i=[],s=_slicedToArray(r.splice(0,1),1),c=_slicedToArray(s[0],7),u=c[0],l=c[2],f=c[3],y=c[4],p=c[5],d=c[6],b=_encapsulate(u,n,l,f,i,!0,d),v=hasConstructorOf(b,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(u&&v)return _await(b.p,(function(e){return y[p]=e,o=!0,a(t,i)}))}),(function(e){return o?e:(u?y[p]=b:t=v?b.p:b,a(t,i))}))})))),(function(){return t}))}))})),u=(n=_objectSpread2(_objectSpread2({sync:!0},this.options),n)).sync,l=this,f={},y=[],p=[],d=[],b=!("cyclic"in n)||n.cyclic,v=n.encapsulateObserver,h=_encapsulate("",t,b,r||{},d);function finish(e){var t=Object.values(f);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)&&!s.call(e,"$types")?e.$types=f:e={$:e,$types:{$:f}}}else isObject(e)&&s.call(e,"$types")&&(e={$:e,$types:!0});return!n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=c.map((function(t){var r=e[t];return delete e[t],r}));r(),c.forEach((function(t,r){e[t]=n[r]}))}function _encapsulate(t,r,a,c,u,d,b){var h,g={},m=_typeof(r),O=v?function(n){var o=b||c.type||Typeson.getJSONType(r);v(Object.assign(n||g,{keypath:t,value:r,cyclic:a,stateObj:c,promisesData:u,resolvingTypesonPromise:d,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:o}))}:null;if(["string","boolean","number","undefined"].includes(m))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY?(h=c.replaced?r:replace(t,r,c,u,!1,d,O))!==r&&(g={replaced:h}):h=r,O&&O(),h;if(null===r)return O&&O(),r;if(a&&!c.iterateIn&&!c.iterateUnsetNumeric&&r&&"object"===_typeof(r)){var S=y.indexOf(r);if(!(S<0))return f[t]="#",O&&O({cyclicKeypath:p[S]}),"#"+p[S];!0===a&&(y.push(r),p.push(t))}var _,j=isPlainObject(r),A=i(r),w=(j||A)&&(!l.plainObjectReplacers.length||c.replaced)||c.iterateIn?r:replace(t,r,c,u,j||A,null,O);if(w!==r?(h=w,g={replaced:w}):""===t&&hasConstructorOf(r,e)?(u.push([t,r,a,c,void 0,void 0,c.type]),h=r):A&&"object"!==c.iterateIn||"array"===c.iterateIn?(_=new Array(r.length),g={clone:_}):(["function","symbol"].includes(_typeof(r))||"toJSON"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!j&&"object"!==c.iterateIn?h=r:(_={},c.addLength&&(_.length=r.length),g={clone:_}),O&&O(),n.iterateNone)return _||h;if(!_)return h;if(c.iterateIn){var T=function _loop(n){var o={ownKeys:s.call(r,n)};_adaptBuiltinStateObjectProperties(c,o,(function(){var o=t+(t?".":"")+escapeKeyPathComponent(n),i=_encapsulate(o,r[n],Boolean(a),c,u,d);hasConstructorOf(i,e)?u.push([o,i,Boolean(a),c,_,n,c.type]):void 0!==i&&(_[n]=i)}))};for(var I in r)T(I);O&&O({endIterateIn:!0,end:!0})}else o(r).forEach((function(n){var o=t+(t?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},(function(){var t=_encapsulate(o,r[n],Boolean(a),c,u,d);hasConstructorOf(t,e)?u.push([o,t,Boolean(a),c,_,n,c.type]):void 0!==t&&(_[n]=t)}))})),O&&O({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var P=r.length,N=function _loop2(n){if(!(n in r)){var o=t+(t?".":"")+n;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},(function(){var t=_encapsulate(o,void 0,Boolean(a),c,u,d);hasConstructorOf(t,e)?u.push([o,t,Boolean(a),c,_,n,c.type]):void 0!==t&&(_[n]=t)}))}},C=0;C<P;C++)N(C);O&&O({endIterateUnsetNumeric:!0,end:!0})}return _}function replace(e,t,r,n,a,o,i){for(var s=a?l.plainObjectReplacers:l.nonplainObjectReplacers,c=s.length;c--;){var y=s[c];if(y.test(t,r)){var p=y.type;if(l.revivers[p]){var d=f[e];f[e]=d?[p].concat(d):p}return Object.assign(r,{type:p,replaced:!0}),!u&&y.replaceAsync||y.replace?(i&&i({replacing:!0}),_encapsulate(e,y[u||!y.replaceAsync?"replace":"replaceAsync"](t,r),b&&"readonly",r,n,o,p)):(i&&i({typeDetected:!0}),_encapsulate(e,t,b&&"readonly",r,n,o,p))}}return t}return d.length?u&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(a(h,d)).then(finish):!u&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&u?[finish(h)]:u?finish(h):Promise.resolve(finish(h))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"revive",value:function revive(t,r){var n=t&&t.$types;if(!n)return t;if(!0===n)return t.$;var a=(r=_objectSpread2(_objectSpread2({sync:!0},this.options),r)).sync,s=[],c={},u=!0;n.$&&isPlainObject(n.$)&&(t=t.$,n=n.$,u=!1);var f=this;function executeReviver(e,t){var r=_slicedToArray(f.revivers[e]||[],1)[0];if(!r)throw new Error("Unregistered type: "+e);return a&&!("revive"in r)?t:r[a&&r.revive?"revive":!a&&r.reviveAsync?"reviveAsync":"revive"](t,c)}var y=[];function checkUndefined(e){return hasConstructorOf(e,l)?void 0:e}var p,d=function revivePlainObjects(){var r=[];if(Object.entries(n).forEach((function(e){var t=_slicedToArray(e,2),a=t[0],o=t[1];"#"!==o&&[].concat(o).forEach((function(e){_slicedToArray(f.revivers[e]||[null,{}],2)[1].plain&&(r.push({keypath:a,type:e}),delete n[a])}))})),r.length)return r.sort(nestedPathsFirst).reduce((function reducer(r,n){var a=n.keypath,o=n.type;if(isThenable(r))return r.then((function(e){return reducer(e,{keypath:a,type:o})}));var i=getByKeyPath(t,a);if(hasConstructorOf(i=executeReviver(o,i),e))return i.then((function(e){var r=setAtKeyPath(t,a,e);r===e&&(t=r)}));var s=setAtKeyPath(t,a,i);s===i&&(t=s)}),void 0)}();return hasConstructorOf(d,e)?p=d.then((function(){return t})):(p=function _revive(t,r,a,c,f){if(!u||"$types"!==t){var p=n[t],d=i(r);if(d||isPlainObject(r)){var b=d?new Array(r.length):{};for(o(r).forEach((function(n){var o=_revive(t+(t?".":"")+escapeKeyPathComponent(n),r[n],a||b,b,n),i=function set(e){return hasConstructorOf(e,l)?b[n]=void 0:void 0!==e&&(b[n]=e),e};hasConstructorOf(o,e)?y.push(o.then((function(e){return i(e)}))):i(o)})),r=b;s.length;){var v=_slicedToArray(s[0],4),h=v[0],g=v[1],m=v[2],O=v[3],S=getByKeyPath(h,g);if(void 0===S)break;m[O]=S,s.splice(0,1)}}if(!p)return r;if("#"===p){var _=getByKeyPath(a,r.slice(1));return void 0===_&&s.push([a,r.slice(1),c,f]),_}return[].concat(p).reduce((function reducer(t,r){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,r)})):executeReviver(r,t)}),r)}}("",t,null),y.length&&(p=e.resolve(p).then((function(t){return e.all([t].concat(y))})).then((function(e){return _slicedToArray(e,1)[0]})))),isThenable(p)?a&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(p,e)?p.p.then(checkUndefined):p:!a&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():a?checkUndefined(p):Promise.resolve(checkUndefined(p))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var r=this;if(i(e))return e.map((function(e){return R.call(r,e)}));e&&o(e).forEach((function(r){if("#"===r)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(r))throw new TypeError("Plain JSON object types are reserved as type names");var n=e[r],a=n&&n.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,o=a.filter((function(e){return e.type===r}));if(o.length&&(a.splice(a.indexOf(o[0]),1),delete this.revivers[r],delete this.types[r]),"function"==typeof n){var s=n;n={test:function test(e){return e&&e.constructor===s},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(s.prototype),e)}}}else if(i(n)){var c=_slicedToArray(n,3);n={test:c[0],replace:c[1],revive:c[2]}}if(n&&n.test){var u={type:r,test:n.test.bind(n)};n.replace&&(u.replace=n.replace.bind(n)),n.replaceAsync&&(u.replaceAsync=n.replaceAsync.bind(n));var l="number"==typeof t.fallback?t.fallback:t.fallback?0:Number.POSITIVE_INFINITY;if(n.testPlainObjects?this.plainObjectReplacers.splice(l,0,u):this.nonplainObjectReplacers.splice(l,0,u),n.revive||n.reviveAsync){var f={};n.revive&&(f.revive=n.revive.bind(n)),n.reviveAsync&&(f.reviveAsync=n.reviveAsync.bind(n)),this.revivers[r]=[f,{plain:n.testPlainObjects}]}this.types[r]=n}}),this)}),this),this}}]),Typeson}(),l=function Undefined(){_classCallCheck(this,Undefined)};l.__typeson__type__="TypesonUndefined",u.Undefined=l,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=n(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"];for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",y=new Uint8Array(256),p=0;p<f.length;p++)y[f.charCodeAt(p)]=p;var d=function encode(e,t,r){null==r&&(r=e.byteLength);for(var n=new Uint8Array(e,t||0,r),a=n.length,o="",i=0;i<a;i+=3)o+=f[n[i]>>2],o+=f[(3&n[i])<<4|n[i+1]>>4],o+=f[(15&n[i+1])<<2|n[i+2]>>6],o+=f[63&n[i+2]];return a%3==2?o=o.slice(0,-1)+"=":a%3==1&&(o=o.slice(0,-2)+"=="),o},b=function decode(e){var t,r,n,a,o=e.length,i=.75*e.length,s=0;"="===e[e.length-1]&&(i--,"="===e[e.length-2]&&i--);for(var c=new ArrayBuffer(i),u=new Uint8Array(c),l=0;l<o;l+=4)t=y[e.charCodeAt(l)],r=y[e.charCodeAt(l+1)],n=y[e.charCodeAt(l+2)],a=y[e.charCodeAt(l+3)],u[s++]=t<<2|r>>4,u[s++]=(15&r)<<4|n>>2,u[s++]=(3&n)<<6|63&a;return c};const v={arraybuffer:{test:e=>"ArrayBuffer"===u.toStringTag(e),replace(e,t){t.buffers||(t.buffers=[]);const r=t.buffers.indexOf(e);return r>-1?{index:r}:(t.buffers.push(e),d(e))},revive(e,t){if(t.buffers||(t.buffers=[]),"object"==typeof e)return t.buffers[e.index];const r=b(e);return t.buffers.push(r),r}}},h={bigintObject:{test:e=>"object"==typeof e&&u.hasConstructorOf(e,BigInt),replace:e=>String(e),revive:e=>new Object(BigInt(e))}},g={bigint:{test:e=>"bigint"==typeof e,replace:e=>String(e),revive:e=>BigInt(e)}};function string2arraybuffer(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer}const m={blob:{test:e=>"Blob"===u.toStringTag(e),replace(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return{type:e.type,stringContents:t.responseText}},revive:({type:e,stringContents:t})=>new Blob([string2arraybuffer(t)],{type:e}),replaceAsync:e=>new u.Promise(((t,r)=>{const n=new FileReader;n.addEventListener("load",(()=>{t({type:e.type,stringContents:n.result})})),n.addEventListener("error",(()=>{r(n.error)})),n.readAsBinaryString(e)}))}};function generateUUID(){let e=Date.now()+("undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():0);return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,(function(t){const r=Math.trunc((e+16*Math.random())%16);return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)}))}const O={},S={cloneable:{test:e=>e&&"object"==typeof e&&"function"==typeof e[Symbol.for("cloneEncapsulate")],replace(e){const t=e[Symbol.for("cloneEncapsulate")](),r=generateUUID();return O[r]=e,{uuid:r,encapsulated:t}},revive:({uuid:e,encapsulated:t})=>O[e][Symbol.for("cloneRevive")](t)}},_={cryptokey:{test:e=>"CryptoKey"===u.toStringTag(e)&&e.extractable,replaceAsync:e=>new u.Promise(((t,r)=>{crypto.subtle.exportKey("jwk",e).catch((e=>{r(e)})).then((r=>{t({jwk:r,algorithm:e.algorithm,usages:e.usages})}))})),revive:({jwk:e,algorithm:t,usages:r})=>crypto.subtle.importKey("jwk",e,t,!0,r)}},j={dataview:{test:e=>"DataView"===u.toStringTag(e),replace({buffer:e,byteOffset:t,byteLength:r},n){n.buffers||(n.buffers=[]);const a=n.buffers.indexOf(e);return a>-1?{index:a,byteOffset:t,byteLength:r}:(n.buffers.push(e),{encoded:d(e),byteOffset:t,byteLength:r})},revive(e,t){t.buffers||(t.buffers=[]);const{byteOffset:r,byteLength:n,encoded:a,index:o}=e;let i;return"index"in e?i=t.buffers[o]:(i=b(a),t.buffers.push(i)),new DataView(i,r,n)}}},A={date:{test:e=>"Date"===u.toStringTag(e),replace(e){const t=e.getTime();return Number.isNaN(t)?"NaN":t},revive:e=>"NaN"===e?new Date(Number.NaN):new Date(e)}},w={error:{test:e=>"Error"===u.toStringTag(e),replace:({name:e,message:t})=>({name:e,message:t}),revive({name:e,message:t}){const r=new Error(t);return r.name=e,r}}},T="undefined"==typeof self?global:self,I={};["TypeError","RangeError","SyntaxError","ReferenceError","EvalError","URIError","InternalError"].forEach((e=>{const t=T[e];t&&(I[e.toLowerCase()]={test:e=>u.hasConstructorOf(e,t),replace:e=>e.message,revive:e=>new t(e)})}));const P={file:{test:e=>"File"===u.toStringTag(e),replace(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad File access: "+t.status);return{type:e.type,stringContents:t.responseText,name:e.name,lastModified:e.lastModified}},revive:({name:e,type:t,stringContents:r,lastModified:n})=>new File([string2arraybuffer(r)],e,{type:t,lastModified:n}),replaceAsync:e=>new u.Promise((function(t,r){const n=new FileReader;n.addEventListener("load",(function(){t({type:e.type,stringContents:n.result,name:e.name,lastModified:e.lastModified})})),n.addEventListener("error",(function(){r(n.error)})),n.readAsBinaryString(e)}))}},N={file:P.file,filelist:{test:e=>"FileList"===u.toStringTag(e),replace(e){const t=[];for(let r=0;r<e.length;r++)t[r]=e.item(r);return t},revive(e){class FileList{constructor(){this._files=arguments[0],this.length=this._files.length}item(e){return this._files[e]}get[Symbol.toStringTag](){return"FileList"}}return new FileList(e)}}},C={imagebitmap:{test:e=>"ImageBitmap"===u.toStringTag(e)||e&&e.dataset&&"ImageBitmap"===e.dataset.toStringTag,replace(e){const t=document.createElement("canvas");return t.getContext("2d").drawImage(e,0,0),t.toDataURL()},revive(e){const t=document.createElement("canvas"),r=t.getContext("2d"),n=document.createElement("img");return n.addEventListener("load",(function(){r.drawImage(n,0,0)})),n.src=e,t},reviveAsync(e){const t=document.createElement("canvas"),r=t.getContext("2d"),n=document.createElement("img");return n.addEventListener("load",(function(){r.drawImage(n,0,0)})),n.src=e,createImageBitmap(t)}}},x={imagedata:{test:e=>"ImageData"===u.toStringTag(e),replace:e=>({array:[...e.data],width:e.width,height:e.height}),revive:e=>new ImageData(new Uint8ClampedArray(e.array),e.width,e.height)}},E={infinity:{test:e=>e===Number.POSITIVE_INFINITY,replace:e=>"Infinity",revive:e=>Number.POSITIVE_INFINITY}},k={IntlCollator:{test:e=>u.hasConstructorOf(e,Intl.Collator),replace:e=>e.resolvedOptions(),revive:e=>new Intl.Collator(e.locale,e)},IntlDateTimeFormat:{test:e=>u.hasConstructorOf(e,Intl.DateTimeFormat),replace:e=>e.resolvedOptions(),revive:e=>new Intl.DateTimeFormat(e.locale,e)},IntlNumberFormat:{test:e=>u.hasConstructorOf(e,Intl.NumberFormat),replace:e=>e.resolvedOptions(),revive:e=>new Intl.NumberFormat(e.locale,e)}},B={map:{test:e=>"Map"===u.toStringTag(e),replace:e=>[...e.entries()],revive:e=>new Map(e)}},U={nan:{test:e=>Number.isNaN(e),replace:e=>"NaN",revive:e=>Number.NaN}},K={negativeInfinity:{test:e=>e===Number.NEGATIVE_INFINITY,replace:e=>"-Infinity",revive:e=>Number.NEGATIVE_INFINITY}},L={nonbuiltinIgnore:{test:e=>e&&"object"==typeof e&&!Array.isArray(e)&&!["Object","Boolean","Number","String","Error","RegExp","Math","Date","Map","Set","JSON","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","Promise","String Iterator","Array Iterator","Map Iterator","Set Iterator","WeakMap","WeakSet","Atomics","Module"].includes(u.toStringTag(e)),replace(e){}}},F={StringObject:{test:e=>"String"===u.toStringTag(e)&&"object"==typeof e,replace:e=>String(e),revive:e=>new String(e)},BooleanObject:{test:e=>"Boolean"===u.toStringTag(e)&&"object"==typeof e,replace:e=>Boolean(e),revive:e=>new Boolean(e)},NumberObject:{test:e=>"Number"===u.toStringTag(e)&&"object"==typeof e,replace:e=>Number(e),revive:e=>new Number(e)}},D={regexp:{test:e=>"RegExp"===u.toStringTag(e),replace:e=>({source:e.source,flags:(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.sticky?"y":"")+(e.unicode?"u":"")}),revive:({source:e,flags:t})=>new RegExp(e,t)}},M={},$={resurrectable:{test:e=>e&&!Array.isArray(e)&&["object","function","symbol"].includes(typeof e),replace(e){const t=generateUUID();return M[t]=e,t},revive:e=>M[e]}},J={set:{test:e=>"Set"===u.toStringTag(e),replace:e=>[...e.values()],revive:e=>new Set(e)}},V="undefined"==typeof self?global:self,Y={};["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"].forEach((function(e){const t=e,r=V[e];r&&(Y[e.toLowerCase()]={test:e=>u.toStringTag(e)===t,replace:e=>(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e:e.slice(0)).buffer,revive:e=>"ArrayBuffer"===u.toStringTag(e)?new r(e):e})}));const q="undefined"==typeof self?global:self,W={};["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"].forEach((function(e){const t=e,r=q[t];r&&(W[e.toLowerCase()]={test:e=>u.toStringTag(e)===t,replace({buffer:e,byteOffset:t,length:r},n){n.buffers||(n.buffers=[]);const a=n.buffers.indexOf(e);return a>-1?{index:a,byteOffset:t,length:r}:(n.buffers.push(e),{encoded:d(e),byteOffset:t,length:r})},revive(e,t){t.buffers||(t.buffers=[]);const{byteOffset:n,length:a,encoded:o,index:i}=e;let s;return"index"in e?s=t.buffers[i]:(s=b(o),t.buffers.push(s)),new r(s,n,a)}})}));const G={undef:{test:(e,t)=>void 0===e&&(t.ownKeys||!("ownKeys"in t)),replace:e=>0,revive:e=>new u.Undefined}},H={userObject:{test:(e,t)=>u.isUserObject(e),replace:e=>({...e}),revive:e=>e}},X=[{arrayNonindexKeys:{testPlainObjects:!0,test:(e,t)=>!!Array.isArray(e)&&(Object.keys(e).some((e=>String(Number.parseInt(e))!==e))&&(t.iterateIn="object",t.addLength=!0),!0),replace:(e,t)=>(t.iterateUnsetNumeric=!0,e),revive(e){if(Array.isArray(e))return e;const t=[];return Object.keys(e).forEach((r=>{const n=e[r];t[r]=n})),t}}},{sparseUndefined:{test:(e,t)=>void 0===e&&!1===t.ownKeys,replace:e=>0,revive(e){}}}],z=[U,E,K],Q=[G,X,F,z,A,w,I,D].concat("function"==typeof Map?B:[],"function"==typeof Set?J:[],"function"==typeof ArrayBuffer?v:[],"function"==typeof Uint8Array?W:[],"function"==typeof DataView?j:[],"undefined"!=typeof Intl?k:[],"undefined"!=typeof BigInt?[g,h]:[]),Z=[w,I],ee=[Q,{arraybuffer:null},Y],te=[{sparseArrays:{testPlainObjects:!0,test:e=>Array.isArray(e),replace:(e,t)=>(t.iterateUnsetNumeric=!0,e)}},{sparseUndefined:{test:(e,t)=>void 0===e&&!1===t.ownKeys,replace:e=>0,revive(e){}}}],re=[H,G,X,F,z,A,D,x,C,P,N,m].concat("function"==typeof Map?B:[],"function"==typeof Set?J:[],"function"==typeof ArrayBuffer?v:[],"function"==typeof Uint8Array?W:[],"function"==typeof DataView?j:[],"undefined"!=typeof Intl?k:[],"undefined"!=typeof crypto?_:[],"undefined"!=typeof BigInt?[g,h]:[]);var ne=re.concat({checkDataCloneException:{test(e){const t={}.toString.call(e).slice(8,-1);if(["symbol","function"].includes(typeof e)||["Arguments","Module","Error","Promise","WeakMap","WeakSet","Event","MessageChannel"].includes(t)||e&&"object"==typeof e&&"number"==typeof e.nodeType&&"function"==typeof e.insertBefore)throw new DOMException("The object cannot be cloned.","DataCloneError");return!1}}});const ae=[te,G],oe=[Q];u.types={arraybuffer:v,bigintObject:h,bigint:g,blob:m,cloneable:S,cryptokey:_,dataview:j,date:A,error:w,errors:I,file:P,filelist:N,imagebitmap:C,imagedata:x,infinity:E,intlTypes:k,map:B,nan:U,negativeInfinity:K,nonbuiltinIgnore:L,primitiveObjects:F,regexp:D,resurrectable:$,set:J,typedArraysSocketio:Y,typedArrays:W,undef:G,userObject:H},u.presets={arrayNonindexKeys:X,builtin:Q,postmessage:Z,socketio:ee,sparseUndefined:te,specialNumbers:z,structuredCloningThrowing:ne,structuredCloning:re,undef:ae,universal:oe};export default u;
function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n);}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t));}));}return e}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 r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==r)return;var n,a,o=[],i=!0,c=!1;try{for(r=r.call(e);!(i=(n=r.next()).done)&&(o.push(n.value),!t||o.length!==t);i=!0);}catch(e){c=!0,a=e;}finally{try{i||null==r.return||r.return();}finally{if(c)throw a}}return o}(e,t)||_unsupportedIterableToArray(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}(e)||function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||_unsupportedIterableToArray(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return "Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var e=_createClass((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,r){var n=this;return new e((function(e,a){n.p.then((function(r){e(t?t(r):r);})).catch((function(e){return r?r(e):Promise.reject(e)})).then(e,a);}))},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,r){r(t);}))},["all","race","allSettled"].forEach((function(t){e[t]=function(r){return new e((function(e,n){Promise[t](r.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,n);}))};}));var t={}.toString,r={}.hasOwnProperty,n=Object.getPrototypeOf,a=r.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=n(e);if(!o)return null===t;var i=r.call(o,"constructor")&&o.constructor;return "function"!=typeof i?null===t:t===i||(null!==t&&a.call(i)===a.call(t)||"function"==typeof t&&"string"==typeof i.__typeson__type__&&i.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return !(!e||"Object"!==toStringTag(e))&&(!n(e)||hasConstructorOf(e,Object))}function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var t=n(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 r=t.indexOf(".");if(r>-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(""===t)return r;var n=t.indexOf(".");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)}function _await(e,t,r){return r?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}var o=Object.keys,i$1=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function _async(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];try{return Promise.resolve(e.apply(this,t))}catch(e){return Promise.reject(e)}}}function nestedPathsFirst(e,t){if(""===e.keypath)return -1;var r=e.keypath.match(/\./g)||0,n=t.keypath.match(/\./g)||0;return r&&(r=r.length),n&&(n=n.length),r>n?-1:r<n?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 _createClass(Typeson,[{key:"stringify",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var a=this.encapsulate(e,null,n);return i$1(a)?JSON.stringify(a[0],t,r):a.then((function(e){return JSON.stringify(e,t,r)}))}},{key:"stringifySync",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:"parse",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:"parseSync",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:"rootTypeName",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:"encapsulate",value:function encapsulate(t,r,n){var a=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var o=!1,i=[],c=_slicedToArray(r.splice(0,1),1),s=_slicedToArray(c[0],7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,n,p,y,i,!0,h),d=hasConstructorOf(v,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(u&&d)return _await(v.p,(function(e){l[f]=e;var r=a(t,i);return o=!0,r}))}),(function(e){return o?e:(u?l[f]=v:t=d?v.p:v,a(t,i))}))})))),(function(){return t}))}))})),u=(n=_objectSpread2(_objectSpread2({sync:!0},this.options),n)).sync,p=this,y={},l=[],f=[],h=[],v=!("cyclic"in n)||n.cyclic,d=n.encapsulateObserver,b=_encapsulate("",t,v,r||{},h);function finish(e){var t=Object.values(y);if(n.iterateNone)return t.length?t[0]:getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=y:e={$:e,$types:{$:y}};}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return !n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=s.map((function(t){var r=e[t];return delete e[t],r}));r(),s.forEach((function(t,r){e[t]=n[r];}));}function _encapsulate(t,r,a,s,u,h,v){var b,_={},O=_typeof(r),j=d?function(n){var o=v||s.type||getJSONType(r);d(Object.assign(n||_,{keypath:t,value:r,cyclic:a,stateObj:s,promisesData:u,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:o}));}:null;if(["string","boolean","number","undefined"].includes(O))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY?(b=s.replaced?r:replace(t,r,s,u,!1,h,j))!==r&&(_={replaced:b}):b=r,j&&j(),b;if(null===r)return j&&j(),r;if(a&&!s.iterateIn&&!s.iterateUnsetNumeric&&r&&"object"===_typeof(r)){var m=l.indexOf(r);if(!(m<0))return y[t]="#",j&&j({cyclicKeypath:f[m]}),"#"+f[m];!0===a&&(l.push(r),f.push(t));}var S,g=isPlainObject(r),P=i$1(r),T=(g||P)&&(!p.plainObjectReplacers.length||s.replaced)||s.iterateIn?r:replace(t,r,s,u,g||P,null,j);if(T!==r?(b=T,_={replaced:T}):""===t&&hasConstructorOf(r,e)?(u.push([t,r,a,s,void 0,void 0,s.type]),b=r):P&&"object"!==s.iterateIn||"array"===s.iterateIn?(S=new Array(r.length),_={clone:S}):(["function","symbol"].includes(_typeof(r))||"toJSON"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!g&&"object"!==s.iterateIn?b=r:(S={},s.addLength&&(S.length=r.length),_={clone:S}),j&&j(),n.iterateNone)return S||b;if(!S)return b;if(s.iterateIn){var w=function _loop(n){var o={ownKeys:c.call(r,n)};_adaptBuiltinStateObjectProperties(s,o,(function(){var o=t+(t?".":"")+escapeKeyPathComponent(n),i=_encapsulate(o,r[n],Boolean(a),s,u,h);hasConstructorOf(i,e)?u.push([o,i,Boolean(a),s,S,n,s.type]):void 0!==i&&(S[n]=i);}));};for(var A in r)w(A);j&&j({endIterateIn:!0,end:!0});}else o(r).forEach((function(n){var o=t+(t?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(o,r[n],Boolean(a),s,u,h);hasConstructorOf(t,e)?u.push([o,t,Boolean(a),s,S,n,s.type]):void 0!==t&&(S[n]=t);}));})),j&&j({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=r.length,k=function _loop2(n){if(!(n in r)){var o=t+(t?".":"")+n;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(o,void 0,Boolean(a),s,u,h);hasConstructorOf(t,e)?u.push([o,t,Boolean(a),s,S,n,s.type]):void 0!==t&&(S[n]=t);}));}},N=0;N<C;N++)k(N);j&&j({endIterateUnsetNumeric:!0,end:!0});}return S}function replace(e,t,r,n,a,o,i){for(var c=a?p.plainObjectReplacers:p.nonplainObjectReplacers,s=c.length;s--;){var l=c[s];if(l.test(t,r)){var f=l.type;if(p.revivers[f]){var h=y[e];y[e]=h?[f].concat(h):f;}return Object.assign(r,{type:f,replaced:!0}),!u&&l.replaceAsync||l.replace?(i&&i({replacing:!0}),_encapsulate(e,l[u||!l.replaceAsync?"replace":"replaceAsync"](t,r),v&&"readonly",r,n,o,f)):(i&&i({typeDetected:!0}),_encapsulate(e,t,v&&"readonly",r,n,o,f))}}return t}return h.length?u&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(a(b,h)).then(finish):!u&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&u?[finish(b)]:u?finish(b):Promise.resolve(finish(b))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"revive",value:function revive(t,r){var n=t&&t.$types;if(!n)return t;if(!0===n)return t.$;var a=(r=_objectSpread2(_objectSpread2({sync:!0},this.options),r)).sync,c=[],s={},u=!0;n.$&&isPlainObject(n.$)&&(t=t.$,n=n.$,u=!1);var y=this;function executeReviver(e,t){var r=_slicedToArray(y.revivers[e]||[],1)[0];if(!r)throw new Error("Unregistered type: "+e);return a&&!("revive"in r)?t:r[a&&r.revive?"revive":!a&&r.reviveAsync?"reviveAsync":"revive"](t,s)}var l=[];function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var f,h=function revivePlainObjects(){var r=[];if(Object.entries(n).forEach((function(e){var t=_slicedToArray(e,2),a=t[0],o=t[1];"#"!==o&&[].concat(o).forEach((function(e){_slicedToArray(y.revivers[e]||[null,{}],2)[1].plain&&(r.push({keypath:a,type:e}),delete n[a]);}));})),r.length)return r.sort(nestedPathsFirst).reduce((function reducer(r,n){var a=n.keypath,o=n.type;if(isThenable(r))return r.then((function(e){return reducer(e,{keypath:a,type:o})}));var i=getByKeyPath(t,a);if(hasConstructorOf(i=executeReviver(o,i),e))return i.then((function(e){var r=setAtKeyPath(t,a,e);r===e&&(t=r);}));var c=setAtKeyPath(t,a,i);c===i&&(t=c);}),void 0)}();return hasConstructorOf(h,e)?f=h.then((function(){return t})):(f=function _revive(t,r,a,s,y){if(!u||"$types"!==t){var f=n[t],h=i$1(r);if(h||isPlainObject(r)){var v=h?new Array(r.length):{};for(o(r).forEach((function(n){var o=_revive(t+(t?".":"")+escapeKeyPathComponent(n),r[n],a||v,v,n),i=function set(e){return hasConstructorOf(e,p)?v[n]=void 0:void 0!==e&&(v[n]=e),e};hasConstructorOf(o,e)?l.push(o.then((function(e){return i(e)}))):i(o);})),r=v;c.length;){var d=_slicedToArray(c[0],4),b=d[0],_=d[1],O=d[2],j=d[3],m=getByKeyPath(b,_);if(void 0===m)break;O[j]=m,c.splice(0,1);}}if(!f)return r;if("#"===f){var S=getByKeyPath(a,r.slice(1));return void 0===S&&c.push([a,r.slice(1),s,y]),S}return [].concat(f).reduce((function reducer(t,r){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,r)})):executeReviver(r,t)}),r)}}("",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)?a&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(f,e)?f.p.then(checkUndefined):f:!a&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():a?checkUndefined(f):Promise.resolve(checkUndefined(f))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!1}))}},{key:"register",value:function register(e,t){var r=this;t=t||{};var n=function R(e){i$1(e)?e.forEach((function(e){return R(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(y.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var a=e[n],o=a&&a.testPlainObjects?r.plainObjectReplacers:r.nonplainObjectReplacers,c=o.filter((function(e){return e.type===n}));if(c.length&&(o.splice(o.indexOf(c[0]),1),delete r.revivers[n],delete r.types[n]),"function"==typeof a){var s=a;a={test:function test(e){return e&&e.constructor===s},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(s.prototype),e)}};}else if(i$1(a)){var u=_slicedToArray(a,3);a={test:u[0],replace:u[1],revive:u[2]};}if(a&&a.test){var p={type:n,test:a.test.bind(a)};a.replace&&(p.replace=a.replace.bind(a)),a.replaceAsync&&(p.replaceAsync=a.replaceAsync.bind(a));var l="number"==typeof t.fallback?t.fallback:t.fallback?0:Number.POSITIVE_INFINITY;if(a.testPlainObjects?r.plainObjectReplacers.splice(l,0,p):r.nonplainObjectReplacers.splice(l,0,p),a.revive||a.reviveAsync){var f={};a.revive&&(f.revive=a.revive.bind(a)),a.reviveAsync&&(f.reviveAsync=a.reviveAsync.bind(a)),r.revivers[n]=[f,{plain:a.testPlainObjects}];}r.types[n]=a;}}));};return [].concat(e).forEach((function(e){return n(e)})),this}}]),Typeson}(),p=_createClass((function Undefined(){_classCallCheck(this,Undefined);}));p.__typeson__type__="TypesonUndefined";var y=["null","boolean","number","string","array","object"];
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.
var lookup = new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.codePointAt(i)] = i;
}
/**
* @param {ArrayBuffer} arraybuffer
* @param {Integer} byteOffset
* @param {Integer} lngth
* @returns {string}
*/
var encode = function encode(arraybuffer, byteOffset, lngth) {
if (lngth === null || lngth === undefined) {
lngth = arraybuffer.byteLength; // Needed for Safari
}
var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari
lngth);
var len = bytes.length;
var base64 = '';
for (var _i = 0; _i < len; _i += 3) {
base64 += chars[bytes[_i] >> 2];
base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];
base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];
base64 += chars[bytes[_i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.slice(0, -1) + '=';
} else if (len % 3 === 1) {
base64 = base64.slice(0, -2) + '==';
}
return base64;
};
/**
* @param {string} base64
* @returns {ArrayBuffer}
*/
var decode = function decode(base64) {
var len = base64.length;
var bufferLength = base64.length * 0.75;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (var _i2 = 0; _i2 < len; _i2 += 4) {
encoded1 = lookup[base64.codePointAt(_i2)];
encoded2 = lookup[base64.codePointAt(_i2 + 1)];
encoded3 = lookup[base64.codePointAt(_i2 + 2)];
encoded4 = lookup[base64.codePointAt(_i2 + 3)];
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return arraybuffer;
};
const arraybuffer = {
arraybuffer: {
test (x) { return toStringTag(x) === 'ArrayBuffer'; },
replace (b, stateObj) {
if (!stateObj.buffers) {
stateObj.buffers = [];
}
const index = stateObj.buffers.indexOf(b);
if (index > -1) {
return {index};
}
stateObj.buffers.push(b);
return encode(b);
},
revive (b64, stateObj) {
if (!stateObj.buffers) {
stateObj.buffers = [];
}
if (typeof b64 === 'object') {
return stateObj.buffers[b64.index];
}
const buffer = decode(b64);
stateObj.buffers.push(buffer);
return buffer;
}
}
};
// See also typed-arrays!
/* globals BigInt */
const bigintObject = {
bigintObject: {
test (x) {
return typeof x === 'object' && hasConstructorOf(x, BigInt);
},
replace (n) { return String(n); },
revive (s) {
// Filed this to avoid error: https://github.com/eslint/eslint/issues/11810
// eslint-disable-next-line no-new-object
return new Object(BigInt(s));
}
}
};
/* globals BigInt */
const bigint = {
bigint: {
test (x) {
return typeof x === 'bigint';
},
replace (n) { return String(n); },
revive (s) { return BigInt(s); }
}
};
/**
* Not currently in use internally, but provided for parity.
* @param {ArrayBuffer} buf
* @returns {Uint8Array}
*/
/**
*
* @param {string} str
* @returns {ArrayBuffer}
*/
function string2arraybuffer (str) {
/*
// UTF-8 approaches
const utf8 = unescape(encodeURIComponent(str));
const arr = new Uint8Array(utf8.length);
for (let i = 0; i < utf8.length; i++) {
arr[i] = utf8.charCodeAt(i);
}
return arr.buffer;
const utf8 = [];
for (let i = 0; i < str.length; i++) {
let charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
} else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f));
// surrogate pair
} else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff) << 10) |
(str.charCodeAt(i) & 0x3ff));
utf8.push(0xf0 | (charcode >> 18),
0x80 | ((charcode >> 12) & 0x3f),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f));
}
}
return utf8;
*/
/*
// Working UTF-16 options (equivalents)
const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
const bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
*/
const array = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
// eslint-disable-next-line max-len -- Long
// eslint-disable-next-line unicorn/prefer-code-point -- Iterating char. codes
array[i] = str.charCodeAt(i); // & 0xff;
}
return array.buffer;
}
/* globals XMLHttpRequest, Blob, FileReader */
const blob = {
blob: {
test (x) { return toStringTag(x) === 'Blob'; },
replace (b) { // Sync
const req = new XMLHttpRequest();
req.overrideMimeType('text/plain; charset=x-user-defined');
req.open('GET', URL.createObjectURL(b), false); // Sync
req.send();
// Seems not feasible to accurately simulate
/* c8 ignore next 3 */
if (req.status !== 200 && req.status !== 0) {
throw new Error('Bad Blob access: ' + req.status);
}
return {
type: b.type,
stringContents: req.responseText
};
},
revive ({type, stringContents}) {
return new Blob([string2arraybuffer(stringContents)], {type});
},
replaceAsync (b) {
return new e((resolve, reject) => {
/*
if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob
reject(new Error('The Blob is closed'));
return;
}
*/
const reader = new FileReader();
reader.addEventListener('load', () => {
resolve({
type: b.type,
stringContents: reader.result
});
});
// Seems not feasible to accurately simulate
/* c8 ignore next 3 */
reader.addEventListener('error', () => {
reject(reader.error);
});
reader.readAsBinaryString(b);
});
}
}
};
/* globals performance */
// The `performance` global is optional
/**
* @todo We could use `import generateUUID from 'uuid/v4';` (but it needs
* crypto library, etc.; `rollup-plugin-node-builtins` doesn't recommend
* using its own version and though there is <https://www.npmjs.com/package/crypto-browserify>,
* it may be troublesome to bundle and not strongly needed)
* @returns {string}
*/
function generateUUID () { // Adapted from original: public domain/MIT: http://stackoverflow.com/a/8809472/271577
/* c8 ignore next */
let d = Date.now() +
// use high-precision timer if available
/* c8 ignore next 4 */
(typeof performance !== 'undefined' &&
typeof performance.now === 'function'
? performance.now()
: 0);
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/gu, function (c) {
/* eslint-disable no-bitwise */
const r = Math.trunc((d + Math.random() * 16) % 16);
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
/* eslint-enable no-bitwise */
});
}
const cloneableObjectsByUUID = {};
const cloneable = {
cloneable: {
test (x) {
return x && typeof x === 'object' &&
typeof x[Symbol.for('cloneEncapsulate')] === 'function';
},
replace (clonable) {
const encapsulated = clonable[Symbol.for('cloneEncapsulate')]();
const uuid = generateUUID();
cloneableObjectsByUUID[uuid] = clonable;
return {uuid, encapsulated};
},
revive ({uuid, encapsulated}) {
return cloneableObjectsByUUID[uuid][Symbol.for('cloneRevive')](
encapsulated
);
}
}
};
/* globals crypto */
const cryptokey = {
cryptokey: {
test (x) {
return toStringTag(x) === 'CryptoKey' && x.extractable;
},
replaceAsync (key) {
return new e(async (resolve, reject) => {
let jwk;
try {
jwk = await crypto.subtle.exportKey('jwk', key);
// Our format should be valid and our key extractable
/* c8 ignore next 4 */
} catch (err) {
reject(err);
return;
}
resolve({
jwk,
algorithm: key.algorithm,
usages: key.usages
});
});
},
revive ({jwk, algorithm, usages}) {
return crypto.subtle.importKey('jwk', jwk, algorithm, true, usages);
}
}
};
const dataview = {
dataview: {
test (x) { return toStringTag(x) === 'DataView'; },
replace ({buffer, byteOffset, byteLength}, stateObj) {
if (!stateObj.buffers) {
stateObj.buffers = [];
}
const index = stateObj.buffers.indexOf(buffer);
if (index > -1) {
return {index, byteOffset, byteLength};
}
stateObj.buffers.push(buffer);
return {
encoded: encode(buffer),
byteOffset,
byteLength
};
},
revive (b64Obj, stateObj) {
if (!stateObj.buffers) {
stateObj.buffers = [];
}
const {byteOffset, byteLength, encoded, index} = b64Obj;
let buffer;
if ('index' in b64Obj) {
buffer = stateObj.buffers[index];
} else {
buffer = decode(encoded);
stateObj.buffers.push(buffer);
}
return new DataView(buffer, byteOffset, byteLength);
}
}
};
const date = {
date: {
test (x) { return toStringTag(x) === 'Date'; },
replace (dt) {
const time = dt.getTime();
if (Number.isNaN(time)) {
return 'NaN';
}
return time;
},
revive (time) {
if (time === 'NaN') {
return new Date(Number.NaN);
}
return new Date(time);
}
}
};
const error = {
error: {
test (x) { return toStringTag(x) === 'Error'; },
replace ({name, message}) {
return {name, message};
},
revive ({name, message}) {
const e = new Error(message);
e.name = name;
return e;
}
}
};
/* eslint-env browser, node */
/* c8 ignore next */
const _global$2 = typeof self === 'undefined' ? global : self;
const errors = {};
// Comprises all built-in errors.
[
'TypeError',
'RangeError',
'SyntaxError',
'ReferenceError',
'EvalError',
'URIError',
'InternalError' // non-standard
].forEach((errName) => {
const Cnstrctr = _global$2[errName];
if (Cnstrctr) {
errors[errName.toLowerCase()] = {
test (x) { return hasConstructorOf(x, Cnstrctr); },
replace (e) { return e.message; },
revive (message) { return new Cnstrctr(message); }
};
}
});
/* globals XMLHttpRequest, File, FileReader */
const file = {
file: {
test (x) { return toStringTag(x) === 'File'; },
replace (f) { // Sync
const req = new XMLHttpRequest();
req.overrideMimeType('text/plain; charset=x-user-defined');
req.open('GET', URL.createObjectURL(f), false); // Sync
req.send();
// Seems not feasible to accurately simulate
/* c8 ignore next 3 */
if (req.status !== 200 && req.status !== 0) {
throw new Error('Bad File access: ' + req.status);
}
return {
type: f.type,
stringContents: req.responseText,
name: f.name,
lastModified: f.lastModified
};
},
revive ({name, type, stringContents, lastModified}) {
return new File([string2arraybuffer(stringContents)], name, {
type,
lastModified
});
},
replaceAsync (f) {
return new e(function (resolve, reject) {
/*
if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob
reject(new Error('The File is closed'));
return;
}
*/
const reader = new FileReader();
reader.addEventListener('load', function () {
resolve({
type: f.type,
stringContents: reader.result,
name: f.name,
lastModified: f.lastModified
});
});
// Seems not feasible to accurately simulate
/* c8 ignore next 3 */
reader.addEventListener('error', function () {
reject(reader.error);
});
reader.readAsBinaryString(f);
});
}
}
};
const filelist = {
file: file.file,
filelist: {
test (x) { return toStringTag(x) === 'FileList'; },
replace (fl) {
const arr = [];
for (let i = 0; i < fl.length; i++) {
arr[i] = fl.item(i);
}
return arr;
},
revive (o) {
/**
* `FileList` polyfill.
*/
class FileList {
/**
* Set private properties and length.
*/
constructor () {
// eslint-disable-next-line prefer-rest-params
this._files = arguments[0];
this.length = this._files.length;
}
/**
* @param {Integer} index
* @returns {File}
*/
item (index) {
return this._files[index];
}
/* eslint-disable class-methods-use-this */
/**
* @returns {"FileList"}
*/
get [Symbol.toStringTag] () {
/* eslint-enable class-methods-use-this */
return 'FileList';
}
}
return new FileList(o);
}
}
};
/* globals createImageBitmap */
const imagebitmap = {
imagebitmap: {
test (x) {
return toStringTag(x) === 'ImageBitmap' ||
// In Node, our polyfill sets the dataset on a canvas
// element as JSDom no longer allows overriding toStringTag
(x && x.dataset && x.dataset.toStringTag === 'ImageBitmap');
},
replace (bm) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.drawImage(bm, 0, 0);
// Although `width` and `height` are part of `ImageBitMap`,
// these will be auto-created for us when reviving with the
// data URL (and they are not settable even if they weren't)
// return {
// width: bm.width, height: bm.height, dataURL: canvas.toDataURL()
// };
return canvas.toDataURL();
},
revive (o) {
/*
var req = new XMLHttpRequest();
req.open('GET', o, false); // Sync
if (req.status !== 200 && req.status !== 0) {
throw new Error('Bad ImageBitmap access: ' + req.status);
}
req.send();
return req.responseText;
*/
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = document.createElement('img');
// The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577
img.addEventListener('load', function () {
ctx.drawImage(img, 0, 0);
});
img.src = o;
// Works in contexts allowing an `ImageBitmap` (We might use
// `OffscreenCanvas.transferToBitmap` when supported)
return canvas;
},
reviveAsync (o) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = document.createElement('img');
// The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577
img.addEventListener('load', function () {
ctx.drawImage(img, 0, 0);
});
img.src = o; // o.dataURL;
return createImageBitmap(canvas); // Returns a promise
}
}
};
/* globals ImageData */
const imagedata = {
imagedata: {
test (x) { return toStringTag(x) === 'ImageData'; },
replace (d) {
return {
// Ensure `length` gets preserved for revival
array: [...d.data],
width: d.width,
height: d.height
};
},
revive (o) {
return new ImageData(
new Uint8ClampedArray(o.array), o.width, o.height
);
}
}
};
const infinity = {
infinity: {
test (x) { return x === Number.POSITIVE_INFINITY; },
replace (n) { return 'Infinity'; },
revive (s) { return Number.POSITIVE_INFINITY; }
}
};
const IntlCollator = {
test (x) { return hasConstructorOf(x, Intl.Collator); },
replace (c) { return c.resolvedOptions(); },
revive (options) { return new Intl.Collator(options.locale, options); }
};
const IntlDateTimeFormat = {
test (x) { return hasConstructorOf(x, Intl.DateTimeFormat); },
replace (dtf) { return dtf.resolvedOptions(); },
revive (options) {
return new Intl.DateTimeFormat(options.locale, options);
}
};
const IntlNumberFormat = {
test (x) { return hasConstructorOf(x, Intl.NumberFormat); },
replace (nf) { return nf.resolvedOptions(); },
revive (options) { return new Intl.NumberFormat(options.locale, options); }
};
const intlTypes = {
IntlCollator,
IntlDateTimeFormat,
IntlNumberFormat
};
const map = {
map: {
test (x) { return toStringTag(x) === 'Map'; },
replace (mp) { return [...mp.entries()]; },
revive (entries) { return new Map(entries); }
}
};
const nan = {
nan: {
test (x) { return Number.isNaN(x); },
replace (n) { return 'NaN'; },
revive (s) { return Number.NaN; }
}
};
const negativeInfinity = {
negativeInfinity: {
test (x) { return x === Number.NEGATIVE_INFINITY; },
replace (n) { return '-Infinity'; },
revive (s) { return Number.NEGATIVE_INFINITY; }
}
};
const nonbuiltinIgnore = {
nonbuiltinIgnore: {
test (x) {
return x && typeof x === 'object' && !Array.isArray(x) && ![
'Object',
// `Proxy` and `Reflect`, two other built-in objects, will also
// have a `toStringTag` of `Object`; we don't want built-in
// function objects, however
'Boolean', 'Number', 'String',
'Error', 'RegExp', 'Math', 'Date',
'Map', 'Set',
'JSON',
'ArrayBuffer', 'SharedArrayBuffer', 'DataView',
'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array',
'Uint16Array', 'Int32Array', 'Uint32Array',
'Float32Array', 'Float64Array',
'Promise',
'String Iterator', 'Array Iterator',
'Map Iterator', 'Set Iterator',
'WeakMap', 'WeakSet',
'Atomics', 'Module'
].includes(toStringTag(x));
},
replace (rexp) {
// Not in use
}
}
};
// This module is for objectified primitives (such as `new Number(3)` or
const primitiveObjects = {
// String Object (not primitive string which need no type spec)
StringObject: {
test (x) {
return toStringTag(x) === 'String' && typeof x === 'object';
},
replace (s) { return String(s); }, // convert to primitive string
revive (s) { return new String(s); } // Revive to an objectified string
},
// Boolean Object (not primitive boolean which need no type spec)
BooleanObject: {
test (x) {
return toStringTag(x) === 'Boolean' &&
typeof x === 'object';
},
replace (b) { return Boolean(b); }, // convert to primitive boolean
revive (b) {
// Revive to an objectified Boolean
return new Boolean(b);
}
},
// Number Object (not primitive number which need no type spec)
NumberObject: {
test (x) {
return toStringTag(x) === 'Number' && typeof x === 'object';
},
replace (n) { return Number(n); }, // convert to primitive number
revive (n) { return new Number(n); } // Revive to an objectified number
}
};
const regexp = {
regexp: {
test (x) { return toStringTag(x) === 'RegExp'; },
replace (rexp) {
return {
source: rexp.source,
flags: (rexp.global ? 'g' : '') +
(rexp.ignoreCase ? 'i' : '') +
(rexp.multiline ? 'm' : '') +
(rexp.sticky ? 'y' : '') +
(rexp.unicode ? 'u' : '')
};
},
revive ({source, flags}) { return new RegExp(source, flags); }
}
};
// Here we allow the exact same non-plain object, function, and symbol
const resurrectableObjectsByUUID = {};
const resurrectable = {
resurrectable: {
test (x) {
return x &&
!Array.isArray(x) &&
['object', 'function', 'symbol'].includes(typeof x);
},
replace (rsrrctble) {
const uuid = generateUUID();
resurrectableObjectsByUUID[uuid] = rsrrctble;
return uuid;
},
revive (serializedResurrectable) {
return resurrectableObjectsByUUID[serializedResurrectable];
}
}
};
const set = {
set: {
test (x) { return toStringTag(x) === 'Set'; },
replace (st) {
return [...st.values()];
},
revive (values) { return new Set(values); }
}
};
/* eslint-env browser, node */
/* c8 ignore next */
const _global$1 = typeof self === 'undefined' ? global : self;
// Support all kinds of typed arrays (views of ArrayBuffers)
const typedArraysSocketIO = {};
[
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array'
].forEach(function (typeName) {
const arrType = typeName;
const TypedArray = _global$1[typeName];
/* c8 ignore next 3 */
if (!TypedArray) {
return;
}
typedArraysSocketIO[typeName.toLowerCase()] = {
test (x) { return toStringTag(x) === arrType; },
replace (a) {
return (a.byteOffset === 0 &&
a.byteLength === a.buffer.byteLength
? a
// socket.io supports streaming ArrayBuffers.
// If we have a typed array representing a portion
// of the buffer, we need to clone
// the buffer before leaving it to socket.io.
: a.slice(0)).buffer;
},
revive (buf) {
// One may configure socket.io to revive binary data as
// Buffer or Blob.
// We should therefore not rely on that the instance we
// get here is an ArrayBuffer
// If not, let's assume user wants to receive it as
// configured with socket.io.
return toStringTag(buf) === 'ArrayBuffer'
? new TypedArray(buf)
: buf;
}
};
});
/* eslint-env browser, node */
/* c8 ignore next */
const _global = typeof self === 'undefined' ? global : self;
const typedArrays = {};
[
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array'
].forEach(function (typeName) {
const arrType = typeName;
const TypedArray = _global[arrType];
/* c8 ignore next 3 */
if (!TypedArray) {
return;
}
typedArrays[typeName.toLowerCase()] = {
test (x) { return toStringTag(x) === arrType; },
replace ({buffer, byteOffset, length: l}, stateObj) {
if (!stateObj.buffers) {
stateObj.buffers = [];
}
const index = stateObj.buffers.indexOf(buffer);
if (index > -1) {
return {index, byteOffset, length: l};
}
stateObj.buffers.push(buffer);
return {
encoded: encode(buffer),
byteOffset,
length: l
};
},
revive (b64Obj, stateObj) {
if (!stateObj.buffers) {
stateObj.buffers = [];
}
const {byteOffset, length: len, encoded, index} = b64Obj;
let buffer;
if ('index' in b64Obj) {
buffer = stateObj.buffers[index];
} else {
buffer = decode(encoded);
stateObj.buffers.push(buffer);
}
return new TypedArray(buffer, byteOffset, len);
}
};
});
// This does not preserve `undefined` in sparse arrays; see the `undef`
const undef$1 = {
undef: {
test (x, stateObj) {
return typeof x === 'undefined' &&
(stateObj.ownKeys || !('ownKeys' in stateObj));
},
replace (n) { return 0; },
revive (s) {
// Will add `undefined` (returning `undefined` would instead
// avoid explicitly setting)
return new p();
}
}
};
const userObject = {
userObject: {
test (x, stateObj) { return isUserObject(x); },
replace (n) { return {...n}; },
revive (s) { return s; }
}
};
const arrayNonindexKeys = [
{
arrayNonindexKeys: {
testPlainObjects: true,
test (x, stateObj) {
if (Array.isArray(x)) {
if (
// By avoiding serializing arrays into objects which
// have only positive-integer keys, we reduce
// size and improve revival performance; arrays with
// non-index keys will be larger however
Object.keys(x).some((k) => {
// No need to check for `isNaN` or
// `isNaN(Number.parseInt())` as `NaN` will be
// treated as a string.
// No need to do check as
// `Number.parseInt(Number())` since scientific
// notation will be pre-resolved if a number
// was given, and it will otherwise be a string
return String(Number.parseInt(k)) !== k;
})
) {
stateObj.iterateIn = 'object';
stateObj.addLength = true;
}
return true;
}
return false;
},
replace (a, stateObj) {
// Catch sparse undefined
stateObj.iterateUnsetNumeric = true;
return a;
},
revive (o) {
if (Array.isArray(o)) {
return o;
}
const arr = [];
// No map here as may be a sparse array (including
// with `length` set)
// Todo: Reenable when Node `engines` >= 7
// Object.entries(o).forEach(([key, val]) => {
Object.keys(o).forEach((key) => {
const val = o[key];
arr[key] = val;
});
return arr;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' && stateObj.ownKeys === false;
},
replace (n) { return 0; },
revive (s) { return undefined; } // Will avoid adding anything
}
}
];
const specialNumbers = [
nan,
infinity,
negativeInfinity
];
/* This preset includes types that are built-in into the JavaScript
language itself, this should work universally.
Types that were added in ES6 or beyond will be checked before inclusion
so that this module can be consumed by both ES5 and ES6 environments.
Some types cannot be encapsulated because their inner state is private:
`WeakMap`, `WeakSet`.
The Function type is not included because their closures would not be
serialized, so a revived Function that uses closures would not behave
as expected.
Symbols are similarly not included.
*/
const expObj$1 = [
undef$1,
// ES5
arrayNonindexKeys, primitiveObjects, specialNumbers,
date, error, errors, regexp
].concat(
// ES2015 (ES6)
/* c8 ignore next */
typeof Map === 'function' ? map : [],
/* c8 ignore next */
typeof Set === 'function' ? set : [],
/* c8 ignore next */
typeof ArrayBuffer === 'function' ? arraybuffer : [],
/* c8 ignore next */
typeof Uint8Array === 'function' ? typedArrays : [],
/* c8 ignore next */
typeof DataView === 'function' ? dataview : [],
/* c8 ignore next */
typeof Intl !== 'undefined' ? intlTypes : [],
/* c8 ignore next */
typeof BigInt !== 'undefined' ? [bigint, bigintObject] : []
);
/*
When communicating via `postMessage()` (`Worker.postMessage()` or
`window.postMessage()`), the browser will use a similar algorithm as Typeson
does to encapsulate and revive all items in the structure (aka the structured
clone algorithm). This algorithm supports all built-in types as well as many
DOM types. Therefore, only types that are not included in the structured clone
algorithm need to be registered, which is:
* Error
* Specific Errors like SyntaxError, TypeError, etc.
* Any custom type you want to send across window- or worker boundraries
This preset will only include the Error types and you can register your
custom types after having registered these.
*/
const postmessage = [
error,
errors
];
const socketio = [
expObj$1,
// Leave ArrayBuffer as is, and let socket.io stream it instead.
{arraybuffer: null},
// Encapsulate TypedArrays in ArrayBuffers instead of base64 strings.
typedArraysSocketIO
];
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' && stateObj.ownKeys === false;
},
replace (n) { return 0; },
revive (s) { return undefined; } // Will avoid adding anything
}
}
];
/* This preset includes types for the Structured Cloning Algorithm. */
const expObj = [
// Todo: Might also register synchronous `ImageBitmap` and
// `Blob`/`File`/`FileList`?
// ES5
userObject, // Processed last (non-builtin)
undef$1,
arrayNonindexKeys, primitiveObjects, specialNumbers,
date, regexp,
// Non-built-ins
imagedata,
imagebitmap, // Async return
file,
filelist,
blob
].concat(
// ES2015 (ES6)
/* c8 ignore next */
typeof Map === 'function' ? map : [],
/* c8 ignore next */
typeof Set === 'function' ? set : [],
/* c8 ignore next */
typeof ArrayBuffer === 'function' ? arraybuffer : [],
/* c8 ignore next */
typeof Uint8Array === 'function' ? typedArrays : [],
/* c8 ignore next */
typeof DataView === 'function' ? dataview : [],
/* c8 ignore next */
typeof Intl !== 'undefined' ? intlTypes : [],
/* c8 ignore next */
typeof crypto !== 'undefined' ? cryptokey : [],
/* c8 ignore next */
typeof BigInt !== 'undefined' ? [bigint, bigintObject] : []
);
/* globals DOMException */
var structuredCloningThrowing = expObj.concat({
checkDataCloneException: {
test (val) {
// Should also throw with:
// 1. `IsDetachedBuffer` (a process not called within the
// ECMAScript spec)
// 2. `IsCallable` (covered by `typeof === 'function'` or a
// function's `toStringTag`)
// 3. internal slots besides [[Prototype]] or [[Extensible]] (e.g.,
// [[PromiseState]] or [[WeakMapData]])
// 4. exotic object (e.g., `Proxy`) (unless an `%ObjectPrototype%`
// intrinsic object) (which does not have default
// behavior for one or more of the essential internal methods
// that are limited to the following for non-function objects
// (we auto-exclude functions):
// [[GetPrototypeOf]],[[SetPrototypeOf]],[[IsExtensible]],
// [[PreventExtensions]],[[GetOwnProperty]],
// [[DefineOwnProperty]],[[HasProperty]],
// [[Get]],[[Set]],[[Delete]],[[OwnPropertyKeys]]);
// except for the standard, built-in exotic objects, we'd need
// to know whether these methods had distinct behaviors
// Note: There is no apparent way for us to detect a `Proxy` and
// reject (Chrome at least is not rejecting anyways)
const stringTag = ({}.toString.call(val).slice(8, -1));
if (
[
// Symbol's `toStringTag` is only "Symbol" for its initial
// value, so we check `typeof`
'symbol',
// All functions including bound function exotic objects
'function'
].includes(typeof val) ||
[
// A non-array exotic object
'Arguments',
// A non-array exotic object
'Module',
// `Error` and other errors have the [[ErrorData]] internal
// slot and give "Error"
'Error',
// Promise instances have an extra slot ([[PromiseState]])
// but not throwing in Chrome `postMessage`
'Promise',
// WeakMap instances have an extra slot ([[WeakMapData]])
// but not throwing in Chrome `postMessage`
'WeakMap',
// WeakSet instances have an extra slot ([[WeakSetData]])
// but not throwing in Chrome `postMessage`
'WeakSet',
// HTML-SPECIFIC
'Event',
// Also in Node `worker_threads` (currently experimental)
'MessageChannel'
].includes(stringTag) ||
/*
// isClosed is no longer documented
((stringTag === 'Blob' || stringTag === 'File') &&
val.isClosed) ||
*/
(val && typeof val === 'object' &&
// Duck-type DOM node objects (non-array exotic?
// objects which cannot be cloned by the SCA)
typeof val.nodeType === 'number' &&
typeof val.insertBefore === 'function')
) {
throw new DOMException(
'The object cannot be cloned.', 'DataCloneError'
);
}
return false;
}
}
});
const undef = [
sparseUndefined,
undef$1
];
const universal = [
expObj$1
// TODO: Add types that are de-facto universal even though not
// built-in into ecmasript standard.
];
export { y as JSON_TYPES, u as Typeson, e as TypesonPromise, p as Undefined, arrayNonindexKeys, arraybuffer, bigint, bigintObject, blob, expObj$1 as builtin, cloneable, cryptokey, dataview, date, error, errors, escapeKeyPathComponent, file, filelist, getByKeyPath, getJSONType, hasConstructorOf, imagebitmap, imagedata, infinity, intlTypes, isObject, isPlainObject, isThenable, isUserObject, map, nan, negativeInfinity, nonbuiltinIgnore, postmessage, primitiveObjects, regexp, resurrectable, set, setAtKeyPath, socketio, sparseUndefined, specialNumbers, expObj as structuredCloning, structuredCloningThrowing, toStringTag, typedArrays, typedArraysSocketIO as typedArraysSocketio, undef$1 as undef, undef as undefPreset, unescapeKeyPathComponent, universal, userObject };
//# sourceMappingURL=index.js.map

121

package.json
{
"name": "typeson-registry",
"version": "1.0.0-alpha.39",
"version": "2.0.0",
"description": "The type registry for typeson",

@@ -9,20 +9,14 @@ "author": "dfahlander",

],
"main": "./dist/all.js",
"type": "module",
"main": "./dist/index.umd.min.js",
"module": "./index.js",
"scripts": {
"prepublishOnly": "yarn",
"eslint": "eslint --ext js,md,html .",
"start": "http-server -p 8085",
"rollup": "node -r esm ./build.js",
"mocha": "mocha --delay --require esm test/test-node",
"open-coverage": "open-cli http://localhost:8085/coverage/ && npm start",
"coverage": "rm -Rf node_modules/.cache && nyc --all npm run mocha",
"test-nocov": "npm run rollup && npm run eslint && npm run coverage",
"test": "npm run rollup && npm run eslint && npm run coverage",
"test:worker-open": "open-cli http://localhost:8085/browser-test/worker.html && npm start",
"test:browser-open": "open-cli http://localhost:8085/browser-test/ && npm start",
"test:browser": "npm run rollup && npm run eslint && npm run test:browser-open",
"windows": "node -r esm windows-devinstall"
"exports": {
".": {
"import": "./dist/index.min.js",
"require": "./dist/index.umd.min.js",
"default": "./dist/index.umd.min.js"
},
"./*": "./*"
},
"nyc": {
"c8": {
"reporter": [

@@ -68,51 +62,66 @@ "text",

"engines": {
"node": ">=10.0.0"
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"devDependencies": {
"@babel/core": "^7.13.8",
"@babel/eslint-parser": "^7.13.8",
"@babel/preset-env": "^7.13.8",
"@brettz9/eslint-plugin": "^1.0.3",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-commonjs": "^17.1.0",
"@rollup/plugin-node-resolve": "^11.2.0",
"canvas": "^2.6.1",
"chai": "^4.3.0",
"eslint": "^7.20.0",
"eslint-config-ash-nazg": "^29.8.0",
"eslint-config-standard": "^16.0.2",
"@babel/core": "^7.17.5",
"@babel/eslint-parser": "^7.17.0",
"@babel/preset-env": "^7.16.11",
"@brettz9/eslint-plugin": "^1.0.4",
"@brettz9/node-static": "^0.1.1",
"@rollup/plugin-babel": "^5.3.1",
"@rollup/plugin-commonjs": "^21.0.2",
"@rollup/plugin-node-resolve": "^13.1.3",
"c8": "^7.11.0",
"canvas": "^2.9.0",
"chai": "^4.3.6",
"eslint": "^8.10.0",
"eslint-config-ash-nazg": "^32.5.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-array-func": "^3.1.7",
"eslint-plugin-chai-expect": "^2.2.0",
"eslint-plugin-chai-friendly": "^0.6.0",
"eslint-plugin-compat": "^3.9.0",
"eslint-plugin-chai-expect": "^3.0.0",
"eslint-plugin-chai-friendly": "^0.7.2",
"eslint-plugin-compat": "^4.0.2",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-html": "^6.1.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsdoc": "^32.2.0",
"eslint-plugin-markdown": "^2.0.0",
"eslint-plugin-no-unsanitized": "^3.1.4",
"eslint-plugin-html": "^6.2.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jsdoc": "^37.9.4",
"eslint-plugin-markdown": "^2.2.1",
"eslint-plugin-no-unsanitized": "^4.0.1",
"eslint-plugin-no-use-extend-native": "^0.5.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.3.1",
"eslint-plugin-radar": "^0.2.1",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-sonarjs": "^0.12.0",
"eslint-plugin-standard": "^4.1.0",
"eslint-plugin-unicorn": "^28.0.2",
"esm": "^3.2.25",
"http-server": "^0.12.3",
"jsdom": "^16.4.0",
"mocha": "^8.3.0",
"node-webcrypto-ossl": "^2.1.2",
"nyc": "^15.1.0",
"open-cli": "^6.0.1",
"rollup": "^2.40.0",
"eslint-plugin-unicorn": "^41.0.0",
"jsdom": "^19.0.0",
"mocha": "^9.2.1",
"node-webcrypto-ossl": "^2.1.3",
"open-cli": "^7.0.1",
"rollup": "^2.68.0",
"rollup-plugin-terser": "^7.0.2",
"socket.io": "^3.1.2",
"socket.io-client": "^3.1.2"
"socket.io": "^4.4.1",
"socket.io-client": "^4.4.1"
},
"dependencies": {
"base64-arraybuffer-es6": "^0.7.0",
"typeson": "^6.0.0",
"whatwg-url": "^8.4.0"
"base64-arraybuffer-es6": "^1.0.0",
"typeson": "^7.0.0",
"whatwg-url": "^11.0.0"
},
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/dist/presets/builtin'));\n\nTSON.stringify({foo: new Date()}, null, 2);"
}
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/dist/presets/builtin'));\n\nTSON.stringify({foo: new Date()}, null, 2);",
"scripts": {
"eslint": "eslint --ext js,md,html .",
"lint": "npm run eslint --",
"start": "static -p 8085",
"rollup": "node ./build.js",
"mocha": "mocha --delay --require chai/register-expect.js --require chai/register-assert.js test/test-node.js",
"open-coverage": "open-cli http://localhost:8085/coverage/ && npm start",
"coverage": "rm -Rf node_modules/.cache && c8 npm run mocha",
"test-nocov": "npm run rollup && npm run eslint && npm run coverage",
"test": "npm run rollup && npm run eslint && npm run coverage",
"test:worker-open": "open-cli http://localhost:8085/browser-test/worker.html && npm start",
"test:browser-open": "open-cli http://localhost:8085/browser-test/ && npm start",
"test:browser": "npm run rollup && npm run eslint && npm run test:browser-open",
"windows": "node windows-devinstall"
},
"readme": "# typeson-registry\n\nThe type registry for [typeson](https://github.com/dfahlander/typeson).\n\n- Types listed under\n [types](https://github.com/dfahlander/typeson-registry/tree/master/types)\n- Presets listed under\n [presets](https://github.com/dfahlander/typeson-registry/tree/master/presets)\n\nSee below for notes on these types and presets.\n\nNote that some types will require polyfills in Node such as via\n[`jsdom`](https://github.com/jsdom/jsdom).\nSee the testing environment of `test/test.js` for some examples.\n\n## Installation\n\nNote that for Node.js, to use the `file` or `blob` types (or the `filelist`\ntype or `structuredCloning` and `structuredCloningThrowing` presets which\ninclude them), you will need a polyfill for `Blob` or `File`, respectively,\nas well as `FileReader` and `URL.createObjectURL` (and a\npolyfill for `URL` if you are using Node < 10.0.0 or an older browser).\nNote that our `URL.createObjectURL` polyfill expects a global\n`XMLHttpRequest` and `location.href` predefined before it as well (and one\nwhich can handle `data:` URLs). For Node, you can add it like this:\n\n```js\nconst url = require('url'); // This line only needed to support Node < 10.0.0\nconst {createObjectURL} = require('typeson-registry/polyfills/createObjectURL.umd.js');\n\nconst URL = url.Url; // This line only needed to support Node < 10.0.0\nURL.createObjectURL = createObjectURL;\n```\n\nWe have not added `jsdom` as a dependency, but it is required if this\npolyfill is used.\n\nBesides the polyfills for `file` or `blob`, the `structuredCloningThrowing`\npreset also needs a global `DOMException` polyfill.\n\nThe `filelist` type, in addition to the polyfills for `file`, will need\na `FileList` polyfill (including a `FileList` string tag).\n\nThe `imagebitmap` type requires a global `createImageBitmap` polyfill (and\nan `ImageBitmap` polyfill (including an `ImageBitmap` string tag).\n\nThe `imagedata` type requires a global `ImageData` polyfill (including an\n`ImageData` string tag).\n\nYou may wish to see our `test-node.js` and `test-environment.js` files\nfor how some polyfilling may be done (largely using `jsdom`).\n\nThe `cloneable` and `resurrectable` types (and the `createObjectURL`\npolyill) each accept an optional global `performance` polyfill (through\nthe common file `utils/generateUUID.js`).\n\n### Building files from Git clone (as opposed to npm installs)\n\nIf you have cloned the repo (and not the npm package), you must run\n`npm install` to get the `devDependencies` and then run\n`npm run rollup` to get the individual browser scripts built locally\n(into `dist`) or to get `index.js` to be rebuilt based on existing\npresets and types).\n\n## Usage (Pre-rollup in Node or browser)\n\n```js\nimport {Typeson, date, error, regexp, typedArrays} from 'typeson-registry';\n\nconst TSON = new Typeson().register([\n date,\n error,\n regexp,\n typedArrays\n // ...\n]);\n\nconst tson = TSON.stringify({\n Hello: 'world',\n date: new Date(),\n error: new Error('test'),\n inner: {\n x: /foo/gui,\n bin: new Uint8Array(64)\n }\n}, null, 2);\n\nconsole.log(tson);\n/* Output:\n\n{\n \"Hello\": \"world\",\n \"date\": 1464049031538,\n \"error\": {\n \"name\": \"Error\",\n \"message\": \"test\"\n },\n \"inner\": {\n \"x\": {\n \"source\": \"foo\",\n \"flags\": \"gi\"\n },\n \"bin\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\"\n },\n \"$types\": {\n \"date\": \"Date\",\n \"error\": \"Error\",\n \"inner.x\": \"RegExp\",\n \"inner.bin\": \"Uint8Array\"\n }\n}\n*/\n\nconst parsedBack = TSON.parse(tson);\n\nconsole.log(parsedBack.date instanceof Date);\nconsole.log(parsedBack.inner.bin instanceof Uint8Array);\n```\n\n## Usage (Node without own Rollup)\n\n```js\nconst {Typeson, builtin} = require('typeson-registry');\n\nconst tson = new Typeson().register([\n builtin\n]);\n```\n\n## Usage (`import` in supporting browsers without own Rollup)\n\n```html\n<script type=\"module\">\n\nimport {Typeson, builtin} from './node_modules/typeson-registry/dist/index.js';\n\nconst TSON = new Typeson().register([\n builtin\n]);\n</script>\n```\n\n## Usage (with plain script tags without own Rollup)\n\nAll types and presets under `dist/` are UMD modules so you could also\nrequire them as AMD modules with requirejs if you prefer.\n\n```html\n<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://unpkg.com/typeson/dist/typeson.umd.min.js\"></script>\n <script src=\"https://unpkg.com/typeson-registry/dist/presets/builtin.umd.js\"></script>\n <script>\n\n const TSON = new Typeson().register(builtin);\n const tson = TSON.stringify({\n Hello: 'world',\n date: new Date(),\n error: new Error('err'),\n inner: {\n x: /foo/giu,\n bin: new Uint8Array(64)\n }\n }, null, 2);\n\n alert(tson);\n /* Alerts:\n\n {\n \"Hello\": \"world\",\n \"date\": 1464049031538,\n \"error\": {\n \"name\": \"Error\",\n \"message\": \"err\"\n },\n \"inner\": {\n \"x\": {\n \"source\": \"foo\",\n \"flags\": \"gi\"\n },\n \"bin\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\"\n },\n \"$types\": {\n \"date\": \"Date\",\n \"error\": \"Error\",\n \"inner.x\": \"RegExp\",\n \"inner.bin\": \"Uint8Array\"\n }\n }\n */\n\n </script>\n </head>\n</html>\n```\n\n## Notes on types and presets\n\nNote that the type name corresponds to the file name in the following manner:\n\n1. Genuine separate words are camel-cased in the type name but hyphenated in\n the file name (e.g., `negativeInfinity` and `negativity-infinity.js`);\n names whose original API is camel-cased are not hyphenated, however\n (e.g., `arraybuffer` and `arraybuffer.js` given `ArrayBuffer`).\n1. All other portions of names are lower-cased (e.g., `date` and `date.js`).\n1. Type names that would clash with existing objects when exported (even after\n lower-casing) must have a separate, preferably abbreviated form (e.g.,\n the type and preset `undef` and `undef.js` was necessary for `undefined`)\n1. Type names which are not allowed as ES6 exports (e.g., periods in `Intl`\n types are now removed: `Intl.Collator` -> `IntlCollator`)\n1. Type names should indicate the singular (e.g., `userObject`) except for\n files containing multiple related exports (e.g., `errors`, `typed-arrays`,\n and `typed-arrays-socketio.js`); files with multiple exports whose extra\n exports are incidental (e.g., `filelist`) do not need a plural.\n\n### Types\n\n- `arraybuffer`\n- `bigintObject`\n- `bigint`\n- `blob` - Has sync and async encapsulation/replacements (though sync only\n via deprecated means)\n- `cloneable` - Looks for `Symbol.for('cloneEncapsulate')` and\n `Symbol.for('cloneRevive')` methods to allow\n for a means of extending our built-in structured cloning presets (though if\n you are polyfilling a standard object, we welcome you to submit back as a\n PR!). The clones cannot be revived past the current window session,\n however.\n- `dataview`\n- `date`\n- `error.js` (`Error`) and `errors.js` (`TypeError`, `RangeError`, `SyntaxError`, `ReferenceError`, `EvalError`, `URIError`, `InternalError`) - These\n provide a means of resurrecting error object across cloning boundaries\n (since they are not otherwise treated as cloneable by the Structured\n Cloning Algorithm).\n- `file` - Has sync and async encapsulation/replacements (though sync only\n via deprecated means)\n- `filelist` - HTML does not provide a means of creating a `FileList` object\n dynamically, so we polyfill one for revival. This method also sets `File`\n- `imagebitmap` - Has sync and async revivers. The sync method does not produce\n a genuine `ImageBitmap` but instead produces a canvas element which can\n frequently be used in a similar context to `ImageBitmap`.\n- `imagedata`\n- `infinity` - Preserves positive infinity\n- `intl-types.js` (`Intl.Collator`, `Intl.DateTimeFormat`, `Intl.NumberFormat`) -\n Not all properties can be preserved\n- `map`\n- `nan` - Preserves `NaN` (not a number)\n- `NegativeInfinity` - Preserves negative infinity\n- `nonBuiltInIgnore` - For roughly detecting non-builtin objects and to avoid\n adding them as properties\n- `primitive-objects.js` (`StringObject`, `BooleanObject`, `NumberObject`)\n- `regexp`\n- `resurrectable` - Resurrects any non-array object, function, or symbol; can\n only be revived for the current window session.\n- `set`\n- `typed-arrays-socketio.js` (`Int8Array`, `Uint8Array`, `Uint8ClampedArray`,\n `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `Float32Array`,\n `Float64Array`) - See\n [typeson#environmentformat-support](https://github.com/dfahlander/typeson#environmentformat-support)\n and `presets/socketio.js`\n- `typed-arrays.js` (`Int8Array`, `Uint8Array`, `Uint8ClampedArray`,\n `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`,\n `Float32Array`, `Float64Array`) - Base64-encodes\n- `undef` (for `undefined`) (See also `presets/undefined.js` and\n `presets/sparse-undefined.js`)\n- `userObjects` - Allows for inherited objects but ensures the prototype chain\n inherits from `Object` (or `null`). Should be low priority if one is\n matching other objects as it will readily match many objects.\n\n### Presets\n\n- `array-nonindex-keys.js`\n- `builtin.js` - Types that are built into the JavaScript language itself.\n Types that were added in ES6 or beyond will be checked before inclusion\n so that this module can be consumed by both ES5 and ES6 environments.\n Some imperfectly serializable objects (such as functions and Symbols)\n are not included in this preset.\n- `postmessage.js` - This preset is intended as a utility to expand on what is\n cloneable via `strcutured-cloning.js` and supports Error objects.\n- `socketio.js`\n- `sparse-undefined.js` (`sparseArrays` and `sparseUndefined`) - Supports\n reconstructing sparse arrays (with missing properties not even assigned\n an explicit `undefined`). See `types/undefined.js` for the explicit case\n or `presets/undefined.js` for a utility combining both.\n- `special-numbers.js` (preserves `NaN`, `Infinity`, `-Infinity`)\n- `structured-cloning.js` - For the Structured Cloning Algorithm used by the\n likes of `postMessage` and `indexedDB`. See also the `cloneable` type.\n- `structured-cloning-throwing.js` - Same as `structured-cloning.js` but\n throws with non-recognized types. See also the `cloneable` type.\n- `undef.js` - Supports reconstructing explicit and implicit (sparse)\n uses of `undefined`.\n- `universal.js`- Meant for de-facto universal types. Currently includes\n built-ins only.\n\n### Functions (support not included)\n\nIf you are looking for a way to resurrect functions, you can use the following,\nbut please bear in mind that it uses `eval` which is prohibited by some\nContent Security Policies (CSP) (so we are not packaging it with our builds),\nthat it is unsafe, and also that the function might not behave\ndeterministically when revived (e.g., if the function were provided from\nanother context).\n\n```js\nconst functionType = {functionType: [\n function (x) { return typeof x === 'function'; },\n function (funcType) { return '(' + funcType.toString() + ')'; },\n // eslint-disable-next-line no-eval\n function (o) { return eval(o); }\n]};\n\nconst typeson = new Typeson().register(functionType);\nconst tson = typeson.stringify(function () { return 'abc'; });\nconst back = typeson.parse(tson);\nback(); // 'abc'\n```\n\n## Development\n\n[node-canvas](https://github.com/Automattic/node-canvas) is used to test\n`ImageData`.\n\nBe sure to follow the installation steps.\n\nOn Windows, besides following the\n[Windows installation steps](https://github.com/Automattic/node-canvas/wiki/Installation---Windows),\n[this](https://github.com/nodejs/node-gyp/issues/94#issuecomment-278587021)\nhelped complete the installation. If you need to have it rebuilt, you can\nrun `npm i` inside of the `node_modules/canvas` directory.\n\n[These steps](https://github.com/Automattic/node-canvas/issues/191#issuecomment-7681555)\nwere also necessary but you can run `npm run windows` after install to get\nthese steps applied. These are the only steps which should need to be re-run\nif you have deleted your local `node-canvas` copy.\n\n## See also\n\n- [typeson](https://github.com/dfahlander/typeson)\n"
}

@@ -11,14 +11,9 @@ /* globals location, XMLHttpRequest, DOMException */

// // eslint-disable-next-line node/no-unpublished-import
// import utils from 'jsdom/lib/jsdom/living/generated/utils.js';
import generateUUID from '../utils/generateUUID.js';
/* globals require */
// These are not working well with Rollup as imports
// We also need to tweak `XMLHttpRequest` which our types
// rely on to obtain the Blob/File content
/* eslint-disable node/no-unpublished-require, import/no-commonjs */
const whatwgURL = require('whatwg-url');
const utils = require('jsdom/lib/jsdom/living/generated/utils');
/* eslint-enable node/no-unpublished-require, import/no-commonjs */
import whatwgURL from 'whatwg-url';
// eslint-disable-next-line node/no-unpublished-import
import * as utils from 'jsdom/lib/jsdom/living/generated/utils.js';
import generateUUID from '../utils/generateUUID.js';

@@ -48,3 +43,3 @@ const {serializeURLOrigin, parseURL} = whatwgURL;

const impl = utils.implSymbol;
const {implForWrapper} = utils.default;

@@ -76,3 +71,4 @@ // We only handle the case of binary, so no need to override `open`

// utf16le and base64 both convert lone surrogates
const encoded = blob[impl]._buffer.toString('binary');
// eslint-disable-next-line max-len -- Long
const encoded = implForWrapper(blob)._buffer.toString('binary');
// Not usable in jsdom which makes properties readonly,

@@ -79,0 +75,0 @@ // but local-xmlhttprequest can use (and jsdom can

@@ -29,3 +29,3 @@ # typeson-registry

const url = require('url'); // This line only needed to support Node < 10.0.0
const {createObjectURL} = require('typeson-registry/polyfills/createObjectURL-cjs');
const {createObjectURL} = require('typeson-registry/polyfills/createObjectURL.umd.js');

@@ -69,7 +69,3 @@ const URL = url.Url; // This line only needed to support Node < 10.0.0

```js
import Typeson from 'typeson';
import date from 'typeson-registry/types/date';
import error from 'typeson-registry/types/error';
import regexp from 'typeson-registry/types/regexp';
import typedArrays from 'typeson-registry/types/typed-arrays';
import {Typeson, date, error, regexp, typedArrays} from 'typeson-registry';

@@ -129,5 +125,4 @@ const TSON = new Typeson().register([

```js
const Typeson = require('typeson-registry/dist/all.js');
const {Typeson, builtin} = require('typeson-registry');
const {presets: {builtin}} = Typeson;
const tson = new Typeson().register([

@@ -143,5 +138,4 @@ builtin

import Typeson from './node_modules/typeson-registry/dist/index.js';
import {Typeson, builtin} from './node_modules/typeson-registry/dist/index.js';
const {presets: {builtin}} = Typeson;
const TSON = new Typeson().register([

@@ -162,7 +156,7 @@ builtin

<head>
<script src="https://unpkg.com/typeson/dist/typeson.js"></script>
<script src="https://unpkg.com/typeson-registry/dist/presets/builtin.js"></script>
<script src="https://unpkg.com/typeson/dist/typeson.umd.min.js"></script>
<script src="https://unpkg.com/typeson-registry/dist/presets/builtin.umd.js"></script>
<script>
const TSON = new Typeson().register(Typeson.presets.builtin);
const TSON = new Typeson().register(builtin);
const tson = TSON.stringify({

@@ -169,0 +163,0 @@ Hello: 'world',

@@ -13,6 +13,6 @@ /* globals performance */

export default function generateUUID () { // Adapted from original: public domain/MIT: http://stackoverflow.com/a/8809472/271577
/* istanbul ignore next */
/* c8 ignore next */
let d = Date.now() +
// use high-precision timer if available
// istanbul ignore next
/* c8 ignore next 4 */
(typeof performance !== 'undefined' &&

@@ -19,0 +19,0 @@ typeof performance.now === 'function'

@@ -8,3 +8,3 @@ /**

return new Uint8Array(buf).reduce(
(s, byte) => s + String.fromCharCode(byte), ''
(s, byte) => s + String.fromCodePoint(byte), ''
);

@@ -67,2 +67,4 @@ }

for (let i = 0; i < str.length; i++) {
// eslint-disable-next-line max-len -- Long
// eslint-disable-next-line unicorn/prefer-code-point -- Iterating char. codes
array[i] = str.charCodeAt(i); // & 0xff;

@@ -69,0 +71,0 @@ }

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc