UNPKG

mobx-state-tree

Version:

Opinionated, transactional, MobX powered state container

2 lines • 74.9 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("mobx");let t="warn";function n(e){t=e}function i(){return t}var s;function r(e){return ce(e).type}function o(e,t){return ce(e).onPatch(t)}function a(e,t){ce(e).applyPatches(Ie(t))}function c(e,t){return ce(e).applySnapshot(t)}function h(e,t=!0){const n=ce(e);return t?n.snapshot:n.type.getSnapshot(n,!1)}function l(e){return ce(e).root.storedValue}function u(e){return ce(e).path}function p(e){return ce(e).identifier}function d(e,t){const n=de(ce(e),t,!1);if(void 0!==n)try{return n.value}catch(e){return}}function f(e){return ce(e).observableIsAlive}function g(e){let t;return t=ae(e)?r(e):e,{name:t.name,properties:Object.assign({},t.properties)}}!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(s||(s={}));class y{get subpath(){return this._subpath}get subpathUponDeath(){return this._subpathUponDeath}get pathUponDeath(){return this._pathUponDeath}get value(){return this.type.getValue(this)}get state(){return this._state}set state(e){const t=this.isAlive;this._state=e;const n=this.isAlive;this.aliveAtom&&t!==n&&this.aliveAtom.reportChanged()}fireInternalHook(e){this._hookSubscribers&&this._hookSubscribers.emit(e,this,e)}registerHook(e,t){return this._hookSubscribers||(this._hookSubscribers=new Ve),this._hookSubscribers.register(e,t)}get parent(){return this._parent}constructor(e,t,n,i){this.type=e,this.environment=i,this._subpathUponDeath=void 0,this._pathUponDeath=void 0,this.storedValue=void 0,this.aliveAtom=void 0,this._state=oe.INITIALIZING,this._hookSubscribers=void 0,this.pathAtom=void 0,this.environment=i,this.baseSetParent(t,n)}getReconciliationType(){return this.type}baseSetParent(e,t){this._parent=e,this._subpath=t,this._escapedSubpath=void 0,this.pathAtom&&this.pathAtom.reportChanged()}get path(){return this.getEscapedPath(!0)}getEscapedPath(t){return t&&(this.pathAtom||(this.pathAtom=e.createAtom("path")),this.pathAtom.reportObserved()),this.parent?(void 0===this._escapedSubpath&&(this._escapedSubpath=this._subpath?Fe(this._subpath):""),this.parent.getEscapedPath(t)+"/"+this._escapedSubpath):""}get isRoot(){return null===this.parent}get isAlive(){return this.state!==oe.DEAD}get isDetaching(){return this.state===oe.DETACHING}get observableIsAlive(){return this.aliveAtom||(this.aliveAtom=e.createAtom("alive")),this.aliveAtom.reportObserved(),this.isAlive}baseFinalizeCreation(e){if(this.state===oe.CREATED){if(this.parent){if(this.parent.state!==oe.FINALIZED)return;this.fireHook(s.afterAttach)}this.state=oe.FINALIZED,e&&e()}}baseFinalizeDeath(){this._hookSubscribers&&this._hookSubscribers.clearAll(),this._subpathUponDeath=this._subpath,this._pathUponDeath=this.getEscapedPath(!1),this.baseSetParent(null,""),this.state=oe.DEAD}baseAboutToDie(){this.fireHook(s.beforeDestroy)}}class b extends y{constructor(e,t,n,i,s){super(e,t,n,i);try{this.storedValue=e.createNewInstance(s)}catch(e){throw this.state=oe.DEAD,e}this.state=oe.CREATED,this.finalizeCreation()}get root(){if(!this.parent)throw new we("This scalar node is not part of a tree");return this.parent.root}setParent(e,t){const n=this.parent!==e,i=this.subpath!==t;(n||i)&&(this.environment=void 0,this.baseSetParent(this.parent,t))}get snapshot(){return this.getSnapshot()}getSnapshot(){return this.type.getSnapshot(this)}toString(){const e=(this.isAlive?this.path:this.pathUponDeath)||"<root>";return`${this.type.name}@${e}${this.isAlive?"":" [dead]"}`}die(){this.isAlive&&this.state!==oe.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}finalizeCreation(){this.baseFinalizeCreation()}aboutToDie(){this.baseAboutToDie()}finalizeDeath(){this.baseFinalizeDeath()}fireHook(e){this.fireInternalHook(e)}}b.prototype.die=e.action(b.prototype.die);let v=1;var m,w;!function(e){e[e.UNINITIALIZED=0]="UNINITIALIZED",e[e.CREATING=1]="CREATING",e[e.CREATED=2]="CREATED"}(m||(m={})),function(e){e.Dispose="dispose",e.Patch="patch",e.Snapshot="snapshot"}(w||(w={}));const _={fireImmediately:!0,onError(e){throw e}};class S extends y{applyPatches(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}applySnapshot(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}constructor(t,n,i,s,r){super(t,n,i,s),this.nodeId=++v,this.identifierCache=void 0,this.isProtectionEnabled=!0,this.middlewares=void 0,this.hasSnapshotPostProcessor=!1,this._applyPatches=void 0,this._applySnapshot=void 0,this._autoUnbox=!0,this._isRunningAction=!1,this._hasSnapshotReaction=!1,this._endOfActionCallbacks=void 0,this._observableInstanceState=m.UNINITIALIZED,this._cachedInitialSnapshot=void 0,this._cachedInitialSnapshotCreated=!1,this._snapshotUponDeath=void 0,this._internalEvents=void 0;const o={node:this};if(this._snapshotSource=o,this._snapshotComputed=e.computed(()=>{const t=o.node;if(!t)return o.snapshotUponDeath;const n=t.getSnapshot();return t.state===oe.INITIALIZING&&t._cachedInitialSnapshotCreated&&e.compareShallow(n,t._cachedInitialSnapshot)?t._cachedInitialSnapshot:n},{keepAlive:!0}),this.unbox=this.unbox.bind(this),this._initialSnapshot=r,this.identifierAttribute=t.identifierAttribute,n||(this.identifierCache=new ie),this._childNodes=t.initializeChildNodes(this,this._initialSnapshot),this.identifier=null,this.unnormalizedIdentifier=null,this.identifierAttribute&&this._initialSnapshot){let e=this._initialSnapshot[this.identifierAttribute];if(void 0===e){const t=this._childNodes[this.identifierAttribute];t&&(e=t.value)}if("string"!=typeof e&&"number"!=typeof e&&"bigint"!=typeof e)throw new we(`Instance identifier '${this.identifierAttribute}' for type '${this.type.name}' must be a string, a number or a bigint`);this.identifier=Jt(e),this.unnormalizedIdentifier=e}n?n.root.identifierCache.addNodeToCache(this):this.identifierCache.addNodeToCache(this)}createObservableInstanceIfNeeded(e=!0){this._observableInstanceState===m.UNINITIALIZED&&this.createObservableInstance(e)}createObservableInstance(e=!0){this._observableInstanceState=m.CREATING;const t=[];let n=this.parent;for(;n&&n._observableInstanceState===m.UNINITIALIZED;)t.unshift(n),n=n.parent;for(const e of t)e.createObservableInstanceIfNeeded(!1);const i=this.type;try{this.storedValue=i.createNewInstance(this._childNodes),this.preboot(),this._isRunningAction=!0,i.finalizeNewInstance(this,this.storedValue)}catch(e){throw this.state=oe.DEAD,e}finally{this._isRunningAction=!1}if(this._observableInstanceState=m.CREATED,this._snapshotComputed.trackAndCompute(),this._childNodes=ve,this.state=oe.CREATED,e){this.fireHook(s.afterCreate),this.finalizeCreation();for(const e of t.reverse())e.fireHook(s.afterCreate),e.finalizeCreation()}}get root(){const e=this.parent;return e?e.root:this}enqueueEndOfAction(e){const t=this.root;t._endOfActionCallbacks||(t._endOfActionCallbacks=[]),t._endOfActionCallbacks.push(e)}flushEndOfActionCallbacks(){const e=this.root;for(;e._endOfActionCallbacks&&e._endOfActionCallbacks.length>0;){const t=e._endOfActionCallbacks;e._endOfActionCallbacks=void 0,t.forEach(e=>{e()})}}clearParent(){if(!this.parent)return;this.fireHook(s.beforeDetach);const e=this.state;this.state=oe.DETACHING;const t=this.root,n=t.environment,i=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=n,this.identifierCache=i}finally{this.state=e}}setParent(e,t){const n=e!==this.parent,i=t!==this.subpath;(n||i)&&(n?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(s.afterAttach)):i&&this.baseSetParent(this.parent,t))}fireHook(t){this.fireInternalHook(t);const n=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[t];"function"==typeof n&&(e._allowStateChangesInsideComputed?e._allowStateChangesInsideComputed(()=>{n.apply(this.storedValue)}):n.apply(this.storedValue))}get snapshot(){return this.hasSnapshotPostProcessor&&this.createObservableInstanceIfNeeded(),this._snapshotComputed.get()}getSnapshot(){return this.isAlive?this._observableInstanceState===m.CREATED?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}_getActualSnapshot(){return this.type.getSnapshot(this)}_getCachedInitialSnapshot(){if(!this._cachedInitialSnapshotCreated){const e=this.type,t=this._childNodes,n=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,n),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}isRunningAction(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}assertAlive(e){const t=i();if(!this.isAlive&&"ignore"!==t){const i=this._getAssertAliveError(e);switch(t){case"error":throw new we(i);case"warn":n=i,console.warn(new Error("[mobx-state-tree] "+n))}}var n}_getAssertAliveError(e){const t=this.getEscapedPath(!1)||this.pathUponDeath||"",n=e.subpath&&Fe(e.subpath)||"";let i=e.actionContext||k();i&&"action"!==i.type&&i.parentActionEvent&&(i=i.parentActionEvent);let s="";if(i&&null!=i.name){s=`${i&&i.context&&u(i.context)||t}.${i.name}()`}return`You are trying to read or write to an object that is no longer part of a state tree. (Object type: '${this.type.name}', Path upon death: '${t}', Subpath: '${n}', Action: '${s}'). Either detach nodes first, or don't use objects after removing / replacing them in the tree.`}getChildNode(e){this.assertAlive({subpath:e}),this._autoUnbox=!1;try{return this._observableInstanceState===m.CREATED?this.type.getChildNode(this,e):this._childNodes[e]}finally{this._autoUnbox=!0}}getChildren(){this.assertAlive(ve),this._autoUnbox=!1;try{return this._observableInstanceState===m.CREATED?this.type.getChildren(this):ge(this._childNodes)}finally{this._autoUnbox=!0}}getChildType(e){return this.type.getChildType(e)}get isProtected(){return this.root.isProtectionEnabled}assertWritable(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw new we(`Cannot modify '${this}', the object is protected and can only be modified by using an action.`)}removeChild(e){this.type.removeChild(this,e)}unbox(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}toString(){const e=(this.isAlive?this.path:this.pathUponDeath)||"<root>",t=this.identifier?`(id: ${this.identifier})`:"";return`${this.type.name}@${e}${t}${this.isAlive?"":" [dead]"}`}finalizeCreation(){this.baseFinalizeCreation(()=>{for(let e of this.getChildren())e.finalizeCreation();this.fireInternalHook(s.afterCreationFinalization)})}detach(){if(!this.isAlive)throw new we("Error while detaching, node is not alive.");this.clearParent()}preboot(){const e=this;this._applyPatches=M(this.storedValue,"@APPLY_PATCHES",t=>{t.forEach(t=>{if(!t.path)return void e.type.applySnapshot(e,t.value);const n=He(t.path);fe(e,n.slice(0,-1),!0,!De(t.path,"/")).applyPatchLocally(n[n.length-1],t)})}),this._applySnapshot=M(this.storedValue,"@APPLY_SNAPSHOT",t=>{if(t!==e.snapshot)return e.type.applySnapshot(e,t)}),Ee(this.storedValue,"$treenode",this),Ee(this.storedValue,"toJSON",le)}die(){this.isAlive&&this.state!==oe.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}aboutToDie(){this._observableInstanceState!==m.UNINITIALIZED&&(this.getChildren().forEach(e=>{e.aboutToDie()}),this.baseAboutToDie(),this._internalEventsEmit(w.Dispose),this._internalEventsClear(w.Dispose))}finalizeDeath(){this.getChildren().forEach(e=>{e.finalizeDeath()}),this.root.identifierCache.notifyDied(this);const e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath(),this._snapshotSource.snapshotUponDeath=e,this._snapshotSource.node=void 0,this._snapshotComputed.trackAndCompute()}onSnapshot(e){return this._addSnapshotReaction(),this._internalEventsRegister(w.Snapshot,e)}emitSnapshot(e){this._internalEventsEmit(w.Snapshot,e)}onPatch(e){return this._internalEventsRegister(w.Patch,e)}hasPatchSubscribers(){return!!this._internalEventsHasSubscribers(w.Patch)||!!this.parent&&this.parent.hasPatchSubscribers()}emitPatch(e,t){if(this._internalEventsHasSubscribers(w.Patch)){const n=function(e,...t){for(let n=0;n<t.length;n++){const i=t[n];for(let t in i)e[t]=i[t]}return e}({},e,{path:t.path.substr(this.path.length)+(void 0!==e.path?"/"+e.path:"")}),[i,s]=function(e){if(!("oldValue"in e))throw new we("Patches without `oldValue` field cannot be inversed");return[Re(e),ze(e)]}(n);this._internalEventsEmit(w.Patch,i,s)}this.parent&&this.parent.emitPatch(e,t)}hasDisposer(e){return this._internalEventsHas(w.Dispose,e)}addDisposer(e){if(this.hasDisposer(e))throw new we("cannot add a disposer when it is already registered for execution");this._internalEventsRegister(w.Dispose,e,!0)}removeDisposer(e){if(!this._internalEventsHas(w.Dispose,e))throw new we("cannot remove a disposer which was never registered for execution");this._internalEventsUnregister(w.Dispose,e)}removeMiddleware(e){if(this.middlewares){const t=this.middlewares.indexOf(e);t>=0&&this.middlewares.splice(t,1)}}addMiddleWare(e,t=!0){const n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],()=>{this.removeMiddleware(n)}}applyPatchLocally(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}_addSnapshotReaction(){if(!this._hasSnapshotReaction){let t=e.untracked(()=>this.snapshot);const n=e.reaction(()=>this.snapshot,e=>{e!==t&&(t=e,this.emitSnapshot(e))},_);this.addDisposer(n),this._hasSnapshotReaction=!0}}_internalEventsHasSubscribers(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}_internalEventsRegister(e,t,n=!1){return this._internalEvents||(this._internalEvents=new Ve),this._internalEvents.register(e,t,n)}_internalEventsHas(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}_internalEventsUnregister(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}_internalEventsEmit(e,...t){this._internalEvents&&this._internalEvents.emit(e,...t)}_internalEventsClear(e){this._internalEvents&&this._internalEvents.clear(e)}_internalEventsClearAll(){this._internalEvents&&this._internalEvents.clearAll()}}var A;S.prototype.createObservableInstance=e.action(S.prototype.createObservableInstance),S.prototype.detach=e.action(S.prototype.detach),S.prototype.die=e.action(S.prototype.die),function(e){e[e.String=1]="String",e[e.Number=2]="Number",e[e.Boolean=4]="Boolean",e[e.Date=8]="Date",e[e.Literal=16]="Literal",e[e.Array=32]="Array",e[e.Map=64]="Map",e[e.Object=128]="Object",e[e.Frozen=256]="Frozen",e[e.Optional=512]="Optional",e[e.Reference=1024]="Reference",e[e.Identifier=2048]="Identifier",e[e.Late=4096]="Late",e[e.Refinement=8192]="Refinement",e[e.Union=16384]="Union",e[e.Null=32768]="Null",e[e.Undefined=65536]="Undefined",e[e.Integer=131072]="Integer",e[e.Custom=262144]="Custom",e[e.SnapshotProcessor=524288]="SnapshotProcessor",e[e.Lazy=1048576]="Lazy",e[e.Finite=2097152]="Finite",e[e.Float=4194304]="Float",e[e.BigInt=8388608]="BigInt"}(A||(A={}));class I{constructor(e){this.isType=!0,this.name=e}create(e,t){return ee(this,e),this.instantiate(null,"",t,e).value}getSnapshot(e,t){throw new we("unimplemented method")}isAssignableFrom(e){return e===this}validate(e,t){if(he(e)){const n=r(e);return this.isAssignableFrom(n)?K():Q(t,e)}return this.isValidSnapshot(e,t)}is(e){return 0===this.validate(e,[{path:"",type:this}]).length}get Type(){throw new we("Factory.Type should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.Type`")}get TypeWithoutSTN(){throw new we("Factory.TypeWithoutSTN should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.TypeWithoutSTN`")}get SnapshotType(){throw new we("Factory.SnapshotType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.SnapshotType`")}get CreationType(){throw new we("Factory.CreationType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.CreationType`")}}I.prototype.create=e.action(I.prototype.create);class P extends I{constructor(e){super(e)}create(e=this.getDefaultSnapshot(),t){return super.create(e,t)}getValue(e){return e.createObservableInstanceIfNeeded(),e.storedValue}isMatchingSnapshotId(e,t){return!e.identifierAttribute||e.identifier===Jt(t[e.identifierAttribute])}tryToReconcileNode(e,t){return!e.isDetaching&&(e.snapshot===t||(!(!ae(t)||ce(t)!==e)||!(e.type!==this||!xe(t)||ae(t)||!this.isMatchingSnapshotId(e,t))&&(e.applySnapshot(t),!0)))}reconcile(e,t,n,i){if(this.tryToReconcileNode(e,t))return e.setParent(n,i),e;if(e.die(),ae(t)&&this.isAssignableFrom(r(t))){const e=ce(t);return e.setParent(n,i),e}return this.instantiate(n,i,void 0,t)}getSubTypes(){return null}}P.prototype.create=e.action(P.prototype.create);class x extends I{createNewInstance(e){return e}getValue(e){return e.storedValue}getSnapshot(e){return e.storedValue}reconcile(e,t,n,i){if(!e.isDetaching&&e.type===this&&e.storedValue===t)return e;const s=this.instantiate(n,i,void 0,t);return e.die(),s}getSubTypes(){return null}}function T(e,t,n){const i=t.getReconciliationType(),s=function e(t){const n=t.getSubTypes();if(!n||Array.isArray(n)||"cannotDetermine"===n||!function(e){const t=A.Optional|A.Late,n=A.Refinement|A.SnapshotProcessor|A.Union;return(e.flags&t)>0&&0==(e.flags&n)}(t))return t;return e(n)}(e);return t instanceof S&&i===s&&i instanceof P&&xe(n)&&!ae(n)&&i.isMatchingSnapshotId(t,n)}function C(e){return"object"==typeof e&&e&&!0===e.isType}const E=new Map;class N{constructor(e,t){this.hooks=e,this.call=t,this.flowsPending=0,this.running=!0,e&&e.onStart(t)}finish(e){this.running&&(this.running=!1,this.hooks&&this.hooks.onFinish(this.call,e))}incFlowsPending(){this.flowsPending++}decFlowsPending(){this.flowsPending--}get hasFlowsPending(){return this.flowsPending>0}}function V(e){return{$MST_UNSERIALIZABLE:!0,type:e}}function O(t,n){e.runInAction(()=>{Ie(n).forEach(e=>function(e,t){const n=d(e,t.path||"");if(!n)throw new we("Invalid action path: "+(t.path||""));const i=ce(n);if("@APPLY_PATCHES"===t.name)return a.call(null,n,t.args[0]);if("@APPLY_SNAPSHOT"===t.name)return c.call(null,n,t.args[0]);if("function"!=typeof n[t.name])throw new we(`Action '${t.name}' does not exist in '${i.path}'`);return n[t.name].apply(n,t.args?t.args.map(e=>{return(t=e)&&"object"==typeof t&&"$MST_DATE"in t?new Date(t.$MST_DATE):t;var t}):[])}(t,e))})}function D(e,t,n=!1){return L(e,(function(i,s){if("action"===i.type&&i.id===i.rootId){const o=ce(i.context),a={name:i.name,path:pe(ce(e),o),args:i.args.map((e,t)=>function(e,t,n,i){if(i instanceof Date)return{$MST_DATE:i.getTime()};if(Te(i))return i;if(ae(i))return V(`[MSTNode: ${r(i).name}]`);if("function"==typeof i)return V("[function]");if("object"==typeof i&&!Pe(i)&&!Ae(i))return V(`[object ${i&&i.constructor&&i.constructor.name||"Complex Object"}]`);try{return JSON.stringify(i),i}catch(e){return V(""+e)}}(0,i.name,0,e))};if(n){const e=s(i);return t(a),e}return t(a),s(i)}return s(i)}))}let $,j=1;function k(){return $}function R(){return j++}function z(t,n){const i=ce(t.context);"action"===t.type&&i.assertAlive({actionContext:t});const r=i._isRunningAction;i._isRunningAction=!0;const o=$,a=!o;$=t;try{return function(t,n,i,r){function o(n,i){const s=()=>{let e,s;try{e=i.apply(null,n.args)}catch(e){s=e}if(r||!n.parentActionEvent)try{t.root.flushEndOfActionCallbacks()}catch(e){s||(s=e)}if(s)throw s;return e};return n.name?e.action(n.name,s)():e.action(s)()}const a=new H(t,i);if(a.isEmpty)return o(n,i);let c=null;return function e(t){const n=a.getNextMiddleware(),h=n&&n.handler;if(!h)return o(t,i);if(!n.includeHooks&&s[t.name])return e(t);let l=!1;return h(t,(function(t,n){c=e(t),n&&(c=n(c))}),(function(e){l=!0,c=e})),!l||!r&&t.parentActionEvent?c:o(t,()=>c)}(n)}(i,t,n,a)}finally{$=o,i._isRunningAction=r}}function F(e){if(e)return"action"===e.type?e:e.parentActionEvent}function M(e,t,n){const i=function(){const i=R(),s=$,r=F(s);return z({type:"action",name:t,id:i,args:Oe(arguments),context:e,tree:l(e),rootId:s?s.rootId:i,parentId:s?s.id:0,allParentIds:s?[...s.allParentIds,s.id]:[],parentEvent:s,parentActionEvent:r},n)};return i._isMSTAction=!0,i._isFlowAction=n._isFlowAction,i}function L(e,t,n=!0){return ce(e).addMiddleWare(t,n)}class H{constructor(e,t){this.arrayIndex=0,this.inArrayIndex=0,this.middlewares=[],t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);let n=e;for(;n;)n.middlewares&&this.middlewares.push(n.middlewares),n=n.parent}get isEmpty(){return this.middlewares.length<=0}getNextMiddleware(){const e=this.middlewares[this.arrayIndex];if(!e)return;const t=e[this.inArrayIndex++];return t||(this.arrayIndex++,this.inArrayIndex=0,this.getNextMiddleware())}}function U(){let e=k();for(;e&&"action"!==e.type;)e=e.parentActionEvent;return e}function B(e,t,n){const i="number"==typeof t?t:t.id;let s=n?e:e.parentActionEvent;for(;s;){if(s.id===i)return!0;s=s.parentActionEvent}return!1}let G=Object.assign({},{enabled:!1,indent:2,maxStringLength:100,maxArrayLength:10,maxPropertyCount:30,maxDepth:5});function W(){return Object.assign({},G)}function Z(e,t){try{return JSON.stringify(e,null,t)}catch(e){return`<Unserializable: ${e}>`}}function Y(e){if("function"==typeof e)return`<function${e.name?" "+e.name:""}>`;if(ae(e))return`<${e}>`;const t=W();if(!t.enabled)return`\`${Z(e)}\``;return`\`${Z(function e(t,n,i){if("string"==typeof t)return t.length>i.maxStringLength?`${t.slice(0,i.maxStringLength)}… (${t.length-i.maxStringLength} more characters)`:t;if(Array.isArray(t)){if(n>=i.maxDepth)return"[…]";const s=t.slice(0,i.maxArrayLength).map(t=>e(t,n+1,i));return t.length>i.maxArrayLength&&s.push(`… ${t.length-i.maxArrayLength} more items`),s}if(Pe(t)){if(n>=i.maxDepth)return"{…}";const s={},r=Object.keys(t);return r.slice(0,i.maxPropertyCount).forEach(r=>{s[r]=e(t[r],n+1,i)}),r.length>i.maxPropertyCount&&(s["…"]=r.length-i.maxPropertyCount+" more keys"),s}return t}(e,0,t),t.indent||void 0)}\``}function J(e){const{value:t}=e,n=e.context[e.context.length-1].type,i=e.context.map(({path:e})=>e).filter(e=>e.length>0).join("/"),s=i.length>0?`at path "/${i}" `:"",r=ae(t)?`value of type ${ce(t).type.name}:`:Te(t)?"value":"snapshot",o=n&&ae(t)&&n.is(ce(t).snapshot),a=W();return`${s}${r} ${Y(t)} is not assignable ${n?`to type: \`${n.name}\``:""}`+(e.message?` (${e.message})`:"")+(n?St(n)||Te(t)?".":`, expected an instance of \`${n.name}\` or a snapshot like \`${c=n,a.enabled?function(e,t){if(t<=0)return e;try{const n=" ".repeat(t);let i="",s=0,r=null,o=!1;const a=()=>{i=i.replace(/[ \t]+$/,""),i+="\n"+n.repeat(Math.max(0,s))};for(let t=0;t<e.length;t++){const n=e[t];if(r)i+=n,o?o=!1:"\\"===n?o=!0:n===r&&(r=null);else switch(n){case'"':case"'":r=n,i+=n;break;case"{":for(s++,i+="{",a();" "===e[t+1];)t++;break;case"}":s--,a(),i+="}";break;case";":for(i+=";",a();" "===e[t+1];)t++;break;default:i+=n}}return i}catch(t){return e}}(c.describe(),a.indent):c.describe()}\` instead.`+(o?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".");var c}function q(e,t,n){return e.concat([{path:t,type:n}])}function K(){return be}function Q(e,t,n){return[{context:e,value:t,message:n}]}function X(e){return e.reduce((e,t)=>e.concat(t),[])}function ee(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&te(e,t)}function te(e,t){const n=e.validate(t,[{path:"",type:e}]);if(n.length>0)throw new we(function(e,t,n){if(0===n.length)return;const i=Y(t);return`Error while converting ${W().enabled?i:(s=i,s.length<280?s:`${s.substring(0,272)}......${s.substring(s.length-8)}`)} to \`${e.name}\`:\n\n    `+n.map(J).join("\n    ");var s}(e,t,n))}let ne=0;class ie{constructor(){this.cacheId=ne++,this.cache=e.observable.map(),this.lastCacheModificationPerId=e.observable.map()}updateLastCacheModificationPerId(e){const t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}getLastCacheModificationPerId(e){const t=this.lastCacheModificationPerId.get(e)||0;return`${this.cacheId}-${t}`}addNodeToCache(t,n=!0){if(t.identifierAttribute){const i=t.identifier;this.cache.has(i)||this.cache.set(i,e.observable.array([],me));const s=this.cache.get(i);if(-1!==s.indexOf(t))throw new we("Already registered");s.push(t),n&&this.updateLastCacheModificationPerId(i)}}mergeCache(t){e.values(t.identifierCache.cache).forEach(e=>e.forEach(e=>{this.addNodeToCache(e)}))}notifyDied(e){if(e.identifierAttribute){const t=e.identifier,n=this.cache.get(t);n&&(n.remove(e),n.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}splitCache(e){const t=new ie;if(0===this.cache.size)return t;const n=e=>{e instanceof S&&(this.notifyDied(e),t.addNodeToCache(e,!1),e.getChildren().forEach(n))};return n(e),t}has(e,t){const n=this.cache.get(t);return!!n&&n.some(t=>e.isAssignableFrom(t.type))}resolve(e,t){const n=this.cache.get(t);if(!n)return null;const i=n.filter(t=>e.isAssignableFrom(t.type));switch(i.length){case 0:return null;case 1:return i[0];default:throw new we(`Cannot resolve a reference to type '${e.name}' with id: '${t}' unambigously, there are multiple candidates: ${i.map(e=>e.path).join(", ")}`)}}}function se(e,t,n,i,s){const r=he(s);if(r){if(r.parent)throw new we(`Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '${t?t.path:""}/${n}', but it lives already at '${r.path}'`);return t&&r.setParent(t,n),r}return new S(e,t,n,i,s)}function re(e,t,n,i,s){return new b(e,t,n,i,s)}var oe;function ae(e){return!(!e||!e.$treenode)}function ce(e){if(!ae(e))throw new we(`Value ${e} is no MST Node`);return e.$treenode}function he(e){return e&&e.$treenode||null}function le(){return ce(this).snapshot}!function(e){e[e.INITIALIZING=0]="INITIALIZING",e[e.CREATED=1]="CREATED",e[e.FINALIZED=2]="FINALIZED",e[e.DETACHING=3]="DETACHING",e[e.DEAD=4]="DEAD"}(oe||(oe={}));const ue=e=>"..";function pe(e,t){if(e.root!==t.root)throw new we(`Cannot calculate relative path: objects '${e}' and '${t}' are not part of the same object tree`);const n=He(e.path),i=He(t.path);let s=0;for(;s<n.length&&n[s]===i[s];s++);return n.slice(s).map(ue).join("/")+Le(i.slice(s))}function de(e,t,n=!0){return fe(e,He(t),n)}function fe(e,t,n=!0,i=!0){let s=e;try{for(let e=0;e<t.length;e++){const n=t[e];if(i&&".."===n){if(s=s.parent,s)continue}else{if(i&&"."===n)continue;if(s){if(s instanceof b){const e=s.value;ae(e)&&(s=ce(e))}if(s instanceof S){if(s.getChildType(n)&&(s=s.getChildNode(n),s))continue}}}throw new we(`Could not resolve '${n}' in path '${Le(t.slice(0,e))||"/"}' while resolving '${Le(t)}'`)}}catch(e){if(!n)return;throw e}return s}function ge(e){if(!e)return be;const t=Object.keys(e);if(!t.length)return be;const n=new Array(t.length);return t.forEach((t,i)=>{n[i]=e[t]}),n}const ye=Object.toString(),be=Object.freeze([]),ve=Object.freeze({}),me={deep:!1};Object.freeze(me);class we extends Error{constructor(e="Illegal state"){super("[mobx-state-tree] "+e)}}function _e(e){return e}const Se=Number.isInteger;function Ae(t){return Array.isArray(t)||e.isObservableArray(t)}function Ie(e){return e?Ae(e)?e:[e]:be}function Pe(e){var t;if(null===e||"object"!=typeof e)return!1;const n=Object.getPrototypeOf(e);return null==n||(null===(t=n.constructor)||void 0===t?void 0:t.toString())===ye}function xe(e){return!(null===e||"object"!=typeof e||e instanceof Date||e instanceof RegExp)}function Te(e,t=!0){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e||t&&e instanceof Date}function Ce(e){return"function"!=typeof e}function Ee(t,n,i){!function(t,n,i){e.isObservableObject(t)?e.defineProperty(t,n,i):Object.defineProperty(t,n,i)}(t,n,{enumerable:!1,writable:!1,configurable:!0,value:i})}class Ne{constructor(){this.handlers=[]}get hasSubscribers(){return this.handlers.length>0}register(e,t=!1){return t?this.handlers.unshift(e):this.handlers.push(e),()=>{this.unregister(e)}}has(e){return this.handlers.indexOf(e)>=0}unregister(e){const t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}clear(){this.handlers.length=0}emit(...e){this.handlers.slice().forEach(t=>t(...e))}}class Ve{hasSubscribers(e){const t=this.eventHandlers&&this.eventHandlers[e];return!!t&&t.hasSubscribers}register(e,t,n=!1){this.eventHandlers||(this.eventHandlers={});let i=this.eventHandlers[e];return i||(i=this.eventHandlers[e]=new Ne),i.register(t,n)}has(e,t){const n=this.eventHandlers&&this.eventHandlers[e];return!!n&&n.has(t)}unregister(e,t){const n=this.eventHandlers&&this.eventHandlers[e];n&&n.unregister(t)}clear(e){this.eventHandlers&&delete this.eventHandlers[e]}clearAll(){this.eventHandlers=void 0}emit(e,...t){const n=this.eventHandlers&&this.eventHandlers[e];n&&n.emit(...t)}}function Oe(e){const t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function De(e,t){return 0===e.indexOf(t)}const $e=function(e,t){};function je(e){"function"==typeof queueMicrotask?queueMicrotask(e):"function"==typeof setImmediate?setImmediate(e):setTimeout(e,1)}function ke(e){return function(e,t){const n=function(){const i=R(),s=k();if(!s)throw new we("a mst flow must always have a parent context");const r=F(s);if(!r)throw new we("a mst flow must always have a parent action context");const o={name:e,id:i,tree:s.tree,context:s.context,parentId:s.id,allParentIds:[...s.allParentIds,s.id],rootId:s.rootId,parentEvent:s,parentActionEvent:r},a=arguments;function c(e,t,i){return e.$mst_middleware=n.$mst_middleware,z(Object.assign(Object.assign({},o),{type:t,args:[i]}),e)}return new Promise((function(e,i){let s;const r=function(){s=t.apply(null,arguments),h(void 0)};function h(e){let t;try{const n=c(e=>{t=s.next(e)},"flow_resume",e);n instanceof Error&&(t=s.throw(n))}catch(e){return void je(()=>{c(t=>{i(e)},"flow_throw",e)})}u(t)}function l(e){let t;try{c(e=>{t=s.throw(e)},"flow_resume_error",e)}catch(e){return void je(()=>{c(t=>{i(e)},"flow_throw",e)})}u(t)}function u(t){if(!t.done){if(!t.value||"function"!=typeof t.value.then)throw new we("Only promises can be yielded to `async`, got: "+t);return t.value.then(h,l)}je(()=>{c(t=>{e(t)},"flow_return",t.value)})}r.$mst_middleware=n.$mst_middleware,z(Object.assign(Object.assign({},o),{type:"flow_spawn",args:Oe(a)}),r)}))};return n._isFlowAction=!0,n}(e.name,e)}function Re(e){switch(e.op){case"add":return{op:"add",path:e.path,value:e.value};case"remove":return{op:"remove",path:e.path};case"replace":return{op:"replace",path:e.path,value:e.value}}}function ze(e){switch(e.op){case"add":return{op:"remove",path:e.path};case"remove":return{op:"add",path:e.path,value:e.oldValue};case"replace":return{op:"replace",path:e.path,value:e.oldValue}}}function Fe(e){return!0==("number"==typeof e)?""+e:-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Me(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Le(e){if(0===e.length)return"";const t=e=>e.map(Fe).join("/");return"."===e[0]||".."===e[0]?t(e):"/"+t(e)}function He(e){const t=e.split("/").map(Me);if(!(""===e||"."===e||".."===e||De(e,"/")||De(e,"./")||De(e,"../")))throw new we(`a json path must be either rooted, empty or relative, but got '${e}'`);return""===t[0]&&t.shift(),t}$e.ids={};const Ue=Symbol("$preProcessorFailed");class Be extends I{get flags(){return this._subtype.flags|A.SnapshotProcessor}constructor(e,t,n){super(n||e.name),this._subtype=e,this._processors=t}describe(){return`snapshotProcessor(${this._subtype.describe()})`}preProcessSnapshot(e){return this._processors.preProcessor?this._processors.preProcessor.call(null,e):e}preProcessSnapshotSafe(e){try{return this.preProcessSnapshot(e)}catch(e){return Ue}}postProcessSnapshot(e,t){return this._processors.postProcessor?this._processors.postProcessor.call(null,e,t.storedValue):e}_fixNode(e){!function(e,t,...n){for(const i of n)e[i]=t[i].bind(t)}(e.type,this,"create"),e instanceof S&&(e.hasSnapshotPostProcessor=!!this._processors.postProcessor);const t=e.getSnapshot;e.getSnapshot=()=>this.postProcessSnapshot(t.call(e),e),e instanceof S&&e.state!==oe.INITIALIZING&&e._snapshotComputed.trackAndCompute(),Ct(this._subtype)||(e.getReconciliationType=()=>this)}instantiate(e,t,n,i){const s=ae(i)?i:this.preProcessSnapshot(i),r=this._subtype.instantiate(e,t,n,s);return this._fixNode(r),r}reconcile(e,t,n,i){const s=this._subtype.reconcile(e,ae(t)?t:this.preProcessSnapshot(t),n,i);return s!==e&&this._fixNode(s),s}getSnapshot(e,t=!0){const n=this._subtype.getSnapshot(e);return t?this.postProcessSnapshot(n,e):n}isValidSnapshot(e,t){const n=this.preProcessSnapshotSafe(e);return n===Ue?Q(t,e,"Failed to preprocess value"):this._subtype.validate(n,t)}getSubTypes(){return this._subtype}is(e){const t=C(e)?this._subtype:ae(e)?e:this.preProcessSnapshotSafe(e);return t!==Ue&&0===this._subtype.validate(t,[{path:"",type:this._subtype}]).length}isAssignableFrom(e){return this._subtype.isAssignableFrom(e)}isMatchingSnapshotId(e,t){if(!(this._subtype instanceof P))return!1;const n=this.preProcessSnapshot(t);return this._subtype.isMatchingSnapshotId(e,n)}}const Ge="Map.put can only be used to store complex values that have an identifier type attribute";var We;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.YES=1]="YES",e[e.NO=2]="NO"}(We||(We={}));class Ze extends e.ObservableMap{constructor(e,t){super(e,e=>e,t)}get(e){return super.get(""+e)}has(e){return super.has(""+e)}delete(e){return super.delete(""+e)}set(e,t){return super.set(""+e,t)}put(e){if(!e)throw new we("Map.put cannot be used to set empty values");if(ae(e)){const t=ce(e);if(null===t.identifier)throw new we(Ge);return this.set(t.identifier,e),e}if(xe(e)){const t=ce(this),n=t.type;if(n.identifierMode!==We.YES)throw new we(Ge);const i=e[n.mapIdentifierAttribute];if(!qt(i)){const i=this.put(n.getChildType().create(e,t.environment));return this.put(h(i))}const s=Jt(i);return this.set(s,e),this.get(s)}throw new we("Map.put can only be used to store complex values")}}class Ye extends P{constructor(e,t,n=[]){super(e),this._subType=t,this.identifierMode=We.UNKNOWN,this.mapIdentifierAttribute=void 0,this.flags=A.Map,this.hookInitializers=[],this._determineIdentifierMode(),this.hookInitializers=n}hooks(e){const t=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new Ye(this.name,this._subType,t)}instantiate(e,t,n,i){return this._determineIdentifierMode(),se(this,e,t,n,i)}_determineIdentifierMode(){if(this.identifierMode!==We.UNKNOWN)return;const e=[];if(function e(t,n){const i=t.getSubTypes();if("cannotDetermine"===i)return!1;if(i){const t=Ie(i);for(const i of t)if(!e(i,n))return!1}return t instanceof at&&n.push(t),!0}(this._subType,e)){const t=e.reduce((e,t)=>{if(!t.identifierAttribute)return e;if(e&&e!==t.identifierAttribute)throw new we(`The objects in a map should all have the same identifier attribute, expected '${e}', but child of type '${t.name}' declared attribute '${t.identifierAttribute}' as identifier`);return t.identifierAttribute},void 0);t?(this.identifierMode=We.YES,this.mapIdentifierAttribute=t):this.identifierMode=We.NO}}initializeChildNodes(e,t={}){const n=e.type._subType,i={};return Object.keys(t).forEach(s=>{i[s]=n.instantiate(e,s,void 0,t[s])}),i}createNewInstance(e){return new Ze(e,this.name)}finalizeNewInstance(t,n){e._interceptReads(n,t.unbox);t.type.hookInitializers.forEach(e=>{const t=e(n);Object.keys(t).forEach(e=>{const i=t[e],s=M(n,e,i);Ee(n,e,s)})}),e.intercept(n,this.willChange),e.observe(n,this.didChange)}describe(){return this.name}getChildren(t){return e.values(t.storedValue)}getChildNode(e,t){const n=e.storedValue.get(""+t);if(!n)throw new we("Not a child "+t);return n}willChange(e){const t=ce(e.object),n=e.name;t.assertWritable({subpath:n});const i=t.type,s=i._subType;switch(e.type){case"update":{const{newValue:r}=e;if(r===e.object.get(n))return null;ee(s,r),e.newValue=s.reconcile(t.getChildNode(n),e.newValue,t,n),i.processIdentifier(n,e.newValue)}break;case"add":ee(s,e.newValue),e.newValue=s.instantiate(t,n,void 0,e.newValue),i.processIdentifier(n,e.newValue)}return e}processIdentifier(e,t){if(this.identifierMode===We.YES&&t instanceof S){const n=t.identifier;if(n!==e)throw new we(`A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '${n}', but expected: '${e}'`)}}getSnapshot(e){const t={};return e.getChildren().forEach(e=>{t[e.subpath]=e.snapshot}),t}processInitialSnapshot(e){const t={};return Object.keys(e).forEach(n=>{t[n]=e[n].getSnapshot()}),t}didChange(e){const t=ce(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:Fe(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:Fe(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":const n=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:Fe(e.name),oldValue:n},t)}}applyPatchLocally(e,t,n){const i=e.storedValue;switch(n.op){case"add":case"replace":i.set(t,n.value);break;case"remove":i.delete(t)}}applySnapshot(e,t){if(!Pe(t))return void ee(this,t);const n=e.storedValue,i=this.getChildType();Array.from(n.keys()).forEach(s=>{if(!Object.prototype.hasOwnProperty.call(t,s))return void n.delete(s);const r=e.getChildNode(s),o=t[s];r.snapshot!==o&&(T(i,r,o)?r.applySnapshot(o):n.set(s,o))});for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&!n.has(e)&&n.set(e,t[e])}getChildType(){return this._subType}isValidSnapshot(e,t){return Pe(e)?X(Object.keys(e).map(n=>this._subType.validate(e[n],q(t,n,this._subType)))):Q(t,e,"Value is not a plain object")}getDefaultSnapshot(){return ve}removeChild(e,t){e.storedValue.delete(t)}}Ye.prototype.applySnapshot=e.action(Ye.prototype.applySnapshot);class Je extends P{constructor(e,t,n=[]){super(e),this._subType=t,this.flags=A.Array,this.hookInitializers=[],this.hookInitializers=n}hooks(e){const t=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new Je(this.name,this._subType,t)}instantiate(e,t,n,i){return se(this,e,t,n,i)}initializeChildNodes(e,t=[]){const n=e.type._subType,i={};return t.forEach((t,s)=>{const r=""+s;i[r]=n.instantiate(e,r,void 0,t)}),i}createNewInstance(t){const n=Object.assign(Object.assign({},me),{name:this.name});return e.observable.array(ge(t),n)}finalizeNewInstance(t,n){e._getAdministration(n).dehancer=t.unbox;t.type.hookInitializers.forEach(e=>{const t=e(n);Object.keys(t).forEach(e=>{const i=t[e],s=M(n,e,i);Ee(n,e,s)})}),e.intercept(n,this.willChange),e.observe(n,this.didChange)}describe(){return this.name}getChildren(e){return e.storedValue.slice()}getChildNode(e,t){const n=Number(t);if(n<e.storedValue.length)return e.storedValue[n];throw new we("Not a child: "+t)}willChange(e){const t=ce(e.object);t.assertWritable({subpath:""+e.index});const n=t.type._subType,i=t.getChildren();switch(e.type){case"update":{if(e.newValue===e.object[e.index])return null;const s=Ke(t,n,[i[e.index]],[e.newValue],[e.index]);if(!s)return null;e.newValue=s[0]}break;case"splice":{const{index:s,removedCount:r,added:o}=e,a=Ke(t,n,i.slice(s,s+r),o,o.map((e,t)=>s+t));if(!a)return null;e.added=a;for(let e=s+r;e<i.length;e++)i[e].setParent(t,""+(e+o.length-r))}}return e}getSnapshot(e){return e.getChildren().map(e=>e.snapshot)}processInitialSnapshot(e){const t=[];return Object.keys(e).forEach(n=>{t.push(e[n].getSnapshot())}),t}didChange(e){const t=ce(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:""+e.index,value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"splice":if(e.removedCount&&e.addedCount===e.object.length)return void t.emitPatch({op:"replace",value:t.snapshot,oldValue:e.removed.map(e=>e.snapshot)},t);for(let n=e.removedCount-1;n>=0;n--)t.emitPatch({op:"remove",path:""+(e.index+n),oldValue:e.removed[n].snapshot},t);for(let n=0;n<e.addedCount;n++)t.emitPatch({op:"add",path:""+(e.index+n),value:e.added[n].snapshot,oldValue:void 0},t);return}}applyPatchLocally(e,t,n){const i=e.storedValue,s="-"===t?i.length:Number(t);switch(n.op){case"replace":i[s]=n.value;break;case"add":i.splice(s,0,n.value);break;case"remove":i.splice(s,1)}}applySnapshot(e,t){if(!Ae(t))return void ee(this,t);const n=e.storedValue,i=e.getChildren(),s=i.length,r=t.length,o=this.getChildType(),a=function(e,t,n){let i=0;for(;i<n&&e[i].snapshot===t[i];)i++;return i}(i,t,Math.min(s,r));if(a===s&&a===r)return;if(s!==r||e.hasPatchSubscribers()||function(e,t,n){let i;for(let s=n;s<e.length;s++){const r=e[s];if(r.snapshot!==t[s]&&qe(r,t[s])&&(i||(i=new Set(e.slice(n).map(e=>e.identifier))),i.has(Jt(t[s][r.identifierAttribute]))))return!0}return!1}(i,t,a))return void n.replace(t);if(function(e,t,n,i){for(let s=i;s<t.length;s++){const i=t[s];if(i.snapshot!==n[s]){if(!T(e,i,n[s]))return!1;if(!i.identifierAttribute||null===i.identifier)return!1}}return!0}(o,i,t,a))return void function(e,t,n){for(let i=n;i<e.length;i++){const n=e[i];n.snapshot!==t[i]&&n.applySnapshot(t[i])}}(i,t,a);const c=[];for(let e=a;e<s;e++)i[e].snapshot!==t[e]&&c.push(e);for(const e of c)n[e]=t[e]}getChildType(){return this._subType}isValidSnapshot(e,t){return Ae(e)?X(e.map((e,n)=>this._subType.validate(e,q(t,""+n,this._subType)))):Q(t,e,"Value is not an array")}getDefaultSnapshot(){return be}removeChild(e,t){e.storedValue.splice(Number(t),1)}}function qe(e,t){return e instanceof S&&null!==e.identifier&&!!e.identifierAttribute&&Pe(t)&&e.getReconciliationType()===e.type&&!e.type.isMatchingSnapshotId(e,t)}function Ke(e,t,n,i,s){let r=!0;for(let a=0;;a++){const c=a<=i.length-1,h=n[a];let l=c?i[a]:void 0;const u=""+s[a];if(((o=l)instanceof b||o instanceof S)&&(l=l.storedValue),!h&&!c)break;if(c)if(h)if(Xe(h,l))n[a]=Qe(t,e,u,l,h);else{let i=void 0;for(let e=a;e<n.length;e++)if(Xe(n[e],l)){i=n.splice(e,1)[0];break}r=!1;const s=Qe(t,e,u,l,i);n.splice(a,0,s)}else{if(ae(l)&&ce(l).parent===e)throw new we(`Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '${e.path}/${u}', but it lives already at '${ce(l).path}'`);r=!1;const i=Qe(t,e,u,l);n.splice(a,0,i)}else r=!1,n.splice(a,1),h instanceof S&&h.createObservableInstanceIfNeeded(),h.die(),a--}var o;return r?null:n}function Qe(e,t,n,i,s){ee(e,i);const r=function(){if(ae(i)){const e=ce(i);if(e.assertAlive(ve),null!==e.parent&&e.parent===t)return e.setParent(t,n),e}return s?e.reconcile(s,i,t,n):e.instantiate(t,n,void 0,i)}();return s&&s!==r&&(s instanceof S&&s.createObservableInstanceIfNeeded(),s.die()),r}function Xe(e,t){if(!e.isAlive)return!1;if(ae(t)){const n=ce(t);return n.isAlive&&n===e}if(e.snapshot===t)return!0;if(!(e instanceof S))return!1;if(qe(e,t))return!1;const n=e.getReconciliationType();return null!==e.identifier&&e.identifierAttribute&&Pe(t)&&n.is(t)&&n.isMatchingSnapshotId(e,t)}Je.prototype.applySnapshot=e.action(Je.prototype.applySnapshot),"function"==typeof SuppressedError&&SuppressedError;const et=new WeakMap;let tt=!1;function nt(e,t,n){if(!tt)return;const i=function(e){let t=et.get(e);return t||(t=new Map,et.set(e,t)),t}(e),s=i.get(t);if(void 0!==s&&s!==n)throw new we(`'${t}' already exists as ${s} and cannot be declared as ${n}`);i.set(t,n)}const it=e=>(et.delete(e),e);function st(){return ce(this).toString()}const rt={name:"AnonymousModel",properties:{},initializers:be};function ot(e){const t=Object.keys(e),n=new Set;return t.forEach(e=>{if(n.has(e))throw new we(e+" is declared twice in the model. Model should not contain the same keys");n.add(e)}),t.reduce((t,n)=>{if(n in s)throw new we(`Hook '${n}' was defined as property. Hooks should be defined as part of the actions`);const i=Object.getOwnPropertyDescriptor(e,n);if("get"in i)throw new we("Getters are not supported as properties. Please use views instead");const r=i.value;if(null==r)throw new we("The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?");if(Te(r))t[n]=Nt(function(e){switch(typeof e){case"string":return lt;case"number":return ut;case"boolean":return bt;case"bigint":return yt;case"object":if(e instanceof Date)return _t}throw new we("Cannot determine primitive type from value "+e)}(r),r);else if(r instanceof Ye)t[n]=Nt(r,{});else if(r instanceof Je)t[n]=Nt(r,[]);else if(!C(r))throw new we(`Invalid type definition for property '${n}', cannot infer a type from a value like '${r}' (${typeof r})`);return t},Object.assign({},e))}class at extends P{constructor(e){super(e.name||rt.name),this.flags=A.Object,this.named=e=>this.cloneAndEnhance({name:e}),this.props=e=>this.cloneAndEnhance({properties:e}),this.preProcessSnapshot=e=>{const t=this.preProcessor;return t?this.cloneAndEnhance({preProcessor:n=>t(e(n))}):this.cloneAndEnhance({preProcessor:e})},this.postProcessSnapshot=e=>{const t=this.postProcessor;return t?this.cloneAndEnhance({postProcessor:n=>e(t(n))}):this.cloneAndEnhance({postProcessor:e})},Object.assign(this,rt,e),this.properties=ot(this.properties),this.properties,this.propertyNames=Object.keys(this.properties),this.identifierAttribute=this._getIdentifierAttribute()}_getIdentifierAttribute(){let e=void 0;return this.forAllProps((t,n)=>{if(n.flags&A.Identifier){if(e)throw new we(`Cannot define property '${t}' as object identifier, property '${e}' is already defined as identifier property`);e=t}}),e}cloneAndEnhance(e){return new at({name:e.name||this.name,properties:Object.assign({},this.properties,e.properties),initializers:this.initializers.concat(e.initializers||[]),preProcessor:e.preProcessor||this.preProcessor,postProcessor:e.postProcessor||this.postProcessor})}actions(e){return this.cloneAndEnhance({initializers:[t=>(this.instantiateActions(t,e(t)),t)]})}instantiateActions(e,t){if(!Pe(t))throw new we("actions initializer should return a plain object containing actions");Object.getOwnPropertyNames(t).forEach(n=>{if(n in this.properties)throw new we(`'${n}' is a property and cannot be declared as an action`);if(nt(e,n,"an action"),"preProcessSnapshot"===n)throw new we("Cannot define action 'preProcessSnapshot', it should be defined using 'type.preProcessSnapshot(fn)' instead");if("postProcessSnapshot"===n)throw new we("Cannot define action 'postProcessSnapshot', it should be defined using 'type.postProcessSnapshot(fn)' instead");let i=t[n],r=e[n];if(n in s&&r){let e=i;i=function(){r.apply(null,arguments),e.apply(null,arguments)}}const o=i.$mst_middleware;let a=i.bind(t);a._isFlowAction=i._isFlowAction||!1,a.$mst_middleware=o;const c=M(e,n,a);t[n]=c,Ee(e,n,c)})}volatile(e){if("function"!=typeof e)throw new we(`You passed an ${typeof e} to volatile state as an argument, when function is expected`);return this.cloneAndEnhance({initializers:[t=>(this.instantiateVolatileState(t,e(t)),t)]})}instantiateVolatileState(t,n){if(!Pe(n))throw new we("volatile state initializer should return a plain object containing state");Object.getOwnPropertyNames(n).forEach(i=>{if(i in this.properties)throw new we(`'${i}' is a property and cannot be declared as volatile state`);nt(t,i,"volatile state"),e.set(t,i,n[i])})}extend(e){return this.cloneAndEnhance({initializers:[t=>{const n=e(t),{actions:i,views:s,state:r}=n,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}(n,["actions","views","state"]);for(let e in o)throw new we(`The \`extend\` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '${e}'`);return r&&this.instantiateVolatileState(t,r),s&&this.instantiateViews(t,s),i&&this.instantiateActions(t,i),t}]})}views(e){return this.cloneAndEnhance({initializers:[t=>(this.instantiateViews(t,e(t)),t)]})}instantiateViews(t,n){if(!Pe(n))throw new we("views initializer should return a plain object containing views");Object.getOwnPropertyNames(n).forEach(i=>{if(i in this.properties)throw new we(`'${i}' is a property and cannot be declared as a view`);nt(t,i,"a view");const s=Object.getOwnPropertyDescriptor(n,i);if("get"in s)e.defineProperty(t,i,s),e.makeObservable(t,{[i]:e.computed});else{if("function"!=typeof s.value)throw new we("A view member should either be a function or getter based property");Ee(t,i,s.value)}})}instantiate(e,t,n,i){return se(this,e,t,n,ae(i)?i:this.applySnapshotPreProcessor(i))}initializeChildNodes(e,t={}){const n=e.type,i={};return n.forAllProps((n,s)=>{i[n]=s.instantiate(e,n,void 0,t[n])}),i}createNewInstance(t){const n=Object.assign(Object.assign({},me),{name:this.name});return e.observable.object(t,ve,n)}finalizeNewInstance(t,n){Ee(n,"toString",st),this.forAllProps(i=>{e._interceptReads(n,i,t.unbox)}),this.initializers.reduce((e,t)=>t(e),n),et.delete(n),e.intercept(n,this.willChange),e.observe(n,this.didChange)}willChange(e){const t=e,n=ce(t.object),i=t.name;n.assertWritable({subpath:i});const s=n.type.properties[i];return s&&(ee(s,t.newValue),t.newValue=s.reconcile(n.getChildNode(i),t.newValue,n,i)),t}didChange(e){const t=e,n=ce(t.object);if(!n.type.properties[t.name])return;const i=t.oldValue?t.oldValue.snapshot:void 0;n.emitPatch({op:"replace",path:Fe(t.name),value:t.newValue.snapshot,oldValue:i},n)}getChildren(e){const t=[];return this.forAllProps(n=>{t.push(this.getChildNode(e,n))}),t}getChildNode(t,n){var i;if(!(n in this.properties))throw new we("Not a value property: "+n);const s=e._getAdministration(t.storedValue,n),r=null===(i=s.raw)||void 0===i?void 0:i.call(s);if(!r)throw new we("Node not available for property "+n);return r}getSnapshot(t,n=!0){const i={};return this.forAllProps((n,s)=>{var r,o;const a=e.getAtom(t.storedValue,n);a.reportObserved();const c=null===(o=(r=a).raw)||void 0===o?void 0:o.call(r);if(!c)throw new we("Node not available for property "+n);i[n]=c.snapshot}),n?this.applySnapshotPostProcessor(i):i}processInitialSnapshot(e){const t={};return Object.keys(e).forEach(n=>{t[n]=e[n].getSnapshot()}),this.applySnapshotPostProcessor(t)}applyPatchLocally(e,t,n){if("replace"!==n.op&&"add"!==n.op)throw new we("object does not support operation "+n.op);e.storedValue[t]=n.value}applySnapshot(e,t){const n=this.applySnapshotPreProcessor(t),i=!Pe(n);(Pe(t)&&!i||(ee(this,t),!i))&&this.forAllProps((t,i)=>{const s=e.getChildNode(t),r=n[t];s.snapshot!==r&&(T(i,s,r)?s.applySnapshot(r):e.storedValue[t]=r)})}applySnapshotPreProcessor(e){const t=this.preProcessor;return t?t.call(null,e):e}applySnapshotPostProcessor(e){const t=this.postProcessor;return t?t.call(null,e):e}getChildType(e){return this.properties[e]}isValidSnapshot(e,t){let n=this.applySnapshotPreProcessor(e);return Pe(n)?X(this.propertyNames.map(e=>this.properties[e].validate(n[e],q(t,e,this.properties[e])))):Q(t,n,"Value is not a plain object")}forAllProps(e){this.propertyNames.forEach(t=>e(t,this.properties[t]))}describe(){return"{ "+this.propertyNames.map(e=>e+": "+this.properties[e].describe()).join("; ")+" }"}getDefaultSnapshot(){return ve}removeChild(e,t){e.storedValue[t]=void 0}}function ct(e){return C(e)&&(e.flags&A.Object)>0}at.prototype.applySnapshot=e.action(at.prototype.applySnapshot);class ht extends x{constructor(e,t,n,i=_e){super(e),this.flags=t,this.checker=n,this.initializer=i,this.flags=t}describe(){return this.name}instantiate(e,t,n,i){return re(this,e,t,n,i)}createNewInstance(e){return this.initializer(e)}isValidSnapshot(e,t){if(Te(e)&&this.checker(e))return K();return Q(t,e,"Value is not a "+("Date"===this.name?"Date or a unix milliseconds timestamp":this.name))}}const lt=new ht("string",A.String,e=>"string"==typeof e),ut=new ht("number",A.Number,e=>"number"==typeof e),pt=new ht("integer",A.Integer,e=>Se(e)),dt=new ht("float",A.Float,e=>{return t=e,Number(t)===t&&t%1!=0;var t}),ft=new ht("finite",A.Finite,e=>{return t=e,Number.isFinite(t);var t}),gt=new ht("bigint",A.BigInt,e=>{if("bigint"==typeof e)return!0;if("string"==typeof e||"number"==typeof e)try{return BigInt(e),!0}catch(e){}return!1},e=>"bigint"==typeof e?e:BigInt(e));gt.getSnapshot=function(e){return String(e.storedValue)};const yt=gt,bt=new ht("boolean",A.Boolean,e=>"boolean"==typeof e),vt=new ht("null",A.Null,e=>null===e),mt=new ht("undefined",A.Undefined,e=>void 0===e),wt=new ht("Date",A.Date,e=>"number"==typeof e||e instanceof Date,e=>e instanceof Date?e:new Date(e));wt.getSnapshot=function(e){return e.storedValue.getTime()};const _t=wt;function St(e){return C(e)&&(e.flags&(A.String|A.Number|A.Integer|A.Boolean|A.Date|A.BigInt))>0}class At extends x{constructor(e){super(JSON.stringify(e)),this.flags=A.Literal,this.value=e}instantiate(e,t,n,i){return re(this,e,t,n,i)}describe(){return JSON.stringify(this.value)}isValidSnapshot(e,t){return Te(e)&&e===this.value?K():Q(t,e,"Value is not a literal "+JSON.stringify(this.value))}}function It(e){return new At(e)}class Pt extends I{get flags(){return this._subtype.flags|A.Refinement}constructor(e,t,n,i){super(e),this._subtype=t,this._predicate=n,this._message=i}describe(){return this.name}instantiate(e,t,n,i){return this._subtype.instantiate(e,t,n,i)}isAssignableFrom(e){return this._subtype.isAssignableFrom(e)}isValidSnapshot(e,t){const n=this._subtype.validate(e,t);if(n.length>0)return n;const i=ae(e)?ce(e).snapshot:e;return this._predicate(i)?K():Q(t,e,this._message(e))}reconcile(e,t,n,i){return this._subtype.reconcile(e,t,n,i)}getSubTypes(){return this._subtype}}class xt extends I{get flags(){let e=A.Union;return this._types.forEach(t=>{e|=t.flags}),e}constructor(e,t,n){super(e),this._types=t,this._eager=!0,n=Object.assign({eager:!0,dispatcher:void 0},n),this._dispatcher=n.dispatcher,n.eager||(this._eager=!1)}isAssignableFrom(e){return this._types.some(t=>t.isAssignableFrom(e))}describe(){return"("+this._types.map(e=>e.describe()).join(" | ")+")"}instantiate(e,t,n,i){const s=this.determineType(i,void 0);if(!s)throw new we("No matching type for union "+this.describe());return s.instantiate(e,t,n,i)}reconcile(e,t,n,i){const s=this.determineType(t,e.getReconciliationType());if(!s)throw new we("No matching type for union "+this.describe());return s.reconcile(e,t,n,i)}determineType(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter(e=>e!==t).find(t=>t.is(e)):this._types.find(t=>t.is(e))}isValidSnapshot(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);const n=[];let i=0;for(let s=0;s<this._types.length;s++){const r=this._types[s].validate(e,t);if(0===r.length){if(this._eager)return K();i++}else n.push(r)}return 1===i?K():Q(t,e,"No type is applicable for the union").concat(X(n))}getSubTypes(){return this._types}}function Tt(e,...t){const n=C(e)?void 0:e,i=C(e)?[e,...t]:t,s="("+i.map(e=>e.name).join(" | ")+")";return new xt(s,i,n)}function Ct(e){return C(e)&&(e.flags&A.Union)>0}class Et extends I{get flags(){return this._subtype.flags|A.Optional}constructor(e,t,n){super(e.name),this._subtype=e,this._defaultValue=t,this.optionalValues=n}describe(){return this._subtype.describe()+"?"}instantiate(e,t,n,i){if(this.optionalValues.indexOf(i)>=0){const i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,n,i)}return this._subtype.instantiate(e,t,n,i)}reconcile(e,t,n,i){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),n,i)}getDefaultInstanceOrSnapshot(){const e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&ee(this,e),e}isValidSnapshot(e,t){return this.optionalValues.indexOf(e)>=0?K():this._subtype.validate(e,t)}isAssignableFrom(e){return this._subtype.isAssignableFrom(e)}getSubTypes(){return this._subtype}}function Nt(e,t,n){return function(e,t){if("function"!=typeof t&&ae(t))throw new we("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new Et(e,t,n||Vt)}const Vt=[void 0];const Ot=Nt(mt,void 0),Dt=Nt(vt,null);function $t(e){return Tt(e,Ot)}class jt extends I{get flags(){return(this._subType?this._subType.flags:0)|A.Late}getSubType(e){if(!this._subType){let t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw new we("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}constructor(e,t){super(e),this._definition=t}instantiate(e,t,n,i){return this.getSubType(!0).instantiate(e,t,n,i)}reconcile(e,t,n,i){return this.getSubType(!0).reconcile(e,t,n,i)}describe(){const e=this.getSubType(!1);return e?e.name:"<uknown late type>"}isValidSnapshot(e,t){const n=this.getSubType(!1);return n?n.validate(e,t):K()}isAssignableFrom(e){const t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}getSubTypes(){const e=this.getSubType(!1);return e||"cannotDetermine"}}class kt extends x{constructor(t,n){super(t),this.options=n,this.flags=A.Lazy,this.loadedType=null,this.pendingNodeList=e.observable.array(),e.when(()=>this.pendingNodeList.length>0&&this.pendingNodeList.some(e=>e.isAlive&&this.options.shouldLoadPredicate(e.parent?e.parent.value:null)),()=>{this.options.loadType().then(e.action(e=>{this.loadedType=e,this.pendingNodeList.forEach(e=>{e.parent&&this.loadedType&&e.parent.applyPatches([{op:"replace",path:"/"+e.subpath,value:e.snapshot}])})}))})}describe(){return`<lazy ${this.name}>`}instantiate(t,n,i,s){if(this.loadedType)return this.loadedType.instantiate(t,n,i,s);const r=re(this,t,n,i,s);return this.pendingNodeList.push(r),e.when(()=>!r.isAlive,()=>this.pendingNodeList.splice(this.pendingNodeList.indexOf(r),1)),r}isValidSnapshot(e,t){return this.loadedType?this.loadedType.validate(e,t):Ce(e)?K():Q(t,e,"Value is not serializable and cannot be lazy")}reconcile(e,t,n,i){return this.loadedType?(e.die(),this.loadedType.instantiate(n,i,n.environment,t)):super.reconcile(e,t,n,i)}}class Rt extends x{constructor(e){super(e?`frozen(${e.name})`:"frozen"),this.subType=e,this.flags=A.Frozen}describe(){return"<any immutable value>"}instantiate(e,t,n,i){return re(this,e,t,n,i)}isValidSnapshot(e,t){return Ce(e)?this.subType?this.subType.validate(e,t):K():Q(t,e,"Value is not serializable and cannot be frozen")}}const zt=new Rt;class Ft{constructor(e,t){if(this.targetType=t,this.resolvedReference=void 0,qt(e))this.identifier=e;else{if(!ae(e))throw new we(`Can only store references to tree nodes or identifiers, got: '${e}'`);{const t=ce(e);if(!t.identifierAttribute)throw new we("Can only store references with a defined identifier attribute.");const n=t.unnormalizedIdentifier;if(null==n)throw new we("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}}updateResolvedReference(e){const t=Jt(this.identifier),n=e.root,i=n.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==i){const{targetType:s}=this,r=n.identifierCache.resolve(s,t);if(!r)throw new Mt(`[mobx-state-tree] Failed to resolve reference '${this.identifier}' to type '${this.targetType.name}' (from node: ${e.path})`);this.resolvedReference={node:r,lastCacheModification:i}}}get resolvedValue(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value}}class Mt extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Mt.prototype)}}class Lt extends x{constructor(e,t){super(`reference(${e.name})`),this.targetType=e,this.onInvalidated=t,this.flags=A.Reference}describe(){return this.name}isAssignableFrom(e){return this.targetType.isAssignableFrom(e)}isValidSnapshot(e,t){return qt(e)?K():Q(t,e,"Value is not a valid identifier, which is a string, number or a bigint")}fireInvalidated(e,t,n,i){const s=t.parent;if(!s||!s.isAlive)return;const r=s.storedValue;r&&this.onInvalidated({cause:e,parent:r,invalidTarget:i?i.storedValue:void 0,invalidId:n,replaceRef(e){a(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef(){ct(s.type)?this.replaceRef(void 0):a(t.root.storedValue,{op:"remove",path:t.path})}})}addTargetNodeWatcher(e,t){const n=this.getValue(e);if(!n)return;const i=ce(n),r=(n,r)=>{const o=function(e){switch(e){case s.beforeDestroy:return"destroy";case s.beforeDetach:return"detach";default:return}}(r);o&&this.fireInvalidated(o,e,t,i)},o=i.registerHook(s.beforeDetach,r),a=i.registerHook(s.beforeDestroy,r);return()=>{o(),a()}}watchTargetNodeForInvalidations(e,t,n){if(!this.onInvalidated)return;let i;e.registerHook(s.beforeDestroy,()=>{i&&i()});const r=()=>{const n=()=>{e.isAlive&&this.getSnapshot(e)===t&&o(!1)};k()?e.root.enqueueEndOfAction(n):je(n)},o=s=>{i&&i();const o=e.parent,a=o&&o.storedValue;if(o&&o.isAlive&&a){let o;o=n?!!n.get(t,a):e.root.identifierCache.has(this.targetType,Jt(t)),o?i=this.addTargetNodeWatcher(e,t):s?r():this.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===oe.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(s.afterCreationFinalization,()=>{e.parent&&e.parent.createObservableInstanceIfNeeded()}),e.registerHook(s.afterAttach,()=>{o(!1)}))}}class Ht extends Lt{constructor(e,t){super(e,t)}getValue(e){if(!e.isAlive)return;return e.storedValue.resolvedValue}getSnapshot(e){return e.storedValue.identifier}instantiate(e,t,n,i){const s=ae(i)?p(i):i,r=new Ft(i,this.targetType),o=re(this,e,t,n,r);return r.node=o,this.watchTargetNodeForInvalidations(o,s,void 0),o}reconcile(e,t,n,i){if(!e.isDetaching&&e.type===this){const s=ae(t),r=e.storedValue;if(!s&&r.identifier===t||s&&r.resolvedValue===t)return e.setParent(n,i),e}const s=this.instantiate(n,i,void 0,t);return e.die(),s}}class Ut extends Lt{constructor(e,t,n){super(e,n),this.options=t}getValue(e){if(!e.isAlive)return;return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}getSnapshot(e){return e.storedValue}instantiate(e,t,n,i){const s=ae(i)?this.options.set(i,e?e.storedValue:null):i,r=re(this,e,t,n,s);return this.watchTargetNodeForInvalidations(r,s,this.options),r}reconcile(e,t,n,i){const s=ae(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===s)return e.setParent(n,i),e;const r=this.instantiate(n,i,void 0,s);return e.die(),r}}function Bt(e,t){const n=t||void 0,i=t?t.onInvalidated:void 0;return n&&(n.get||n.set)?new Ut(e,{get:n.get,set:n.set},i):new Ht(e,i)}class Gt extends x{constructor(e,t){super(e),this.validType=t,this.flags=A.Identifier}instantiate(e,t,n,i){if(!(e&&e.type instanceof at))throw new we("Identifier types can only be instantiated as direct child of a model type");return re(this,e,t,n,i)}reconcile(e,t,n,i){if(e.storedValue!==t)throw new we(`Tried to change identifier from '${e.storedValue}' to '${t}'. Changing identifiers is not allowed.`);return e.setParent(n,i),e}isValidSnapshot(e,t){return typeof e!==this.validType?Q(t,e,`Value is not a valid ${this.describe()}, expected a ${this.validType}`):K()}}const Wt=new class extends Gt{constructor(){super("identifier","string"),this.flags=A.Identifier}describe(){return"identifier"}},Zt=new class extends Gt{constructor(){super("identifierNumber","number")}getSnapshot(e){return e.storedValue}describe(){return"identifierNumber"}};const Yt=new class extends x{constructor(){super("identifierBigint"),this.flags=A.Identifier}createNewInstance(e){return"bigint"==typeof e?e:BigInt(e)}instantiate(e,t,n,i){if(!(e&&e.type instanceof at))throw new we("Identifier types can only be instantiated as direct child of a model type");return re(this,e,t,n,i)}reconcile(e,t,n,i){const s=e.storedValue,r="bigint"==typeof t?t:BigInt(t);if(s!==r)throw new we(`Tried to change identifier from '${s}' to '${r}'. Changing identifiers is not allowed.`);return e.setParent(n,i),e}isValidSnapshot(e,t){if("bigint"==typeof e)return K();if("string"==typeof e||"number"==typeof e)try{return BigInt(e),K()}catch(n){const i=n instanceof Error?n.message:String(n);return Q(t,e,`Value is not a valid ${this.describe()}: ${i}`)}return Q(t,e,`Value is not a valid ${this.describe()}, expected a bigint, a string or a number`)}getSnapshot(e){return String(e.storedValue)}describe(){return"identifierBigint"}};function Jt(e){return""+e}function qt(e){return"string"==typeof e||"number"==typeof e||"bigint"==typeof e}class Kt extends x{constructor(e){super(e.name),this.options=e,this.flags=A.Custom}describe(){return this.name}isValidSnapshot(e,t){if(this.options.isTargetType(e))return K();const n=this.options.getValidationMessage(e);return n?Q(t,e,`Invalid value for type '${this.name}': ${n}`):K()}getSnapshot(e){return this.options.toSnapshot(e.storedValue)}instantiate(e,t,n,i){return re(this,e,t,n,this.options.isTargetType(i)?i:this.options.fromSnapshot(i,e&&e.root.environment))}reconcile(e,t,n,i){const s=!this.options.isTargetType(t);if(!e.isDetaching){if(e.type===this&&(s?t===e.snapshot:t===e.storedValue))return e.setParent(n,i),e}const r=s?this.options.fromSnapshot(t,n.root.environment):t,o=this.instantiate(n,i,void 0,r);return e.die(),o}}const Qt={enumeration:function(e,t){const n=Tt(...("string"==typeof e?t:e).map(e=>It(e)));return"string"==typeof e&&(n.name=e),n},model:function(...e){const t="string"==typeof e[0]?e.shift():"AnonymousModel",n=e.shift()||{};return new at({name:t,properties:n})},compose:function(...e){const t="string"==typeof e[0],n=t?e[0]:"AnonymousModel";return t&&e.shift(),e.reduce((e,t)=>e.cloneAndEnhance({name:e.name+"_"+t.name,properties:t.properties,initializers:[it,...t.initializers],preProcessor:n=>t.applySnapshotPreProcessor(e.applySnapshotPreProcessor(n)),postProcessor:n=>t.applySnapshotPostProcessor(e.applySnapshotPostProcessor(n))})).named(n)},custom:function(e){return new Kt(e)},reference:Bt,safeReference:function(e,t){const n=Bt(e,Object.assign(Object.assign({},t),{onInvalidated(e){t&&t.onInvalidated&&t.onInvalidated(e),e.removeRef()}}));return t&&!1===t.acceptsUndefined?n:$t(n)},union:Tt,optional:Nt,literal:It,maybe:$t,maybeNull:function(e){return Tt(e,Dt)},refinement:function(...e){const t="string"==typeof e[0]?e.shift():C(e[0])?e[0].name:null,n=e[0],i=e[1],s=e[2]?e[2]:e=>"Value does not respect the refinement predicate";return new Pt(t,n,i,s)},string:lt,boolean:bt,number:ut,integer:pt,float:dt,finite:ft,bigint:yt,Date:_t,map:function(e){return new Ye(`Map<string, ${e.name}>`,e)},array:function(e){return new Je(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?zt:C(e)?new Rt(e):Nt(zt,e)},identifier:Wt,identifierNumber:Zt,identifierBigint:Yt,late:function(e,t){const n="string"==typeof e?e:`late(${e.toString()})`;return new jt(n,"string"==typeof e?t:e)},lazy:function(e,t){return new kt(e,t)},undefined:mt,null:vt,snapshotProcessor:function(e,t,n){return new Be(e,t,n)}};exports.addDisposer=function(e,t){return ce(e).addDisposer(t),t},exports.addMiddleware=L,exports.applyAction=O,exports.applyPatch=a,exports.applySnapshot=c,exports.cast=function(e){return e},exports.castFlowReturn=function(e){return e},exports.castToReferenceSnapshot=function(e){return e},exports.castToSnapshot=function(e){return e},exports.clone=function(e,t=!0){const n=ce(e);return n.type.create(n.snapshot,!0===t?n.root.environment:!1===t?void 0:t)},exports.createActionTrackingMiddleware=function(e){return function(t,n,i){switch(t.type){case"action":if(e.filter&&!0!==e.filter(t))return n(t);{const i=e.onStart(t);e.onResume(t,i),E.set(t.id,{call:t,context:i,async:!1});try{const s=n(t);return e.onSuspend(t,i),!1===E.get(t.id).async&&(E.delete(t.id),e.onSuccess(t,i,s)),s}catch(n){throw E.delete(t.id),e.onFail(t,i,n),n}}case"flow_spawn":return E.get(t.rootId).async=!0,n(t);case"flow_resume":case"flow_resume_error":{const i=E.get(t.rootId);e.onResume(t,i.context);try{return n(t)}finally{e.onSuspend(t,i.context)}}case"flow_throw":{const i=E.get(t.rootId);return E.delete(t.rootId),e.onFail(t,i.context,t.args[0]),n(t)}case"flow_return":{const i=E.get(t.rootId);return E.delete(t.rootId),e.onSuccess(t,i.context,t.args[0]),n(t)}}}},exports.createActionTrackingMiddleware2=function(e){const t=new Map;return function(n,i){const s=n.parentActionEvent?t.get(n.parentActionEvent.id):void 0;if("action"===n.type){const r=Object.assign(Object.assign({},n),{env:s&&s.call.env,parentCall:s&&s.call}),o=!e.filter||e.filter(r),a=new N(o?e:void 0,r);let c;t.set(n.id,a);try{c=i(n)}catch(e){throw t.delete(n.id),a.finish(e),e}return a.hasFlowsPending||(t.delete(n.id),a.finish()),c}if(!s)return i(n);switch(n.type){case"flow_spawn":return s.incFlowsPending(),i(n);case"flow_resume":case"flow_resume_error":return i(n);case"flow_throw":{const e=n.args[0];try{return i(n)}finally{s.decFlowsPending(),s.hasFlowsPending||(t.delete(n.parentActionEvent.id),s.finish(e))}}case"flow_return":try{return i(n)}finally{s.decFlowsPending(),s.hasFlowsPending||(t.delete(n.parentActionEvent.id),s.finish())}}}},exports.decorate=function(e,t,n=!0){const i={handler:e,includeHooks:n};return t.$mst_middleware=t.$mst_middleware||[],t.$mst_middleware.push(i),t},exports.destroy=function(e){const t=ce(e);t.isRoot?t.die():t.parent.removeChild(t.subpath)},exports.detach=function(e){return ce(e).detach(),e},exports.escapeJsonPath=Fe,exports.flow=ke,exports.getChildType=function(e,t){return ce(e).getChildType(t)},exports.getEnv=function(e){const t=ce(e),n=t.root.environment;if(!n)throw new we(`Failed to find the environment of ${t} ${t.path}`);return n},exports.getErrorFormatting=W,exports.getIdentifier=p,exports.getLivelinessChecking=i,exports.getMemberRedeclarationChecking=function(){return tt},exports.getMembers=function(t){const n=ce(t).type,i=Object.assign(Object.assign({},g(n)),{actions:[],volatile:[],views:[],flowActions:[]});return Object.getOwnPropertyNames(t).forEach(n=>{if(n in i.properties)return;const s=Object.getOwnPropertyDescriptor(t,n);s.get?e.isComputedProp(t,n)?i.views.push(n):i.volatile.push(n):(!0===s.value._isFlowAction&&i.flowActions.push(n),!0===s.value._isMSTAction?i.actions.push(n):e.isObservableProp(t,n)?i.volatile.push(n):i.views.push(n))}),i},exports.getNodeId=function(e){return ce(e).nodeId},exports.getParent=function(e,t=1){let n=t,i=ce(e).parent;for(;i;){if(0==--n)return i.storedValue;i=i.parent}throw new we(`Failed to find the parent of ${ce(e)} at depth ${t}`)},exports.getParentOfType=function(e,t){let n=ce(e).parent;for(;n;){if(t.is(n.storedValue))return n.storedValue;n=n.parent}throw new we(`Failed to find the parent of ${ce(e)} of a given type`)},exports.getPath=u,exports.getPathParts=function(e){return He(ce(e).path)},exports.getPropertyMembers=g,exports.getRelativePath=function(e,t){return pe(ce(e),ce(t))},exports.getRoot=l,exports.getRunningActionContext=U,exports.getSnapshot=h,exports.getType=r,exports.hasEnv=function(e){return!!ce(e).root.environment},exports.hasParent=function(e,t=1){let n=ce(e).parent;for(;n;){if(0==--t)return!0;n=n.parent}return!1},exports.hasParentOfType=function(e,t){let n=ce(e).parent;for(;n;){if(t.is(n.storedValue))return!0;n=n.parent}return!1},exports.isActionContextChildOf=function(e,t){return B(e,t,!1)},exports.isActionContextThisOrChildOf=function(e,t){return B(e,t,!0)},exports.isAlive=f,exports.isArrayType=function(e){return C(e)&&(e.flags&A.Array)>0},exports.isFrozenType=function(e){return C(e)&&(e.flags&A.Frozen)>0},exports.isIdentifierType=function(e){return C(e)&&(e.flags&A.Identifier)>0},exports.isLateType=function(e){return C(e)&&(e.flags&A.Late)>0},exports.isLiteralType=function(e){return C(e)&&(e.flags&A.Literal)>0},exports.isMapType=function(e){return C(e)&&(e.flags&A.Map)>0},exports.isModelType=ct,exports.isOptionalType=function(e){return C(e)&&(e.flags&A.Optional)>0},exports.isPrimitiveType=St,exports.isProtected=function(e){return ce(e).isProtected},exports.isReferenceType=function(e){return C(e)&&(e.flags&A.Reference)>0},exports.isRefinementType=function(e){return C(e)&&(e.flags&A.Refinement)>0},exports.isRoot=function(e){return ce(e).isRoot},exports.isStateTreeNode=ae,exports.isType=C,exports.isUnionType=Ct,exports.isValidReference=function(e,t=!0){try{const n=e();if(null==n)return!1;if(ae(n))return!t||f(n);throw new we("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof Mt)return!1;throw e}},exports.joinJsonPath=Le,exports.onAction=D,exports.onPatch=o,exports.onSnapshot=function(e,t){return ce(e).onSnapshot(t)},exports.process=function(e){return $e(),ke(e)},exports.protect=function(e){const t=ce(e);if(!t.isRoot)throw new we("`protect` can only be invoked on root nodes");t.isProtectionEnabled=!0},exports.recordActions=function(e,t){const n=[],i=e=>{(!t||t(e,U()))&&n.push(e)};let s;const r={actions:n,get recording(){return!!s},stop(){s&&(s(),s=void 0)},resume(){s||(s=D(e,i))},replay(e){O(e,n)}};return r.resume(),r},exports.recordPatches=function(e,t){const n={patches:[],inversePatches:[]},i={};let s;const r={get recording(){return!!s},get patches(){return i.patches||(i.patches=n.patches.slice()),i.patches},get reversedInversePatches(){return i.reversedInversePatches||(i.reversedInversePatches=n.inversePatches.slice().reverse()),i.reversedInversePatches},get inversePatches(){return i.inversePatches||(i.inversePatches=n.inversePatches.slice()),i.inversePatches},stop(){s&&(s(),s=void 0)},resume(){s||(s=o(e,(e,s)=>{t&&!t(e,s,U())||(n.patches.push(e),n.inversePatches.push(s),i.patches=void 0,i.inversePatches=void 0,i.reversedInversePatches=void 0)}))},replay(t){a(t||e,n.patches)},undo(t){a(t||e,n.inversePatches.slice().reverse())}};return r.resume(),r},exports.resolveIdentifier=function(e,t,n){const i=ce(t).root.identifierCache.resolve(e,Jt(n));return null==i?void 0:i.value},exports.resolvePath=function(e,t){const n=de(ce(e),t);return n?n.value:void 0},exports.setErrorFormatting=function(e){G=Object.assign(Object.assign({},G),e)},exports.setLivelinessChecking=n,exports.setLivelynessChecking=function(e){n(e)},exports.setMemberRedeclarationChecking=function(e){tt=e},exports.splitJsonPath=He,exports.t=Qt,exports.toGenerator=function*(e){return yield e},exports.toGeneratorFunction=function(e){return function*(...t){return yield e(...t)}},exports.tryReference=function(e,t=!0){try{const n=e();if(null==n)return;if(ae(n))return t?f(n)?n:void 0:n;throw new we("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof Mt)return;throw e}},exports.tryResolve=d,exports.typecheck=te,exports.types=Qt,exports.unescapeJsonPath=Me,exports.unprotect=function(e){const t=ce(e);if(!t.isRoot)throw new we("`unprotect` can only be invoked on root nodes");t.isProtectionEnabled=!1},exports.walk=function e(t,n){const i=ce(t);i.getChildren().forEach(t=>{const i=t instanceof S?t.value:t.storedValue;ae(i)&&e(i,n)}),n(i.storedValue)};