@persevie/statemanjs
Version:
Proper state manager for JavaScript
3 lines (2 loc) • 13.5 kB
JavaScript
var t=Object.defineProperty,e=(e,s,r)=>(((e,s,r)=>{s in e?t(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r})(e,"symbol"!=typeof s?s+"":s,r),r);class s{constructor(t){e(this,"transactionService"),this.transactionService=t}}function r(t,e){return`${t}: ${i(e)}`}function i(t){return t.message}var n,o,a,h,c,u,l,p,d,b,f,w,y,g,m,v,S,C,A,k,O,E,T,W,P,B,M,j,N,_,D,J,I,U,L,G,x,$,z,Y,q,F,H,K,Q,R=Object.defineProperty,V=(t,e,s)=>(((t,e,s)=>{e in t?R(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s})(t,"symbol"!=typeof e?e+"":e,s),s),X=(t,e,s)=>{if(!e.has(t))throw TypeError("Cannot "+s)},Z=(t,e,s)=>(X(t,e,"read from private field"),s?s.call(t):e.get(t)),tt=(t,e,s)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,s)},et=(t,e,s,r)=>(X(t,e,"write to private field"),r?r.call(t,s):e.set(t,s),s),st=(t,e,s)=>(X(t,e,"access private method"),s);class rt{constructor(t,e){tt(this,w),tt(this,g),tt(this,v),tt(this,C),tt(this,k),tt(this,E),tt(this,W),tt(this,B),tt(this,j),tt(this,_),tt(this,J),tt(this,U),tt(this,G),tt(this,$),tt(this,Y),tt(this,F),tt(this,K),tt(this,n,void 0),tt(this,o,{}),tt(this,a,!1),tt(this,h,"none"),tt(this,c,!1),tt(this,u,!1),tt(this,l,!1),tt(this,p,new Set),tt(this,d,!1),tt(this,b,void 0),tt(this,f,new Set(["clear","delete","set","add","fill","reverse","sort","unscopables","pop","push","shift","unshift","splice"])),V(this,"customComparator"),V(this,"defaultComparator"),this.get=this.get.bind(this),this.set=this.set.bind(this),this.update=this.update.bind(this),this.subscribe=this.subscribe.bind(this),this.unsubscribeById=this.unsubscribeById.bind(this),this.unsubscribeByIds=this.unsubscribeByIds.bind(this),this.getActiveSubscribersCount=this.getActiveSubscribersCount.bind(this),this.unsubscribeAll=this.unsubscribeAll.bind(this),this.unwrap=this.unwrap.bind(this),this.getPathToChangedProperty=this.getPathToChangedProperty.bind(this),this.customComparator=e.customComparator,this.defaultComparator=e.defaultComparator||"ref",et(this,b,new Map),et(this,n,new Proxy({__STATEMANJS_STATE__:t},st(this,J,I).call(this,[])))}get(){return Z(this,n).__STATEMANJS_STATE__}set(t,e){try{return!!st(this,K,Q).call(this,(()=>{et(this,d,e.skipComparison||!1),Z(this,n).__STATEMANJS_STATE__=t}),"set")&&(e.afterUpdate(),et(this,l,!1),st(this,$,z).call(this),st(this,v,S).call(this),et(this,h,"none"),!0)}catch(t){throw new Error(r("An error occurred while setting the new state",t))}}update(t,e){try{return!!st(this,K,Q).call(this,(()=>{et(this,d,e.skipComparison||!1),t(this.get())}),"update")&&(e.afterUpdate(),et(this,l,!1),st(this,$,z).call(this),st(this,v,S).call(this),et(this,h,"none"),!0)}catch(t){throw new Error(r("An error occurred while updating the state",t))}}subscribe(t,e={}){var s;const i=st(this,G,x).call(this),n=e.notifyCondition,o=e.properties&&e.properties.length>0;return o&&et(this,a,!0),st(this,U,L).call(this,{subId:i,subCb:()=>t(this.get()),notifyCondition:()=>{if(o){if(!st(this,Y,q).call(this,this.unwrap()))throw new Error("You can't add properties to track if your state is not an object");try{return st(this,F,H).call(this,e.properties,this.getPathToChangedProperty())}catch(t){throw new Error(r("An error occurred when accessing a property from the subscriptionOptions list",t))}}return void 0===n||n(this.get())},isProtected:null!=(s=e.protect)&&s}),()=>{o||et(this,a,!1),this.unsubscribeById(i)}}unsubscribeById(t){delete Z(this,o)[t]}unsubscribeByIds(t){t.forEach((t=>{this.unsubscribeById(t)}))}getActiveSubscribersCount(){return Object.getOwnPropertySymbols(Z(this,o)).length}unsubscribeAll(){et(this,a,!1);const t={};for(const e of Object.getOwnPropertySymbols(Z(this,o))){const s=Z(this,o)[e];s.isProtected&&(t[e]=s)}et(this,o,t)}unwrap(){et(this,u,!0);const t=this.get();return et(this,u,!1),t}getPathToChangedProperty(){return Array.from(Z(this,p).values())}}n=new WeakMap,o=new WeakMap,a=new WeakMap,h=new WeakMap,c=new WeakMap,u=new WeakMap,l=new WeakMap,p=new WeakMap,d=new WeakMap,b=new WeakMap,f=new WeakMap,w=new WeakSet,y=function(t){return null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"bigint"==typeof t},g=new WeakSet,m=function(t){Z(this,p).add(t)},v=new WeakSet,S=function(){et(this,p,new Set)},C=new WeakSet,A=function(t,e){return t&&"function"==typeof t[e]?t[e].bind(t):t[e]},k=new WeakSet,O=function(t){let e="";for(let s=0;s<t.length;s++){const r=t[s];e+="symbol"==typeof r?r.toString():r,s<t.length-1&&(e+=".")}return e},E=new WeakSet,T=function(t,e,s){const r=t[e],i="function"==typeof r,n=st(this,Y,q).call(this,r)&&null!==r;if(i){if(Z(this,f).has(e)&&!Z(this,c))throw new Error("Access is denied. Use 'update' method to do this.");const r=s.concat(e);return Z(this,f).has(e)&&(et(this,l,!0),st(this,W,P).call(this,s)),new Proxy(st(this,C,A).call(this,t,e),st(this,J,I).call(this,r))}if(n&&!Z(this,u)){const r=s.concat(e),i=st(this,k,O).call(this,r);if(!Z(this,b).has(i)){const s=new Proxy(st(this,C,A).call(this,t,e),st(this,J,I).call(this,r));Z(this,b).set(i,s)}return Z(this,b).get(i)}return st(this,C,A).call(this,t,e)},W=new WeakSet,P=function(t){const e=st(this,k,O).call(this,t);for(const t of Z(this,b).keys())t.startsWith(e)&&Z(this,b).delete(t)},B=new WeakSet,M=function(t,e){if(st(this,w,y).call(this,t)||st(this,w,y).call(this,e))return t===e;if(Object.keys(t).length!==Object.keys(e).length)return!1;for(const s in t)if(t[s]!==e[s])return!1;return!0},j=new WeakSet,N=function(t,e,s,r){if(t[e]=s,et(this,l,!0),st(this,W,P).call(this,r),Z(this,a)&&"update"===Z(this,h)){const t=r.slice(1),e=st(this,k,O).call(this,t);e.length&&st(this,g,m).call(this,e)}},_=new WeakSet,D=function(t,e,s){switch(this.defaultComparator){case"ref":return t[e]!==s;case"shallow":return!st(this,B,M).call(this,t[e],s);case"custom":if(!this.customComparator)throw new Error("Custom comparator is not provided.");return!this.customComparator(t[e],s);default:return!0}},J=new WeakSet,I=function(t){return{get:(e,s)=>st(this,E,T).call(this,e,s,t),set:(e,s,r)=>{if(!Z(this,c))throw new Error("Access is denied.");const i=t.concat(s);return(Z(this,d)||st(this,_,D).call(this,e,s,r))&&st(this,j,N).call(this,e,s,r,i),!0},defineProperty:()=>{throw new Error("Cannot define property.")},deleteProperty:(e,s)=>{if(!Z(this,c))throw new Error('Cannot delete property directly. Use "update" instead.');if(!(s in e))return console.warn(`property not found: ${String(s)}`),!1;const r=t.concat(s);return delete e[s],st(this,W,P).call(this,r),!0}}},U=new WeakSet,L=function(t){Z(this,o)[t.subId]=t},G=new WeakSet,x=function(){return Symbol()},$=new WeakSet,z=function(){const t=Z(this,o),e=[],s=Object.getOwnPropertySymbols(t);for(const r of s){const s=t[r];try{s.notifyCondition&&!s.notifyCondition()||s.subCb()}catch(t){e.push(r),console.info(`One of your subscribers marked as inactive and was removed. Error message - ${i(t)}`)}}e.length>0&&this.unsubscribeByIds(e)},Y=new WeakSet,q=function(t){return null!==t&&"object"==typeof t},F=new WeakSet,H=function(t,e){const s=new Map(t.map((t=>[t,t.length])));return 0===e.length||e.some((t=>{for(const[e,r]of s)if(t.slice(0,r)===e)return!0;return!1}))},K=new WeakSet,Q=function(t,e){return et(this,c,!0),et(this,h,e),t(),et(this,h,"none"),et(this,c,!1),Z(this,l)};var it,nt,ot=Object.defineProperty,at=Object.getOwnPropertySymbols,ht=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable,ut=(t,e,s)=>e in t?ot(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,lt=(t,e)=>{for(var s in e||(e={}))ht.call(e,s)&&ut(t,s,e[s]);if(at)for(var s of at(e))ct.call(e,s)&&ut(t,s,e[s]);return t},pt=(t,e,s)=>{if(!e.has(t))throw TypeError("Cannot "+s)},dt=(t,e,s)=>(pt(t,e,"read from private field"),s?s.call(t):e.get(t)),bt=(t,e,s)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,s)},ft=(t,e,s,r)=>(pt(t,e,"write to private field"),r?r.call(t,s):e.set(t,s),s);class wt{constructor(t,e){var s,r;bt(this,it,void 0),ut(this,"symbol"!=typeof(s="DEBUG")?s+"":s,r),this.set=this.set.bind(this),this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this),this.unsubscribeAll=this.unsubscribeAll.bind(this),this.getActiveSubscribersCount=this.getActiveSubscribersCount.bind(this),this.update=this.update.bind(this),this.unwrap=this.unwrap.bind(this),ft(this,it,new rt(t,{customComparator:e.customComparator,defaultComparator:e.defaultComparator})),this.DEBUG=e.debugService}set(t,e={}){try{return dt(this,it).set(t,lt({afterUpdate:()=>{void 0!==this.DEBUG&&this.DEBUG.transactionService.addTransaction(this.unwrap())}},e))}catch(t){throw new Error(r("An error occurred while setting the new state",t))}}get(){return dt(this,it).get()}subscribe(t,e={}){return dt(this,it).subscribe(t,e)}unsubscribeAll(){dt(this,it).unsubscribeAll()}getActiveSubscribersCount(){return dt(this,it).getActiveSubscribersCount()}update(t,e={}){try{return dt(this,it).update(t,lt({afterUpdate:()=>{void 0!==this.DEBUG&&this.DEBUG.transactionService.addTransaction(this.unwrap())}},e))}catch(t){throw new Error(r("An error occurred while updating the state",t))}}unwrap(){return dt(this,it).unwrap()}asyncAction(t){return e=this,s=null,r=function*(){try{yield t(this)}catch(t){throw new Error(`An error occurred while dispatching the async action: ${t.message}`)}},new Promise(((t,i)=>{var n=t=>{try{a(r.next(t))}catch(t){i(t)}},o=t=>{try{a(r.throw(t))}catch(t){i(t)}},a=e=>e.done?t(e.value):Promise.resolve(e.value).then(n,o);a((r=r.apply(e,s)).next())}));var e,s,r}createSelector(t,e={}){return new yt((()=>t(this.get())),[this],lt({debugService:this.DEBUG,customComparator:dt(this,it).customComparator,defaultComparator:dt(this,it).defaultComparator},e))}}it=new WeakMap;class yt{constructor(t,e,s){if(bt(this,nt,void 0),!e.length)throw new Error("No dependencies provided");this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this),this.unsubscribeAll=this.unsubscribeAll.bind(this),this.getActiveSubscribersCount=this.getActiveSubscribersCount.bind(this),this.unwrap=this.unwrap.bind(this),ft(this,nt,new wt(t(),{debugService:s.debugService,customComparator:s.customComparator,defaultComparator:s.defaultComparator}));for(const r of e)r.subscribe((()=>{dt(this,nt).set(t())}),{notifyCondition:s.notifyCondition,protect:void 0===s.protect||s.protect,properties:s.properties})}get(){return dt(this,nt).get()}subscribe(t,e){return dt(this,nt).subscribe(t,e)}unsubscribeAll(){dt(this,nt).unsubscribeAll()}getActiveSubscribersCount(){return dt(this,nt).getActiveSubscribersCount()}unwrap(){return dt(this,nt).unwrap()}}nt=new WeakMap;var gt,mt,vt,St=(t,e,s)=>{if(!e.has(t))throw TypeError("Cannot "+s)},Ct=(t,e,s)=>(St(t,e,"read from private field"),s?s.call(t):e.get(t)),At=(t,e,s)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,s)},kt=(t,e,s,r)=>(St(t,e,"write to private field"),r?r.call(t,s):e.set(t,s),s);class Ot{constructor(t){At(this,gt,new Map),At(this,mt,1),At(this,vt,void 0),this.addTransaction=this.addTransaction.bind(this),this.getLastTransaction=this.getLastTransaction.bind(this),this.getAllTransactions=this.getAllTransactions.bind(this),this.getTransactionByNumber=this.getTransactionByNumber.bind(this),this.getLastDiff=this.getLastDiff.bind(this),this.getDiffBetween=this.getDiffBetween.bind(this),kt(this,vt,t>2?t:2)}get totalTransactions(){return Ct(this,mt)}addTransaction(t){const e=(s=this,r=mt,{set _(t){kt(s,r,t,i)},get _(){return Ct(s,r,n)}})._++;var s,r,i,n;const o=Date.now(),a={number:e,snapshot:JSON.parse(JSON.stringify(t)),timestamp:o};if(Ct(this,gt).size>=Ct(this,vt)){const t=Array.from(Ct(this,gt).keys())[0];Ct(this,gt).delete(t)}Ct(this,gt).set(e,a)}getLastTransaction(){return Ct(this,gt).size>0?JSON.parse(JSON.stringify(Array.from(Ct(this,gt).values()))).pop():null}getAllTransactions(){return JSON.parse(JSON.stringify(Array.from(Ct(this,gt).values())))}getTransactionByNumber(t){return JSON.parse(JSON.stringify(Ct(this,gt).get(t)))||null}getLastDiff(){const t=JSON.parse(JSON.stringify(Array.from(Ct(this,gt).values()))),e=t.length;if(e<2)return null;return{old:t[e-2].snapshot,new:t[e-1].snapshot}}getDiffBetween(t,e){if(t>=e)throw new Error("transactionA must be less than transactionB");const s=Ct(this,gt).get(t),r=Ct(this,gt).get(e);return s&&r?JSON.parse(JSON.stringify({old:s.snapshot,new:r.snapshot})):null}}gt=new WeakMap,mt=new WeakMap,vt=new WeakMap;var Et=Object.defineProperty,Tt=Object.defineProperties,Wt=Object.getOwnPropertyDescriptors,Pt=Object.getOwnPropertySymbols,Bt=Object.prototype.hasOwnProperty,Mt=Object.prototype.propertyIsEnumerable,jt=(t,e,s)=>e in t?Et(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;function Nt(t,e){let r;return void 0!==e&&void 0!==e.transactionsLen&&(r=new s(new Ot(e.transactionsLen))),new wt(t,{debugService:r,customComparator:null==e?void 0:e.customComparator,defaultComparator:null==e?void 0:e.defaultComparator})}function _t(t,e,r){return new yt(t,e,(i=((t,e)=>{for(var s in e||(e={}))Bt.call(e,s)&&jt(t,s,e[s]);if(Pt)for(var s of Pt(e))Mt.call(e,s)&&jt(t,s,e[s]);return t})({},r||{}),n={debugService:void 0!==r&&void 0!==r.transactionsLen?new s(new Ot(r.transactionsLen)):void 0,customComparator:null==r?void 0:r.customComparator,defaultComparator:null==r?void 0:r.defaultComparator},Tt(i,Wt(n))));var i,n}export{_t as createComputedState,Nt as createState};
//# sourceMappingURL=statemanjs.mjs.map