@planjs/mobx-persist
Version:
enhance-mobx-persist
17 lines (14 loc) • 15.4 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("mobx")):"function"==typeof define&&define.amd?define(["exports","mobx"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).mobxPersist={},e.mobx)}(this,(function(e,t){"use strict";var r={j:function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}};function n(e,t){if(!e){var n=Array.prototype.slice.call(arguments,2),o=[],i=0,a=t.replace(/%([a-zA-Z%])/g,(function(e,t){if("%%"===e)return e;var a=r[t];if("function"==typeof a){var s=n[i++];return o.push(s),a(s)}return e}));throw console&&o.length>0&&console.log.apply(console,o),Error("[serializr] "+(a||"Illegal State"))}}function o(e){if(e)throw Error(e)}function i(e,t,r){if(0!==e.length){var n=e.filter((function(){return!0})).length,o=[],i=!1,a=function(e,t,a){t?i||(i=!0,r(t)):(o[e]=a,0==--n&&r(null,o))};e.forEach((function(e,r){t(e,a.bind(null,r),r)}))}else r(null,[])}function a(e){return null===e||"object"!=typeof e&&"function"!=typeof e}function s(e){return e&&e.factory&&e.props}function c(e){return e&&e.serializer&&e.deserializer}function u(e){return"object"==typeof e&&!!e.jsonname}function f(e,t){for(;e;){if(e===t)return!0;e=e.extends}return!1}function l(e){return e&&"function"==typeof e.keys&&"function"==typeof e.clear}function p(e,t){if(t){n(c(e),"expected a propSchema");["beforeDeserialize","afterDeserialize"].forEach((function(r){"function"==typeof t[r]&&(e[r]=t[r])}))}return e}function h(e){return e?s(e)?e:s(e.serializeInfo)?e.serializeInfo:e.constructor&&e.constructor.serializeInfo?e.constructor.serializeInfo:void 0:null}function d(e,t){return n(s(t)),e.serializeInfo=t}function y(e,t,r){n(e!==Object,"one cannot simply put define a model schema for Object"),n("function"==typeof e,"expected constructor function");var o={targetClass:e,factory:r||function(){return new e},props:t};if(e.prototype.constructor!==Object){var i=h(e.prototype.constructor);i&&i.targetClass!==e&&(o.extends=i)}return d(e,o),o}function m(e){var t={serializer:function(e){return n(a(e),"this value is not primitive: "+e),e},deserializer:function(e,t){a(e)?t(null,e):t("[serializr] this value is not primitive: "+e)}};return t=p(t,e)}var v="undefined"!=typeof Symbol?Symbol("SKIP"):{SKIP:!0},b=m(),g=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,j=/([^\s,]+)/g;function z(e){var t=(""+e).replace(g,""),r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(j);return null===r&&(r=[]),r}function w(e,t,r,o){var i;if(n(arguments.length>=2,"too few arguments. Please use @serializable as property decorator"),void 0===r&&"function"==typeof t&&t.prototype&&void 0!==o&&"number"==typeof o){n(c(e),"Constructor params must use alias(name)"),n(e.jsonname,"Constructor params must use alias(name)");var a=z(t);o>a.length||(r=a[o],e.paramNumber=o,o=void 0,t=t.prototype,i=function(e){for(var r=[],n=0;t.constructor.length>n;n++)Object.keys(e.modelSchema.props).forEach((function(t){var o=e.modelSchema.props[t];o.paramNumber===n&&(r[n]=e.json[o.jsonname])}));return new(Function.prototype.bind.apply(t.constructor,[null].concat(r)))})}n("string"==typeof r,"incorrect usage of @serializable decorator");var s=h(t);return s&&t.constructor.hasOwnProperty("serializeInfo")||(s=y(t.constructor,{},i)),s&&s.targetClass!==t.constructor&&(s=y(t.constructor,{},i)),s.props[r]=e,!o||o.get||o.set||(o.writable=!0),o}function x(e,t,r){if(1===arguments.length){var o=!0===e?b:e;return n(c(o),"@serializable expects prop schema"),w.bind(null,o)}return w(m(),e,t,r)}function S(e,t){n(1===arguments.length||2===arguments.length,"serialize expects one or 2 arguments");var r=1===arguments.length?e:t,o=1===arguments.length?null:e;if(Array.isArray(r)){if(0===r.length)return[];o?"object"!=typeof o&&(o=h(o)):o=h(r[0])}else o?"object"!=typeof o&&(o=h(o)):o=h(r);return n(!!o,"Failed to find default schema for "+e),Array.isArray(r)?r.map((function(e){return C(o,e)})):C(o,r)}function R(e){n(!0===e||e.pattern,"prop schema '*' can only be used with 'true' or a prop def with a 'pattern': "+JSON.stringify(e))}function C(e,t){var r;return n(e&&"object"==typeof e&&e.props,"Expected schema"),n(t&&"object"==typeof t,"Expected object"),r=e.extends?C(e.extends,t):{},Object.keys(e.props).forEach((function(n){var o=e.props[n];if("*"!==n){if(!0===o&&(o=b),!1!==o){var i=o.serializer(t[n],n,t);i!==v&&(r[o.jsonname||n]=i)}}else!function(e,t,r,n){for(var o in R(t),r)if(r.hasOwnProperty(o)&&!(o in e.props)&&(!0===t||t.pattern&&t.pattern.test(o))){var i=r[o];if(!0===t)a(i)&&(n[o]=i);else if(t.props){if((s=S(t,i))===v)return;n[o]=s}else{var s;if((s=t.serializer(i,o,r))===v)return;n[o]=s}}}(e,o,t,r)})),r}var O=new WeakMap;function I(e,t,r,n,i){this.parentContext=e,this.isRoot=!e,this.pendingCallbacks=0,this.pendingRefsCount=0,this.onReadyCb=n||o,this.json=r,this.target=null,this.hasError=!1,this.modelSchema=t,this.isRoot?(this.rootContext=this,this.args=i,this.pendingRefs={},this.resolvedRefs={}):(this.rootContext=e.rootContext,this.args=e.args)}function k(e,t){for(var r in e.props)if("object"==typeof e.props[r]&&e.props[r].jsonname===t)return!0;return!1}function E(e,t,r,i,a){if(null!=r&&"object"==typeof r){var s=new I(e,t,r,i,a),c=t.factory(s);n(!!c,"No object returned from factory"),s.setTarget(c);var u=s.createCallback(o);return A(s,t,r,c),u(),c}i(null,null)}function A(e,t,r,i){t.extends&&A(e,t.extends,r,i),Object.keys(t.props).forEach((function(s){var c=t.props[s];if("*"!==s){if(!0===c&&(c=b),!1!==c){var u=c.jsonname||s;P((function(t,n){t||void 0===n||function(t,n,o){t.deserializer(n,function a(s){return function(c,u){N((function(r,n){r&&void 0!==n&&"function"==typeof t.afterDeserialize?t.deserializer(n,a(s),e,i[o]):s(r,n)}),c,u,n,r,o,e,t)}}(e.rootContext.createCallback((function(e){e!==v&&(i[o]=e)}))),e,i[o])}(c,n,s)}),r[u],r,u,e,c)}}else!function(e,t,r,i,s){for(var c in R(r),s)if(!(c in t.props)&&!k(t,c)){var u=s[c];if(!0===r)n(a(u),"encountered non primitive value while deserializing '*' properties in property '"+c+"': "+u),i[c]=u;else if(r.pattern.test(c))if(r.factory){var f=E(e,r,u,e.callback||o,{});void 0!==f&&(i[c]=f)}else{function t(e){e!==v&&(i[c]=e)}r.deserializer(u,e.rootContext.createCallback(t),e)}}}(e,t,c,i,r)}))}function P(e,t,r,n,o,i){i&&"function"==typeof i.beforeDeserialize?i.beforeDeserialize(e,t,r,n,o,i):e(null,t)}function N(e,t,r,n,o,i,a,s){s&&"function"==typeof s.afterDeserialize?s.afterDeserialize(e,t,r,n,o,i,a,s):e(t,r)}function D(e,t){n(c(e=e||b),"expected prop schema as first argument"),n(!u(e),"provided prop is aliased, please put aliases first");var r={serializer:function(t){return void 0===t?v:(n(t&&"length"in t&&"map"in t,"expected array (like) object"),t.map(e.serializer))},deserializer:function(t,r,n){Array.isArray(t)?i(t,(function(r,o,i){function a(t,a){"function"==typeof e.afterDeserialize?N(s,t,a,r,i,n,e):o(t,a)}function s(t,r){t&&void 0!==r&&"function"==typeof e.afterDeserialize?e.deserializer(r,a,n):o(t,r)}P((function(t,r){t?o(t):e.deserializer(r,a,n)}),r,t,i,n,e)}),r):r("[serializr] expected JSON array")}};return r=p(r,t)}function _(e){return(_="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 T(e){return"object"===_(e)&&e&&Object.keys(e).map((function(t){return T(e[t])})),e}function J(){return function(e,t,r){n("function"==typeof e,"first argument should be function"),n("function"==typeof t,"second argument should be a function or promise");var o={serializer:e,deserializer:function(e,n,o,i){4===t.length?t(e,o,i,n,r):n(null,t(e,o,i,null,r))}};return p(o,r)}(T,(function(e){return e}))}I.prototype.createCallback=function(e){return this.pendingCallbacks++,function(e){var t=!1;return function(){if(!t)return t=!0,e.apply(null,arguments);n(!1,"callback was invoked twice")}}(function(t,r){t?this.hasError||(this.hasError=!0,this.onReadyCb(t),O.delete(this)):this.hasError||(e(r),--this.pendingCallbacks===this.pendingRefsCount&&(this.pendingRefsCount>0?(this.onReadyCb(Error('Unresolvable references in json: "'+Object.keys(this.pendingRefs).filter((function(e){return this.pendingRefs[e].length>0}),this).join('", "')+'"')),O.delete(this)):(this.onReadyCb(null,this.target),O.delete(this))))}.bind(this))},I.prototype.await=function(e,t,r){if(n(this.isRoot),t in this.resolvedRefs){var o=this.resolvedRefs[t].filter((function(t){return f(t.modelSchema,e)}))[0];if(o)return void r(null,o.value)}this.pendingRefsCount++,this.pendingRefs[t]||(this.pendingRefs[t]=[]),this.pendingRefs[t].push({modelSchema:e,uuid:t,callback:r})},I.prototype.resolve=function(e,t,r){if(n(this.isRoot),this.resolvedRefs[t]||(this.resolvedRefs[t]=[]),this.resolvedRefs[t].push({modelSchema:e,value:r}),t in this.pendingRefs)for(var o=this.pendingRefs[t].length-1;o>=0;o--){var i=this.pendingRefs[t][o];f(e,i.modelSchema)&&(this.pendingRefs[t].splice(o,1),this.pendingRefsCount--,i.callback(null,r))}},I.prototype.setTarget=function(e){this.isRoot&&this.target&&O.delete(this.target),this.target=e,O.set(this.target,this)},I.prototype.cancelAwaits=function(){n(this.isRoot);var e=this;Object.keys(this.pendingRefs).forEach((function(t){e.pendingRefs[t].forEach((function(r){e.pendingRefsCount--,r.callback(Error("Reference resolution canceled for "+t))}))})),this.pendingRefs={},this.pendingRefsCount=0};var M={object:function(e){return e?function(e,t){n("object"==typeof e||"function"==typeof e,"No modelschema provided. If you are importing it from another file be aware of circular dependencies.");var r={serializer:function(t){return n(s(e=h(e)),"expected modelSchema, got "+e),null==t?t:S(e,t)},deserializer:function(r,o,i){n(s(e=h(e)),"expected modelSchema, got "+e),null!=r?E(i,e,r,o,t):o(null,r)}};return p(r,t)}(e):J()},list:function(e){return D(this.object(e))},map:function(e){return function(e,t){n(c(e=e||b),"expected prop schema as first argument"),n(!u(e),"provided prop is aliased, please put aliases first");var r={serializer:function(t){n(t&&"object"==typeof t,"expected object or Map");var r=l(t),o={};if(r)t.forEach((function(t,r){o[r]=e.serializer(t)}));else for(var i in t)o[i]=e.serializer(t[i]);return o},deserializer:function(r,n,o,i){if(r&&"object"==typeof r){var a=Object.keys(r);D(e,t).deserializer(a.map((function(e){return r[e]})),(function(e,t){if(e)n(e);else{var r,o=l(i);o?(i.clear(),r=i):r={};for(var s=0,c=a.length;c>s;s++)o?r.set(a[s],t[s]):r[a[s]]=t[s];n(null,r)}}),o)}else n("[serializr] expected JSON object")}};return p(r,t)}(this.object(e))}};function L(e,t){return d(e,F(t)),e}function F(e){var t={};return Object.keys(e).forEach((function(r){"object"===_(e[r])?e[r].type in M&&(t[r]="object"===_(e[r].schema)?M[e[r].type](F(e[r].schema)):M[e[r].type](e[r].schema)):!0===e[r]&&(t[r]=!0)})),{factory:function(){return{}},props:t}}var K=function(){function e(){}return e.prototype.getItem=function(e){throw Error("IStorage has to implement `getItem` method")},e.prototype.removeItem=function(e){throw Error("IStorage has to implement `removeItem` method")},e.prototype.setItem=function(e,t){throw Error("IStorage has to implement `setItem` method")},e.prototype.clear=function(){throw Error("IStorage has to implement `clear` method")},e.prototype.onChange=function(e,t,r){},e}();function U(e,r,n){var o=e,i=r;if("object"===_(o)&&"object"===_(i))for(var a in o)o[a]&&"object"===_(o[a])&&"object"===_(i[a])?t.isObservableMap(o[a])?o[a].merge(i[a]):t.isObservableArray(o[a])?o[a].replace(i[a]):t.isObservableObject(o[a])&&(o[a]=U(o[a],i[a])):void 0!==i[a]&&(o[a]=i[a]);return o}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var V=function(e,t){return(V=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)};var q=function(e){function t(){var t=e.call(this)||this;try{window.addEventListener("storage",(function(e){var r;null===(r=t.onChange)||void 0===r||r.call(t,e.key,e.newValue,e.oldValue)}))}catch(e){console.error("[mobx-persist] LocalStorage error",e)}return t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+t+" is not a constructor or null");function r(){this.constructor=e}V(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t.prototype.getItem=function(e){return new Promise((function(t,r){try{t(window.localStorage.getItem(e))}catch(e){r(e)}}))},t.prototype.removeItem=function(e){return new Promise((function(t,r){try{window.localStorage.removeItem(e),t(null)}catch(e){r(e)}}))},t.prototype.setItem=function(e,t){return new Promise((function(r,n){try{window.localStorage.setItem(e,t),r(null)}catch(e){n(e)}}))},t.prototype.clear=function(){return new Promise((function(e,t){try{window.localStorage.clear(),e(null)}catch(e){t(e)}}))},t.prototype.onChange=function(e,t,r){},t}(K);e.IStorage=K,e.create=function(e){void 0===e&&(e={});var r=e.storage,i=void 0===r?new q:r,a=e.jsonify,c=void 0===a||a,u=e.debounce,f=void 0===u?0:u,l=e.sync,p=void 0===l||l;if(!(i instanceof K))throw Error("storage has to implement `IStorage` all method");return function(e,r,a,u){void 0===a&&(a={}),void 0===u&&(u={});var l=h(r);if(!l){var d=function(){console.error("[mobx-persist] No cacheable value")},y=Promise.resolve(r);return y.rehydrate=function(){return d(),y},y.clear=d,y.dispose=d,d(),y}var m=function d(){var y,m=i.getItem(e).then((function(e){return c?JSON.parse(e):e})).then(t.action("[mobx-persist "+e+"] LOAD_DATA",(function(e){return e&&"object"===_(e)&&function(e,t,r,i,a){2===arguments.length||"function"==typeof arguments[2]?(e=h(t=arguments[0]),r=arguments[1],i=arguments[2],a=arguments[3]):e=h(e),n(s(e),"update failed to determine schema"),n("object"==typeof t&&t&&!Array.isArray(t),"update needs an object");var c=new I(null,e,r,i,a);c.setTarget(t);var u=c.createCallback(o),f=A(c,e,r,t);u()}(l,r,e,(function(e){e&&console.error("[mobx-persist] Mobx update error",e)}),u),U(r,a),r})));return m.rehydrate=d,p&&(i.onChange=function(t){t===e&&(console.warn("[mobx-persist] change key "+t),y&&clearTimeout(y),y=setTimeout((function(){m.rehydrate(),y=null}),f||0))}),m}();return m.clear=function(){i.removeItem(e)},m.dispose=t.reaction((function(){return S(l,r)}),(function(t){return i.setItem(e,c?JSON.stringify(t):t)}),{delay:f}),m}},e.persist=function(){for(var e=[],t=0;arguments.length>t;t++)e[t]=arguments[t];var r=e[0],n=e[1];return r in M?x(M[r](n)):1===e.length?function(e){return L(e,r)}:x.apply(null,e)},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=index.umd.min.js.map