mobx-state-tree 3.12.2 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +103 -23
  2. package/dist/core/action.d.ts +50 -48
  3. package/dist/core/actionContext.d.ts +27 -0
  4. package/dist/core/flow.d.ts +14 -30
  5. package/dist/core/json-patch.d.ts +36 -36
  6. package/dist/core/mst-operations.d.ts +451 -444
  7. package/dist/core/node/BaseNode.d.ts +1 -1
  8. package/dist/core/node/Hook.d.ts +17 -1
  9. package/dist/core/node/create-node.d.ts +1 -1
  10. package/dist/core/node/identifier-cache.d.ts +1 -1
  11. package/dist/core/node/livelinessChecking.d.ts +37 -37
  12. package/dist/core/node/node-utils.d.ts +28 -28
  13. package/dist/core/node/object-node.d.ts +1 -1
  14. package/dist/core/node/scalar-node.d.ts +1 -1
  15. package/dist/core/process.d.ts +45 -45
  16. package/dist/core/type/type-checker.d.ts +30 -30
  17. package/dist/core/type/type.d.ts +162 -177
  18. package/dist/index.d.ts +3 -3
  19. package/dist/internal.d.ts +37 -35
  20. package/dist/middlewares/create-action-tracking-middleware.d.ts +24 -22
  21. package/dist/middlewares/createActionTrackingMiddleware2.d.ts +34 -0
  22. package/dist/middlewares/on-action.d.ts +87 -79
  23. package/dist/mobx-state-tree.js +6285 -5985
  24. package/dist/mobx-state-tree.min.js +16 -1
  25. package/dist/mobx-state-tree.module.js +6234 -5938
  26. package/dist/mobx-state-tree.umd.js +6263 -5985
  27. package/dist/mobx-state-tree.umd.min.js +16 -1
  28. package/dist/types/complex-types/array.d.ts +52 -51
  29. package/dist/types/complex-types/map.d.ts +80 -79
  30. package/dist/types/complex-types/model.d.ts +133 -125
  31. package/dist/types/index.d.ts +29 -29
  32. package/dist/types/primitives.d.ts +81 -81
  33. package/dist/types/utility-types/custom.d.ts +60 -60
  34. package/dist/types/utility-types/enumeration.d.ts +5 -5
  35. package/dist/types/utility-types/frozen.d.ts +11 -11
  36. package/dist/types/utility-types/identifier.d.ts +44 -44
  37. package/dist/types/utility-types/late.d.ts +10 -10
  38. package/dist/types/utility-types/literal.d.ts +25 -25
  39. package/dist/types/utility-types/maybe.d.ts +26 -26
  40. package/dist/types/utility-types/optional.d.ts +20 -20
  41. package/dist/types/utility-types/reference.d.ts +41 -47
  42. package/dist/types/utility-types/refinement.d.ts +10 -10
  43. package/dist/types/utility-types/snapshotProcessor.d.ts +61 -61
  44. package/dist/types/utility-types/union.d.ts +55 -55
  45. package/dist/utils.d.ts +4 -4
  46. package/package.json +16 -12
@@ -1 +1,16 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var Hook,mobx=require("mobx"),livelinessChecking="warn";function setLivelinessChecking(e){livelinessChecking=e}function getLivelinessChecking(){return livelinessChecking}function setLivelynessChecking(e){setLivelinessChecking(e)}!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Hook||(Hook={}));var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function __rest(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&(n[r[i]]=e[r[i]])}return n}function __decorate(e,t,n,r){var i,o=arguments.length,a=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;0<=s;s--)(i=e[s])&&(a=(o<3?i(a):3<o?i(t,n,a):i(t,n))||a);return 3<o&&a&&Object.defineProperty(t,n,a),a}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function __read(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||0<t--)&&!(r=o.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}function getType(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).type}function getChildType(e,t){return assertIsStateTreeNode(e,1),getStateTreeNode(e).getChildType(t)}function onPatch(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"function"!=typeof t)throw fail$1("expected second argument to be a function, got "+t+" instead");return getStateTreeNode(e).onPatch(t)}function onSnapshot(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"function"!=typeof t)throw fail$1("expected second argument to be a function, got "+t+" instead");return getStateTreeNode(e).onSnapshot(t)}function applyPatch(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"object"!=typeof t)throw fail$1("expected second argument to be an object or array, got "+t+" instead");getStateTreeNode(e).applyPatches(asArray(t))}function recordPatches(t){assertIsStateTreeNode(t,1);var e=null;function n(){e||(e=onPatch(t,function(e,t){r.rawPatches.push([e,t])}))}var r={rawPatches:[],get patches(){return this.rawPatches.map(function(e){return __read(e,1)[0]})},get inversePatches(){return this.rawPatches.map(function(e){var t=__read(e,2);t[0];return t[1]})},stop:function(){e&&e(),e=null},resume:n,replay:function(e){applyPatch(e||t,r.patches)},undo:function(e){applyPatch(e||t,r.inversePatches.slice().reverse())}};return n(),r}function protect(e){assertIsStateTreeNode(e,1);var t=getStateTreeNode(e);if(!t.isRoot)throw fail$1("`protect` can only be invoked on root nodes");t.isProtectionEnabled=!0}function unprotect(e){assertIsStateTreeNode(e,1);var t=getStateTreeNode(e);if(!t.isRoot)throw fail$1("`unprotect` can only be invoked on root nodes");t.isProtectionEnabled=!1}function isProtected(e){return getStateTreeNode(e).isProtected}function applySnapshot(e,t){return assertIsStateTreeNode(e,1),getStateTreeNode(e).applySnapshot(t)}function getSnapshot(e,t){void 0===t&&(t=!0),assertIsStateTreeNode(e,1);var n=getStateTreeNode(e);return t?n.snapshot:freeze(n.type.getSnapshot(n,!1))}function hasParent(e,t){if(void 0===t&&(t=1),assertIsStateTreeNode(e,1),"production"!==production){if("number"!=typeof t)throw fail$1("expected second argument to be a number, got "+t+" instead");if(t<0)throw fail$1("Invalid depth: "+t+", should be >= 1")}for(var n=getStateTreeNode(e).parent;n;){if(0==--t)return!0;n=n.parent}return!1}function getParent(e,t){if(void 0===t&&(t=1),assertIsStateTreeNode(e,1),"production"!==production){if("number"!=typeof t)throw fail$1("expected second argument to be a number, got "+t+" instead");if(t<0)throw fail$1("Invalid depth: "+t+", should be >= 1")}for(var n=t,r=getStateTreeNode(e).parent;r;){if(0==--n)return r.storedValue;r=r.parent}throw fail$1("Failed to find the parent of "+getStateTreeNode(e)+" at depth "+t)}function hasParentOfType(e,t){assertIsStateTreeNode(e,1),assertIsType(t,2);for(var n=getStateTreeNode(e).parent;n;){if(t.is(n.storedValue))return!0;n=n.parent}return!1}function getParentOfType(e,t){assertIsStateTreeNode(e,1),assertIsType(t,2);for(var n=getStateTreeNode(e).parent;n;){if(t.is(n.storedValue))return n.storedValue;n=n.parent}throw fail$1("Failed to find the parent of "+getStateTreeNode(e)+" of a given type")}function getRoot(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).root.storedValue}function getPath(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).path}function getPathParts(e){return assertIsStateTreeNode(e,1),splitJsonPath(getStateTreeNode(e).path)}function isRoot(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).isRoot}function resolvePath(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"string"!=typeof t)throw fail$1("expected second argument to be a number, got "+t+" instead");var n=resolveNodeByPath(getStateTreeNode(e),t);return n?n.value:void 0}function resolveIdentifier(e,t,n){if(assertIsType(e,1),assertIsStateTreeNode(t,2),"production"!==production&&!isValidIdentifier(n))throw fail$1("expected third argument to be a string or number, got "+n+" instead");var r=getStateTreeNode(t).root.identifierCache.resolve(e,normalizeIdentifier(n));return r?r.value:void 0}function getIdentifier(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).identifier}function tryReference(e,t){void 0===t&&(t=!0);try{var n=e();if(null==n)return;if(isStateTreeNode(n))return t?isAlive(n)?n:void 0:n;throw fail$1("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof InvalidReferenceError)return;throw e}}function isValidReference(e,t){void 0===t&&(t=!0);try{var n=e();if(null==n)return!1;if(isStateTreeNode(n))return!t||isAlive(n);throw fail$1("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof InvalidReferenceError)return!1;throw e}}function tryResolve(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"string"!=typeof t)throw fail$1("expected second argument to be a string, got "+t+" instead");var n=resolveNodeByPath(getStateTreeNode(e),t,!1);if(void 0!==n)try{return n.value}catch(e){return}}function getRelativePath(e,t){return assertIsStateTreeNode(e,1),assertIsStateTreeNode(t,2),getRelativePathBetweenNodes(getStateTreeNode(e),getStateTreeNode(t))}function clone(e,t){void 0===t&&(t=!0),assertIsStateTreeNode(e,1);var n=getStateTreeNode(e);return n.type.create(n.snapshot,!0===t?n.root.environment:!1===t?void 0:t)}function detach(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).detach(),e}function destroy(e){assertIsStateTreeNode(e,1);var t=getStateTreeNode(e);t.isRoot?t.die():t.parent.removeChild(t.subpath)}function isAlive(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).observableIsAlive}function addDisposer(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"function"!=typeof t)throw fail$1("expected second argument to be a function, got "+t+" instead");return getStateTreeNode(e).addDisposer(t),t}function getEnv(e){assertIsStateTreeNode(e,1);var t=getStateTreeNode(e).root.environment;return t||EMPTY_OBJECT}function walk(e,t){if(assertIsStateTreeNode(e,1),"production"!==production&&"function"!=typeof t)throw fail$1("expected second argument to be a function, got "+t+" instead");var n=getStateTreeNode(e);n.getChildren().forEach(function(e){isStateTreeNode(e.storedValue)&&walk(e.storedValue,t)}),t(n.storedValue)}function getPropertyMembers(e){var t;if(t=isStateTreeNode(e)?getType(e):e,"production"!==production&&!isModelType(t))throw fail$1("expected a model type, but got "+t+" instead.");return{name:t.name,properties:__assign({},t.properties)}}function getMembers(n){var e=getStateTreeNode(n).type,r=__assign({},getPropertyMembers(e),{actions:[],volatile:[],views:[]});return Object.getOwnPropertyNames(n).forEach(function(e){if(!(e in r.properties)){var t=Object.getOwnPropertyDescriptor(n,e);t.get?mobx.isComputedProp(n,e)?r.views.push(e):r.volatile.push(e):!0===t.value._isMSTAction?r.actions.push(e):mobx.isObservableProp(n,e)?r.volatile.push(e):r.views.push(e)}}),r}function cast(e){return e}function castToSnapshot(e){return e}function castToReferenceSnapshot(e){return e}function getNodeId(e){return assertIsStateTreeNode(e,1),getStateTreeNode(e).nodeId}var TypeFlags,BaseNode=function(){function e(e,t,n,r){this.type=e,this.environment=r,this._state=NodeLifeCycle.INITIALIZING,this.environment=r,this.baseSetParent(t,n)}return Object.defineProperty(e.prototype,"subpath",{get:function(){return this._subpath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"subpathUponDeath",{get:function(){return this._subpathUponDeath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pathUponDeath",{get:function(){return this._pathUponDeath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.type.getValue(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},set:function(e){var t=this.isAlive;this._state=e;var n=this.isAlive;this.aliveAtom&&t!==n&&this.aliveAtom.reportChanged()},enumerable:!0,configurable:!0}),e.prototype.fireInternalHook=function(e){this._hookSubscribers&&this._hookSubscribers.emit(e,this,e)},e.prototype.registerHook=function(e,t){return this._hookSubscribers||(this._hookSubscribers=new EventHandlers),this._hookSubscribers.register(e,t)},Object.defineProperty(e.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),e.prototype.baseSetParent=function(e,t){this._parent=e,this._subpath=t,this._escapedSubpath=void 0,this.pathAtom&&this.pathAtom.reportChanged()},Object.defineProperty(e.prototype,"path",{get:function(){return this.getEscapedPath(!0)},enumerable:!0,configurable:!0}),e.prototype.getEscapedPath=function(e){return e&&(this.pathAtom||(this.pathAtom=mobx.createAtom("path")),this.pathAtom.reportObserved()),this.parent?(void 0===this._escapedSubpath&&(this._escapedSubpath=this._subpath?escapeJsonPath(this._subpath):""),this.parent.getEscapedPath(e)+"/"+this._escapedSubpath):""},Object.defineProperty(e.prototype,"isRoot",{get:function(){return null===this.parent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAlive",{get:function(){return this.state!==NodeLifeCycle.DEAD},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isDetaching",{get:function(){return this.state===NodeLifeCycle.DETACHING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"observableIsAlive",{get:function(){return this.aliveAtom||(this.aliveAtom=mobx.createAtom("alive")),this.aliveAtom.reportObserved(),this.isAlive},enumerable:!0,configurable:!0}),e.prototype.baseFinalizeCreation=function(e){if("production"!==production&&!this.isAlive)throw fail("assertion failed: cannot finalize the creation of a node that is already dead");if(this.state===NodeLifeCycle.CREATED){if(this.parent){if(this.parent.state!==NodeLifeCycle.FINALIZED)return;this.fireHook(Hook.afterAttach)}this.state=NodeLifeCycle.FINALIZED,e&&e()}},e.prototype.baseFinalizeDeath=function(){this._hookSubscribers&&this._hookSubscribers.clearAll(),this._subpathUponDeath=this._subpath,this._pathUponDeath=this.getEscapedPath(!1),this.baseSetParent(null,""),this.state=NodeLifeCycle.DEAD},e.prototype.baseAboutToDie=function(){this.fireHook(Hook.beforeDestroy)},e}(),ScalarNode=function(a){function e(e,t,n,r,i){var o=a.call(this,e,t,n,r)||this;try{o.storedValue=e.createNewInstance(i)}catch(e){throw o.state=NodeLifeCycle.DEAD,e}return o.state=NodeLifeCycle.CREATED,o.finalizeCreation(),o}return __extends(e,a),Object.defineProperty(e.prototype,"root",{get:function(){if(!this.parent)throw fail$1("This scalar node is not part of a tree");return this.parent.root},enumerable:!0,configurable:!0}),e.prototype.setParent=function(e,t){var n=this.parent!==e,r=this.subpath!==t;if(n||r){if("production"!==production){if(!t)throw fail$1("assertion failed: subpath expected");if(!e)throw fail$1("assertion failed: parent expected");if(n)throw fail$1("assertion failed: scalar nodes cannot change their parent")}this.environment=void 0,this.baseSetParent(this.parent,t)}},Object.defineProperty(e.prototype,"snapshot",{get:function(){return freeze(this.getSnapshot())},enumerable:!0,configurable:!0}),e.prototype.getSnapshot=function(){return this.type.getSnapshot(this)},e.prototype.toString=function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"<root>";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")},e.prototype.die=function(){this.isAlive&&this.state!==NodeLifeCycle.DETACHING&&(this.aboutToDie(),this.finalizeDeath())},e.prototype.finalizeCreation=function(){this.baseFinalizeCreation()},e.prototype.aboutToDie=function(){this.baseAboutToDie()},e.prototype.finalizeDeath=function(){this.baseFinalizeDeath()},e.prototype.fireHook=function(e){this.fireInternalHook(e)},__decorate([mobx.action],e.prototype,"die",null),e}(BaseNode),nextNodeId=1,snapshotReactionOptions={onError:function(e){throw e}},ObjectNode=function(p){function e(e,t,n,r,i){var o=p.call(this,e,t,n,r)||this;if(o.nodeId=++nextNodeId,o.isProtectionEnabled=!0,o.middlewares=null,o._autoUnbox=!0,o._isRunningAction=!1,o._hasSnapshotReaction=!1,o._observableInstanceState=0,o._cachedInitialSnapshotCreated=!1,o.unbox=o.unbox.bind(o),o._initialSnapshot=freeze(i),o.identifierAttribute=e.identifierAttribute,t||(o.identifierCache=new IdentifierCache),o._childNodes=e.initializeChildNodes(o,o._initialSnapshot),o.identifier=null,o.unnormalizedIdentifier=null,o.identifierAttribute&&o._initialSnapshot){var a=o._initialSnapshot[o.identifierAttribute];if(void 0===a){var s=o._childNodes[o.identifierAttribute];s&&(a=s.value)}if("string"!=typeof a&&"number"!=typeof a)throw fail$1("Instance identifier '"+o.identifierAttribute+"' for type '"+o.type.name+"' must be a string or a number");o.identifier=normalizeIdentifier(a),o.unnormalizedIdentifier=a}return t?t.root.identifierCache.addNodeToCache(o):o.identifierCache.addNodeToCache(o),o}return __extends(e,p),e.prototype.applyPatches=function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)},e.prototype.applySnapshot=function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)},e.prototype.createObservableInstanceIfNeeded=function(){var t,e;if(0===this._observableInstanceState){if("production"!==production&&this.state!==NodeLifeCycle.INITIALIZING)throw fail$1("assertion failed: the creation of the observable instance must be done on the initializing phase");this._observableInstanceState=1;for(var n=[],r=this.parent;r&&0===r._observableInstanceState;)n.unshift(r),r=r.parent;try{for(var i=__values(n),o=i.next();!o.done;o=i.next()){o.value.createObservableInstanceIfNeeded()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=i.return)&&e.call(i)}finally{if(t)throw t.error}}var a=this.type;try{this.storedValue=a.createNewInstance(this._childNodes),this.preboot(),this._isRunningAction=!0,a.finalizeNewInstance(this,this.storedValue)}catch(e){throw this.state=NodeLifeCycle.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,invalidateComputed(this,"snapshot"),this.isRoot&&this._addSnapshotReaction(),this._childNodes=EMPTY_OBJECT,this.state=NodeLifeCycle.CREATED,this.fireHook(Hook.afterCreate),this.finalizeCreation()}},Object.defineProperty(e.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!0,configurable:!0}),e.prototype.clearParent=function(){if(this.parent){this.fireHook(Hook.beforeDetach);var e=this.state;this.state=NodeLifeCycle.DETACHING;var t=this.root,n=t.environment,r=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=n,this.identifierCache=r}finally{this.state=e}}},e.prototype.setParent=function(e,t){var n=e!==this.parent,r=t!==this.subpath;if(n||r){if("production"!==production){if(!t)throw fail$1("assertion failed: subpath expected");if(!e)throw fail$1("assertion failed: new parent expected");if(this.parent&&n)throw fail$1("A node cannot exists twice in the state tree. Failed to add "+this+" to path '"+e.path+"/"+t+"'.");if(!this.parent&&e.root===this)throw fail$1("A state tree is not allowed to contain itself. Cannot assign "+this+" to path '"+e.path+"/"+t+"'");if(!this.parent&&this.environment&&this.environment!==e.root.environment)throw fail$1("A state tree cannot be made part of another state tree as long as their environments are different.")}n?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Hook.afterAttach)):r&&this.baseSetParent(this.parent,t)}},e.prototype.fireHook=function(e){var t=this;this.fireInternalHook(e);var n=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof n&&(mobx._allowStateChangesInsideComputed?mobx._allowStateChangesInsideComputed(function(){n.apply(t.storedValue)}):n.apply(this.storedValue))},Object.defineProperty(e.prototype,"snapshot",{get:function(){return freeze(this.getSnapshot())},enumerable:!0,configurable:!0}),e.prototype.getSnapshot=function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath},e.prototype._getActualSnapshot=function(){return this.type.getSnapshot(this)},e.prototype._getCachedInitialSnapshot=function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,n=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,n),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot},e.prototype.isRunningAction=function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()},e.prototype.assertAlive=function(e){var t=getLivelinessChecking();if(!this.isAlive&&"ignore"!==t){var n=this._getAssertAliveError(e);switch(t){case"error":throw fail$1(n);case"warn":warnError(n)}}},e.prototype._getAssertAliveError=function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",n=e.subpath&&escapeJsonPath(e.subpath)||"",r=e.actionContext||getCurrentActionContext(),i="";r&&null!=r.name&&(i=(r&&r.context&&getPath(r.context)||t)+"."+r.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: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."},e.prototype.getChildNode=function(e){this.assertAlive({subpath:e}),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildNode(this,e):this._childNodes[e]}finally{this._autoUnbox=!0}},e.prototype.getChildren=function(){this.assertAlive(EMPTY_OBJECT),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):convertChildNodesToArray(this._childNodes)}finally{this._autoUnbox=!0}},e.prototype.getChildType=function(e){return this.type.getChildType(e)},Object.defineProperty(e.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!0,configurable:!0}),e.prototype.assertWritable=function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw fail$1("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")},e.prototype.removeChild=function(e){this.type.removeChild(this,e)},e.prototype.unbox=function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e},e.prototype.toString=function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"<root>",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")},e.prototype.finalizeCreation=function(){var i=this;this.baseFinalizeCreation(function(){var t,e;try{for(var n=__values(i.getChildren()),r=n.next();!r.done;r=n.next()){r.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{r&&!r.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}i.fireInternalHook(Hook.afterCreationFinalization)})},e.prototype.detach=function(){if(!this.isAlive)throw fail$1("Error while detaching, node is not alive.");this.clearParent()},e.prototype.preboot=function(){var n=this;this._applyPatches=createActionInvoker(this.storedValue,"@APPLY_PATCHES",function(e){e.forEach(function(e){var t=splitJsonPath(e.path);resolveNodeByPathParts(n,t.slice(0,-1)).applyPatchLocally(t[t.length-1],e)})}),this._applySnapshot=createActionInvoker(this.storedValue,"@APPLY_SNAPSHOT",function(e){if(e!==n.snapshot)return n.type.applySnapshot(n,e)}),addHiddenFinalProp(this.storedValue,"$treenode",this),addHiddenFinalProp(this.storedValue,"toJSON",toJSON)},e.prototype.die=function(){this.isAlive&&this.state!==NodeLifeCycle.DETACHING&&(this.aboutToDie(),this.finalizeDeath())},e.prototype.aboutToDie=function(){0!==this._observableInstanceState&&(this.getChildren().forEach(function(e){e.aboutToDie()}),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))},e.prototype.finalizeDeath=function(){this.getChildren().forEach(function(e){e.finalizeDeath()}),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()},e.prototype.onSnapshot=function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)},e.prototype.emitSnapshot=function(e){this._internalEventsEmit("snapshot",e)},e.prototype.onPatch=function(e){return this._internalEventsRegister("patch",e)},e.prototype.emitPatch=function(e,t){if(this._internalEventsHasSubscribers("patch")){var n=__read(splitPatch(extend({},e,{path:t.path.substr(this.path.length)+"/"+e.path})),2),r=n[0],i=n[1];this._internalEventsEmit("patch",r,i)}this.parent&&this.parent.emitPatch(e,t)},e.prototype.hasDisposer=function(e){return this._internalEventsHas("dispose",e)},e.prototype.addDisposer=function(e){if(this.hasDisposer(e))throw fail$1("cannot add a disposer when it is already registered for execution");this._internalEventsRegister("dispose",e,!0)},e.prototype.removeDisposer=function(e){if(!this._internalEventsHas("dispose",e))throw fail$1("cannot remove a disposer which was never registered for execution");this._internalEventsUnregister("dispose",e)},e.prototype.removeMiddleware=function(t){this.middlewares&&(this.middlewares=this.middlewares.filter(function(e){return e.handler!==t}))},e.prototype.addMiddleWare=function(e,t){var n=this;return void 0===t&&(t=!0),this.middlewares?this.middlewares.push({handler:e,includeHooks:t}):this.middlewares=[{handler:e,includeHooks:t}],function(){n.removeMiddleware(e)}},e.prototype.applyPatchLocally=function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)},e.prototype._addSnapshotReaction=function(){var t=this;if(!this._hasSnapshotReaction){var e=mobx.reaction(function(){return t.snapshot},function(e){return t.emitSnapshot(e)},snapshotReactionOptions);this.addDisposer(e),this._hasSnapshotReaction=!0}},e.prototype._internalEventsHasSubscribers=function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)},e.prototype._internalEventsRegister=function(e,t,n){return void 0===n&&(n=!1),this._internalEvents||(this._internalEvents=new EventHandlers),this._internalEvents.register(e,t,n)},e.prototype._internalEventsHas=function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)},e.prototype._internalEventsUnregister=function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)},e.prototype._internalEventsEmit=function(e){for(var t,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];this._internalEvents&&(t=this._internalEvents).emit.apply(t,__spread([e],n))},e.prototype._internalEventsClear=function(e){this._internalEvents&&this._internalEvents.clear(e)},e.prototype._internalEventsClearAll=function(){this._internalEvents&&this._internalEvents.clearAll()},__decorate([mobx.action],e.prototype,"createObservableInstanceIfNeeded",null),__decorate([mobx.computed],e.prototype,"snapshot",null),__decorate([mobx.action],e.prototype,"detach",null),__decorate([mobx.action],e.prototype,"die",null),e}(BaseNode);!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"}(TypeFlags||(TypeFlags={}));var cannotDetermineSubtype="cannotDetermine",BaseType=function(){function e(e){this.isType=!0,this.name=e}return e.prototype.create=function(e,t){return typecheckInternal(this,e),this.instantiate(null,"",t,e).value},e.prototype.getSnapshot=function(e,t){throw fail$1("unimplemented method")},e.prototype.isAssignableFrom=function(e){return e===this},e.prototype.validate=function(e,t){if(getStateTreeNodeSafe(e)){var n=getType(e);return this.isAssignableFrom(n)?typeCheckSuccess():typeCheckFailure(t,e)}return this.isValidSnapshot(e,t)},e.prototype.is=function(e){return 0===this.validate(e,[{path:"",type:this}]).length},Object.defineProperty(e.prototype,"Type",{get:function(){throw fail$1("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`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"SnapshotType",{get:function(){throw fail$1("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`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CreationType",{get:function(){throw fail$1("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`")},enumerable:!0,configurable:!0}),__decorate([mobx.action],e.prototype,"create",null),e}(),ComplexType=function(n){function e(e){return n.call(this,e)||this}return __extends(e,n),e.prototype.create=function(e,t){return void 0===e&&(e=this.getDefaultSnapshot()),n.prototype.create.call(this,e,t)},e.prototype.getValue=function(e){return e.createObservableInstanceIfNeeded(),e.storedValue},e.prototype.tryToReconcileNode=function(e,t){return!e.isDetaching&&(e.snapshot===t||(!(!isStateTreeNode(t)||getStateTreeNode(t)!==e)||!(e.type!==this||!isMutable(t)||isStateTreeNode(t)||e.identifierAttribute&&e.identifier!==normalizeIdentifier(t[e.identifierAttribute]))&&(e.applySnapshot(t),!0)))},e.prototype.reconcile=function(e,t,n,r){if(this.tryToReconcileNode(e,t))return e.setParent(n,r),e;if(e.die(),isStateTreeNode(t)&&this.isAssignableFrom(getType(t))){var i=getStateTreeNode(t);return i.setParent(n,r),i}return this.instantiate(n,r,void 0,t)},e.prototype.getSubTypes=function(){return null},__decorate([mobx.action],e.prototype,"create",null),e}(BaseType),SimpleType=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.createNewInstance=function(e){return e},t.prototype.getValue=function(e){return e.storedValue},t.prototype.getSnapshot=function(e){return e.storedValue},t.prototype.reconcile=function(e,t,n,r){if(!e.isDetaching&&e.type===this&&e.storedValue===t)return e;var i=this.instantiate(n,r,void 0,t);return e.die(),i},t.prototype.getSubTypes=function(){return null},t}(BaseType);function isType(e){return"object"==typeof e&&e&&!0===e.isType}function assertIsType(e,t){if("production"!==production&&!isType(e))throw fail$1("expected a mobx-state-tree type as argument "+t+", got "+e+" instead")}var runningActions=new Map;function createActionTrackingMiddleware(a){return function(t,e,n){switch(t.type){case"action":if(a.filter&&!0!==a.filter(t))return e(t);var r=a.onStart(t);a.onResume(t,r),runningActions.set(t.id,{call:t,context:r,async:!1});try{var i=e(t);return a.onSuspend(t,r),!1===runningActions.get(t.id).async&&(runningActions.delete(t.id),a.onSuccess(t,r,i)),i}catch(e){throw runningActions.delete(t.id),a.onFail(t,r,e),e}case"flow_spawn":return(o=runningActions.get(t.rootId)).async=!0,e(t);case"flow_resume":case"flow_resume_error":var o=runningActions.get(t.rootId);a.onResume(t,o.context);try{return e(t)}finally{a.onSuspend(t,o.context)}case"flow_throw":o=runningActions.get(t.rootId);return runningActions.delete(t.rootId),a.onFail(t,o.context,t.args[0]),e(t);case"flow_return":o=runningActions.get(t.rootId);return runningActions.delete(t.rootId),a.onSuccess(t,o.context,t.args[0]),e(t)}}}function serializeArgument(e,t,n,r){if(r instanceof Date)return{$MST_DATE:r.getTime()};if(isPrimitive(r))return r;if(isStateTreeNode(r))return serializeTheUnserializable("[MSTNode: "+getType(r).name+"]");if("function"==typeof r)return serializeTheUnserializable("[function]");if("object"==typeof r&&!isPlainObject(r)&&!isArray(r))return serializeTheUnserializable("[object "+(r&&r.constructor&&r.constructor.name||"Complex Object")+"]");try{return JSON.stringify(r),r}catch(e){return serializeTheUnserializable(""+e)}}function deserializeArgument(e,t){return t&&"object"==typeof t&&"$MST_DATE"in t?new Date(t.$MST_DATE):t}function serializeTheUnserializable(e){return{$MST_UNSERIALIZABLE:!0,type:e}}function applyAction(t,e){if(assertIsStateTreeNode(t,1),"production"!==production&&"object"!=typeof e)throw fail$1("expected second argument to be an object or array, got "+e+" instead");mobx.runInAction(function(){asArray(e).forEach(function(e){return baseApplyAction(t,e)})})}function baseApplyAction(e,t){var n=tryResolve(e,t.path||"");if(!n)throw fail$1("Invalid action path: "+(t.path||""));var r=getStateTreeNode(n);if("@APPLY_PATCHES"===t.name)return applyPatch.call(null,n,t.args[0]);if("@APPLY_SNAPSHOT"===t.name)return applySnapshot.call(null,n,t.args[0]);if("function"!=typeof n[t.name])throw fail$1("Action '"+t.name+"' does not exist in '"+r.path+"'");return n[t.name].apply(n,t.args?t.args.map(function(e){return deserializeArgument(r,e)}):[])}function recordActions(e){assertIsStateTreeNode(e,1);var t=[],n={actions:t,stop:function(){return r()},replay:function(e){applyAction(e,t)}},r=onAction(e,t.push.bind(n.actions));return n}function onAction(o,a,s){return void 0===s&&(s=!1),assertIsStateTreeNode(o,1),"production"!==production&&(isRoot(o)||warnError("Warning: Attaching onAction listeners to non root nodes is dangerous: No events will be emitted for actions initiated higher up in the tree."),isProtected(o)||warnError("Warning: Attaching onAction listeners to non protected nodes is dangerous: No events will be emitted for direct modifications without action.")),addMiddleware(o,function(n,e){if("action"!==n.type||n.id!==n.rootId)return e(n);var r=getStateTreeNode(n.context),t={name:n.name,path:getRelativePathBetweenNodes(getStateTreeNode(o),r),args:n.args.map(function(e,t){return serializeArgument(r,n.name,t,e)})};if(s){var i=e(n);return a(t),i}return a(t),e(n)})}var nextActionId=1,currentActionContext=null;function getCurrentActionContext(){return currentActionContext}function getNextActionId(){return nextActionId++}function runWithActionContext(e,t){var n=getStateTreeNode(e.context),r=n._isRunningAction,i=currentActionContext;"action"===e.type&&n.assertAlive({actionContext:e}),n._isRunningAction=!0,currentActionContext=e;try{return runMiddleWares(n,e,t)}finally{currentActionContext=i,n._isRunningAction=r}}function getActionContext(){if(!currentActionContext)throw fail$1("Not running an action!");return currentActionContext}function createActionInvoker(t,n,r){var e=function(){var e=getNextActionId();return runWithActionContext({type:"action",name:n,id:e,args:argsToArray(arguments),context:t,tree:getRoot(t),rootId:currentActionContext?currentActionContext.rootId:e,parentId:currentActionContext?currentActionContext.id:0,allParentIds:currentActionContext?__spread(currentActionContext.allParentIds,[currentActionContext.id]):[]},r)};return e._isMSTAction=!0,e}function addMiddleware(e,t,n){void 0===n&&(n=!0);var r=getStateTreeNode(e);return"production"!==production&&(r.isProtectionEnabled||warnError("It is recommended to protect the state tree before attaching action middleware, as otherwise it cannot be guaranteed that all changes are passed through middleware. See `protect`")),r.addMiddleWare(t,n)}function decorate(e,t){var n={handler:e,includeHooks:!0};return t.$mst_middleware&&t.$mst_middleware.push(n),t.$mst_middleware=[n],t}function collectMiddlewares(e,t,n){for(var r=n.$mst_middleware||EMPTY_ARRAY,i=e;i;)i.middlewares&&(r=r.concat(i.middlewares)),i=i.parent;return r}function runMiddleWares(e,t,s){var p=collectMiddlewares(e,t,s);if(!p.length)return mobx.action(s).apply(null,t.args);var c=0,u=null;return function r(e){var t=p[c++],n=t&&t.handler;if(!n)return mobx.action(s).apply(null,e.args);if(!t.includeHooks&&Hook[e.name])return r(e);var i=!1;var o=!1;if(n(e,function(e,t){i=!0;var n=r(e);u=t?t(n):n},function(e){o=!0,u=e}),"production"!==production){if(!i&&!o){var a=getStateTreeNode(e.tree);throw fail$1("Neither the next() nor the abort() callback within the middleware "+n.name+' for the action: "'+e.name+'" on the node: '+a.type.name+" was invoked.")}if(i&&o)throw a=getStateTreeNode(e.tree),fail$1("The next() and abort() callback within the middleware "+n.name+' for the action: "'+e.name+'" on the node: '+a.type.name+" were invoked.")}return u}(t)}function safeStringify(e){try{return JSON.stringify(e)}catch(e){return"<Unserializable: "+e+">"}}function prettyPrintValue(e){return"function"==typeof e?"<function"+(e.name?" "+e.name:"")+">":isStateTreeNode(e)?"<"+e+">":"`"+safeStringify(e)+"`"}function shortenPrintValue(e){return e.length<280?e:e.substring(0,272)+"......"+e.substring(e.length-8)}function toErrorString(e){var t=e.value,n=e.context[e.context.length-1].type,r=e.context.map(function(e){return e.path}).filter(function(e){return 0<e.length}).join("/"),i=0<r.length?'at path "/'+r+'" ':"",o=isStateTreeNode(t)?"value of type "+getStateTreeNode(t).type.name+":":isPrimitive(t)?"value":"snapshot",a=n&&isStateTreeNode(t)&&n.is(getStateTreeNode(t).snapshot);return""+i+o+" "+prettyPrintValue(t)+" is not assignable "+(n?"to type: `"+n.name+"`":"")+(e.message?" ("+e.message+")":"")+(n?isPrimitiveType(n)||isPrimitive(t)?".":", expected an instance of `"+n.name+"` or a snapshot like `"+n.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function getContextForPath(e,t,n){return e.concat([{path:t,type:n}])}function typeCheckSuccess(){return EMPTY_ARRAY}function typeCheckFailure(e,t,n){return[{context:e,value:t,message:n}]}function flattenTypeErrors(e){return e.reduce(function(e,t){return e.concat(t)},[])}function typecheckInternal(e,t){"production"!==production&&typecheck(e,t)}function typecheck(e,t){var n=e.validate(t,[{path:"",type:e}]);if(0<n.length)throw fail$1(validationErrorsToString(e,t,n))}function validationErrorsToString(e,t,n){if(0!==n.length)return"Error while converting "+shortenPrintValue(prettyPrintValue(t))+" to `"+e.name+"`:\n\n "+n.map(toErrorString).join("\n ")}var NodeLifeCycle,identifierCacheId=0,IdentifierCache=function(){function t(){this.cacheId=identifierCacheId++,this.cache=mobx.observable.map(),this.lastCacheModificationPerId=mobx.observable.map()}return t.prototype.updateLastCacheModificationPerId=function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)},t.prototype.getLastCacheModificationPerId=function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t},t.prototype.addNodeToCache=function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var n=e.identifier;this.cache.has(n)||this.cache.set(n,mobx.observable.array([],mobxShallow));var r=this.cache.get(n);if(-1!==r.indexOf(e))throw fail$1("Already registered");r.push(e),t&&this.updateLastCacheModificationPerId(n)}},t.prototype.mergeCache=function(e){var t=this;mobx.values(e.identifierCache.cache).forEach(function(e){return e.forEach(function(e){t.addNodeToCache(e)})})},t.prototype.notifyDied=function(e){if(e.identifierAttribute){var t=e.identifier,n=this.cache.get(t);n&&(n.remove(e),n.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}},t.prototype.splitCache=function(e){var a=this,s=new t,p=e.path;return mobx.entries(this.cache).forEach(function(e){for(var t=__read(e,2),n=t[0],r=t[1],i=!1,o=r.length-1;0<=o;o--)0===r[o].path.indexOf(p)&&(s.addNodeToCache(r[o],!1),r.splice(o,1),i=!0);i&&a.updateLastCacheModificationPerId(n)}),s},t.prototype.has=function(t,e){var n=this.cache.get(e);return!!n&&n.some(function(e){return t.isAssignableFrom(e.type)})},t.prototype.resolve=function(t,e){var n=this.cache.get(e);if(!n)return null;var r=n.filter(function(e){return t.isAssignableFrom(e.type)});switch(r.length){case 0:return null;case 1:return r[0];default:throw fail$1("Cannot resolve a reference to type '"+t.name+"' with id: '"+e+"' unambigously, there are multiple candidates: "+r.map(function(e){return e.path}).join(", "))}},t}();function createObjectNode(e,t,n,r,i){var o=getStateTreeNodeSafe(i);if(o){if(o.parent)throw fail$1("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 '"+o.path+"'");return t&&o.setParent(t,n),o}return new ObjectNode(e,t,n,r,i)}function createScalarNode(e,t,n,r,i){return new ScalarNode(e,t,n,r,i)}function isNode(e){return e instanceof ScalarNode||e instanceof ObjectNode}function isStateTreeNode(e){return!(!e||!e.$treenode)}function assertIsStateTreeNode(e,t){if("production"!==production&&!isStateTreeNode(e))throw fail$1("expected a mobx-state-tree node as argument "+t+", got "+e+" instead")}function getStateTreeNode(e){if(!isStateTreeNode(e))throw fail$1("Value "+e+" is no MST Node");return e.$treenode}function getStateTreeNodeSafe(e){return e&&e.$treenode||null}function toJSON(){return getStateTreeNode(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"}(NodeLifeCycle||(NodeLifeCycle={}));var doubleDot=function(e){return".."};function getRelativePathBetweenNodes(e,t){if(e.root!==t.root)throw fail$1("Cannot calculate relative path: objects '"+e+"' and '"+t+"' are not part of the same object tree");for(var n=splitJsonPath(e.path),r=splitJsonPath(t.path),i=0;i<n.length&&n[i]===r[i];i++);return n.slice(i).map(doubleDot).join("/")+joinJsonPath(r.slice(i))}function resolveNodeByPath(e,t,n){return void 0===n&&(n=!0),resolveNodeByPathParts(e,splitJsonPath(t),n)}function resolveNodeByPathParts(e,t,n){void 0===n&&(n=!0);for(var r=e,i=0;i<t.length;i++){var o=t[i];if(".."===o){if(r=r.parent)continue}else{if("."===o)continue;if(r){if(r instanceof ScalarNode)try{var a=r.value;isStateTreeNode(a)&&(r=getStateTreeNode(a))}catch(e){if(!n)return;throw e}if(r instanceof ObjectNode)if(r.getChildType(o)&&(r=r.getChildNode(o)))continue}}if(n)throw fail$1("Could not resolve '"+o+"' in path '"+(joinJsonPath(t.slice(0,i))||"/")+"' while resolving '"+joinJsonPath(t)+"'");return}return r}function convertChildNodesToArray(n){if(!n)return EMPTY_ARRAY;var e=Object.keys(n);if(!e.length)return EMPTY_ARRAY;var r=new Array(e.length);return e.forEach(function(e,t){r[t]=n[e]}),r}var DEPRECATION_MESSAGE="See https://github.com/mobxjs/mobx-state-tree/issues/399 for more information. Note that the middleware event types starting with `process` now start with `flow`.";function process(e){return deprecated("process","`process()` has been renamed to `flow()`. "+DEPRECATION_MESSAGE),flow(e)}var EMPTY_ARRAY=Object.freeze([]),EMPTY_OBJECT=Object.freeze({}),mobxShallow="string"==typeof mobx.$mobx?{deep:!1}:{deep:!1,proxy:!1};function fail$1(e){return void 0===e&&(e="Illegal state"),new Error("[mobx-state-tree] "+e)}function identity(e){return e}Object.freeze(mobxShallow);var isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function isArray(e){return Array.isArray(e)||mobx.isObservableArray(e)}function asArray(e){return e?isArray(e)?e:[e]:EMPTY_ARRAY}function extend(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0;r<t.length;r++){var i=t[r];for(var o in i)e[o]=i[o]}return e}function isPlainObject(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function isMutable(e){return!(null===e||"object"!=typeof e||e instanceof Date||e instanceof RegExp)}function isPrimitive(e,t){return void 0===t&&(t=!0),null==e||!!("string"==typeof e||"number"==typeof e||"boolean"==typeof e||t&&e instanceof Date)}function freeze(e){return"production"===production?e:isPrimitive(e)||mobx.isObservableArray(e)?e:Object.freeze(e)}function deepFreeze(t){return"production"===production||(freeze(t),isPlainObject(t)&&Object.keys(t).forEach(function(e){isPrimitive(t[e])||Object.isFrozen(t[e])||deepFreeze(t[e])})),t}function isSerializable(e){return"function"!=typeof e}function addHiddenFinalProp(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function addHiddenWritableProp(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}var EventHandler=function(){function e(){this.handlers=[]}return Object.defineProperty(e.prototype,"hasSubscribers",{get:function(){return 0<this.handlers.length},enumerable:!0,configurable:!0}),e.prototype.register=function(e,t){var n=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){n.unregister(e)}},e.prototype.has=function(e){return 0<=this.handlers.indexOf(e)},e.prototype.unregister=function(e){var t=this.handlers.indexOf(e);0<=t&&this.handlers.splice(t,1)},e.prototype.clear=function(){this.handlers.length=0},e.prototype.emit=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.handlers.slice().forEach(function(e){return e.apply(void 0,__spread(t))})},e}(),EventHandlers=function(){function e(){}return e.prototype.hasSubscribers=function(e){var t=this.eventHandlers&&this.eventHandlers[e];return!!t&&t.hasSubscribers},e.prototype.register=function(e,t,n){void 0===n&&(n=!1),this.eventHandlers||(this.eventHandlers={});var r=this.eventHandlers[e];return r||(r=this.eventHandlers[e]=new EventHandler),r.register(t,n)},e.prototype.has=function(e,t){var n=this.eventHandlers&&this.eventHandlers[e];return!!n&&n.has(t)},e.prototype.unregister=function(e,t){var n=this.eventHandlers&&this.eventHandlers[e];n&&n.unregister(t)},e.prototype.clear=function(e){this.eventHandlers&&delete this.eventHandlers[e]},e.prototype.clearAll=function(){this.eventHandlers=void 0},e.prototype.emit=function(e){for(var t,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=this.eventHandlers&&this.eventHandlers[e];i&&(t=i).emit.apply(t,__spread(n))},e}();function argsToArray(e){for(var t=new Array(e.length),n=0;n<e.length;n++)t[n]=e[n];return t}function invalidateComputed(e,t){mobx.getAtom(e,t).trackAndCompute()}function stringStartsWith(e,t){return 0===e.indexOf(t)}var deprecated=function(e,t){"production"!==production&&(deprecated.ids&&!deprecated.ids.hasOwnProperty(e)&&warnError("Deprecation warning: "+t),deprecated.ids&&(deprecated.ids[e]=!0))};function warnError(e){console.warn(new Error("[mobx-state-tree] "+e))}function flow(e){return createFlowSpawner(e.name,e)}function castFlowReturn(e){return e}function createFlowSpawner(l,d){var f=function(){var s=getNextActionId(),p=getActionContext(),c=arguments;function u(e,t,n){e.$mst_middleware=f.$mst_middleware,runWithActionContext({name:l,type:t,id:s,args:[n],tree:p.tree,context:p.context,parentId:p.id,allParentIds:__spread(p.allParentIds,[p.id]),rootId:p.rootId},e)}return new Promise(function(t,n){var r,e=function(){r=d.apply(null,arguments),i(void 0)};function i(e){var t;try{u(function(e){t=r.next(e)},"flow_resume",e)}catch(t){return void setImmediate(function(){u(function(e){n(t)},"flow_throw",t)})}a(t)}function o(e){var t;try{u(function(e){t=r.throw(e)},"flow_resume_error",e)}catch(t){return void setImmediate(function(){u(function(e){n(t)},"flow_throw",t)})}a(t)}function a(e){if(!e.done){if(!e.value||"function"!=typeof e.value.then)throw fail$1("Only promises can be yielded to `async`, got: "+e);return e.value.then(i,o)}setImmediate(function(){u(function(e){t(e)},"flow_return",e.value)})}e.$mst_middleware=f.$mst_middleware,runWithActionContext({name:l,type:"flow_spawn",id:s,args:argsToArray(c),tree:p.tree,context:p.context,parentId:p.id,allParentIds:__spread(p.allParentIds,[p.id]),rootId:p.rootId},e)})};return f}function splitPatch(e){if(!("oldValue"in e))throw fail$1("Patches without `oldValue` field cannot be inversed");return[stripPatch(e),invertPatch(e)]}function stripPatch(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 invertPatch(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 isNumber(e){return"number"==typeof e}function escapeJsonPath(e){return!0===isNumber(e)?""+e:-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPath(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function joinJsonPath(e){if(0===e.length)return"";var t=function(e){return e.map(escapeJsonPath).join("/")};return"."===e[0]||".."===e[0]?t(e):"/"+t(e)}function splitJsonPath(e){var t=e.split("/").map(unescapeJsonPath);if(!(""===e||"."===e||".."===e||stringStartsWith(e,"/")||stringStartsWith(e,"./")||stringStartsWith(e,"../")))throw fail$1("a json path must be either rooted, empty or relative, but got '"+e+"'");return""===t[0]&&t.shift(),t}deprecated.ids={};var SnapshotProcessor=function(i){function e(e,t,n){var r=i.call(this,n||e.name)||this;return r._subtype=e,r._processors=t,r}return __extends(e,i),Object.defineProperty(e.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.SnapshotProcessor},enumerable:!0,configurable:!0}),e.prototype.describe=function(){return"snapshotProcessor("+this._subtype.describe()+")"},e.prototype.preProcessSnapshot=function(e){return this._processors.preProcessor?this._processors.preProcessor.call(null,e):e},e.prototype.postProcessSnapshot=function(e){return this._processors.postProcessor?this._processors.postProcessor.call(null,e):e},e.prototype._fixNode=function(e){var t=this;proxyNodeTypeMethods(e.type,this,"isAssignableFrom","create");var n=e.getSnapshot;e.getSnapshot=function(){return t.postProcessSnapshot(n.call(e))}},e.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?r:this.preProcessSnapshot(r),o=this._subtype.instantiate(e,t,n,i);return this._fixNode(o),o},e.prototype.reconcile=function(e,t,n,r){var i=this._subtype.reconcile(e,isStateTreeNode(t)?t:this.preProcessSnapshot(t),n,r);return i!==e&&this._fixNode(i),i},e.prototype.getSnapshot=function(e,t){void 0===t&&(t=!0);var n=this._subtype.getSnapshot(e);return t?this.postProcessSnapshot(n):n},e.prototype.isValidSnapshot=function(e,t){var n=this.preProcessSnapshot(e);return this._subtype.validate(n,t)},e.prototype.getSubTypes=function(){return this._subtype},e}(BaseType);function proxyNodeTypeMethods(e,t){for(var n,r,i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];try{for(var a=__values(i),s=a.next();!s.done;s=a.next()){var p=s.value;e[p]=t[p].bind(t)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}function snapshotProcessor(e,t,n){if(assertIsType(e,1),"production"!==production){if(t.postProcessor&&"function"!=typeof t.postProcessor)throw fail("postSnapshotProcessor must be a function");if(t.preProcessor&&"function"!=typeof t.preProcessor)throw fail("preSnapshotProcessor must be a function")}return new SnapshotProcessor(e,t,n)}var MapIdentifierMode,needsIdentifierError="Map.put can only be used to store complex values that have an identifier type attribute";function tryCollectModelTypes(e,t){var n,r,i=e.getSubTypes();if(i===cannotDetermineSubtype)return!1;if(i){var o=asArray(i);try{for(var a=__values(o),s=a.next();!s.done;s=a.next()){if(!tryCollectModelTypes(s.value,t))return!1}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}return e instanceof ModelType&&t.push(e),!0}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.YES=1]="YES",e[e.NO=2]="NO"}(MapIdentifierMode||(MapIdentifierMode={}));var MSTMap=function(n){function e(e){return n.call(this,e,mobx.observable.ref.enhancer)||this}return __extends(e,n),e.prototype.get=function(e){return n.prototype.get.call(this,""+e)},e.prototype.has=function(e){return n.prototype.has.call(this,""+e)},e.prototype.delete=function(e){return n.prototype.delete.call(this,""+e)},e.prototype.set=function(e,t){return n.prototype.set.call(this,""+e,t)},e.prototype.put=function(e){if(!e)throw fail$1("Map.put cannot be used to set empty values");if(isStateTreeNode(e)){var t=getStateTreeNode(e);if("production"!==production&&!t.identifierAttribute)throw fail$1(needsIdentifierError);if(null===t.identifier)throw fail$1(needsIdentifierError);return this.set(t.identifier,e),e}if(isMutable(e)){var n=getStateTreeNode(this),r=n.type;if(r.identifierMode!==MapIdentifierMode.YES)throw fail$1(needsIdentifierError);var i=e[r.mapIdentifierAttribute];if(!isValidIdentifier(i)){var o=this.put(r.getChildType().create(e,n.environment));return this.put(getSnapshot(o))}var a=normalizeIdentifier(i);return this.set(a,e),this.get(a)}throw fail$1("Map.put can only be used to store complex values")},e}(mobx.ObservableMap),MapType=function(r){function e(e,t){var n=r.call(this,e)||this;return n._subType=t,n.identifierMode=MapIdentifierMode.UNKNOWN,n.mapIdentifierAttribute=void 0,n.flags=TypeFlags.Map,n._determineIdentifierMode(),n}return __extends(e,r),e.prototype.instantiate=function(e,t,n,r){return this._determineIdentifierMode(),createObjectNode(this,e,t,n,r)},e.prototype._determineIdentifierMode=function(){if(this.identifierMode===MapIdentifierMode.UNKNOWN){var e=[];if(tryCollectModelTypes(this._subType,e)){var t=void 0;e.forEach(function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw fail$1("The objects in a map should all have the same identifier attribute, expected '"+t+"', but child of type '"+e.name+"' declared attribute '"+e.identifierAttribute+"' as identifier");t=e.identifierAttribute}}),t?(this.identifierMode=MapIdentifierMode.YES,this.mapIdentifierAttribute=t):this.identifierMode=MapIdentifierMode.NO}}},e.prototype.initializeChildNodes=function(t,n){void 0===n&&(n={});var r=t.type._subType,i={};return Object.keys(n).forEach(function(e){i[e]=r.instantiate(t,e,void 0,n[e])}),i},e.prototype.createNewInstance=function(e){return new MSTMap(e)},e.prototype.finalizeNewInstance=function(e,t){mobx._interceptReads(t,e.unbox),mobx.intercept(t,this.willChange),mobx.observe(t,this.didChange)},e.prototype.describe=function(){return"Map<string, "+this._subType.describe()+">"},e.prototype.getChildren=function(e){return mobx.values(e.storedValue)},e.prototype.getChildNode=function(e,t){var n=e.storedValue.get(""+t);if(!n)throw fail$1("Not a child "+t);return n},e.prototype.willChange=function(e){var t=getStateTreeNode(e.object),n=e.name;t.assertWritable({subpath:n});var r=t.type,i=r._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(n))return null;typecheckInternal(i,o),e.newValue=i.reconcile(t.getChildNode(n),e.newValue,t,n),r.processIdentifier(n,e.newValue);break;case"add":typecheckInternal(i,e.newValue),e.newValue=i.instantiate(t,n,void 0,e.newValue),r.processIdentifier(n,e.newValue)}return e},e.prototype.processIdentifier=function(e,t){if(this.identifierMode===MapIdentifierMode.YES&&t instanceof ObjectNode){var n=t.identifier;if(n!==e)throw fail$1("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+n+"', but expected: '"+e+"'")}},e.prototype.getSnapshot=function(e){var t={};return e.getChildren().forEach(function(e){t[e.subpath]=e.snapshot}),t},e.prototype.processInitialSnapshot=function(t){var n={};return Object.keys(t).forEach(function(e){n[e]=t[e].getSnapshot()}),n},e.prototype.didChange=function(e){var t=getStateTreeNode(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:escapeJsonPath(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:escapeJsonPath(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var n=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:escapeJsonPath(e.name),oldValue:n},t)}},e.prototype.applyPatchLocally=function(e,t,n){var r=e.storedValue;switch(n.op){case"add":case"replace":r.set(t,n.value);break;case"remove":r.delete(t)}},e.prototype.applySnapshot=function(e,t){typecheckInternal(this,t);var n=e.storedValue,r={};if(Array.from(n.keys()).forEach(function(e){r[e]=!1}),t)for(var i in t)n.set(i,t[i]),r[""+i]=!0;Object.keys(r).forEach(function(e){!1===r[e]&&n.delete(e)})},e.prototype.getChildType=function(){return this._subType},e.prototype.isValidSnapshot=function(t,n){var r=this;return isPlainObject(t)?flattenTypeErrors(Object.keys(t).map(function(e){return r._subType.validate(t[e],getContextForPath(n,e,r._subType))})):typeCheckFailure(n,t,"Value is not a plain object")},e.prototype.getDefaultSnapshot=function(){return EMPTY_OBJECT},e.prototype.removeChild=function(e,t){e.storedValue.delete(t)},__decorate([mobx.action],e.prototype,"applySnapshot",null),e}(ComplexType);function map(e){return new MapType("map<string, "+e.name+">",e)}function isMapType(e){return isType(e)&&0<(e.flags&TypeFlags.Map)}var ArrayType=function(r){function e(e,t){var n=r.call(this,e)||this;return n._subType=t,n.flags=TypeFlags.Array,n}return __extends(e,r),e.prototype.instantiate=function(e,t,n,r){return createObjectNode(this,e,t,n,r)},e.prototype.initializeChildNodes=function(r,e){void 0===e&&(e=[]);var i=r.type._subType,o={};return e.forEach(function(e,t){var n=""+t;o[n]=i.instantiate(r,n,void 0,e)}),o},e.prototype.createNewInstance=function(e){return mobx.observable.array(convertChildNodesToArray(e),mobxShallow)},e.prototype.finalizeNewInstance=function(e,t){mobx._getAdministration(t).dehancer=e.unbox,mobx.intercept(t,this.willChange),mobx.observe(t,this.didChange)},e.prototype.describe=function(){return this._subType.describe()+"[]"},e.prototype.getChildren=function(e){return e.storedValue.slice()},e.prototype.getChildNode=function(e,t){var n=Number(t);if(n<e.storedValue.length)return e.storedValue[n];throw fail$1("Not a child: "+t)},e.prototype.willChange=function(e){var t=getStateTreeNode(e.object);t.assertWritable({subpath:""+e.index});var n=t.type._subType,r=t.getChildren();switch(e.type){case"update":if(e.newValue===e.object[e.index])return null;var i=reconcileArrayChildren(t,n,[r[e.index]],[e.newValue],[e.index]);if(!i)return null;e.newValue=i[0];break;case"splice":var o=e.index,a=e.removedCount,s=e.added,p=reconcileArrayChildren(t,n,r.slice(o,o+a),s,s.map(function(e,t){return o+t}));if(!p)return null;e.added=p;for(var c=o+a;c<r.length;c++)r[c].setParent(t,""+(c+s.length-a))}return e},e.prototype.getSnapshot=function(e){return e.getChildren().map(function(e){return e.snapshot})},e.prototype.processInitialSnapshot=function(t){var n=[];return Object.keys(t).forEach(function(e){n.push(t[e].getSnapshot())}),n},e.prototype.didChange=function(e){var t=getStateTreeNode(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":for(var n=e.removedCount-1;0<=n;n--)t.emitPatch({op:"remove",path:""+(e.index+n),oldValue:e.removed[n].snapshot},t);for(n=0;n<e.addedCount;n++)t.emitPatch({op:"add",path:""+(e.index+n),value:t.getChildNode(""+(e.index+n)).snapshot,oldValue:void 0},t);return}},e.prototype.applyPatchLocally=function(e,t,n){var r=e.storedValue,i="-"===t?r.length:Number(t);switch(n.op){case"replace":r[i]=n.value;break;case"add":r.splice(i,0,n.value);break;case"remove":r.splice(i,1)}},e.prototype.applySnapshot=function(e,t){typecheckInternal(this,t),e.storedValue.replace(t)},e.prototype.getChildType=function(){return this._subType},e.prototype.isValidSnapshot=function(e,n){var r=this;return isArray(e)?flattenTypeErrors(e.map(function(e,t){return r._subType.validate(e,getContextForPath(n,""+t,r._subType))})):typeCheckFailure(n,e,"Value is not an array")},e.prototype.getDefaultSnapshot=function(){return EMPTY_ARRAY},e.prototype.removeChild=function(e,t){e.storedValue.splice(Number(t),1)},__decorate([mobx.action],e.prototype,"applySnapshot",null),e}(ComplexType);function array(e){return assertIsType(e,1),new ArrayType(e.name+"[]",e)}function reconcileArrayChildren(e,t,n,r,i){for(var o=!0,a=0;;a++){var s=a<=r.length-1,p=n[a],c=s?r[a]:void 0,u=""+i[a];if(isNode(c)&&(c=c.storedValue),!p&&!s)break;if(s)if(p)if(areSame(p,c))n[a]=valueAsNode(t,e,u,c,p);else{for(var l=void 0,d=a;d<n.length;d++)if(areSame(n[d],c)){l=n.splice(d,1)[0];break}o=!1;f=valueAsNode(t,e,u,c,l);n.splice(a,0,f)}else{if(isStateTreeNode(c)&&getStateTreeNode(c).parent===e)throw fail$1("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 '"+getStateTreeNode(c).path+"'");o=!1;var f=valueAsNode(t,e,u,c);n.splice(a,0,f)}else o=!1,n.splice(a,1),p instanceof ObjectNode&&p.createObservableInstanceIfNeeded(),p.die(),a--}return o?null:n}function valueAsNode(t,n,r,i,o){typecheckInternal(t,i);var e=function(){if(isStateTreeNode(i)){var e=getStateTreeNode(i);if(e.assertAlive(EMPTY_OBJECT),null!==e.parent&&e.parent===n)return e.setParent(n,r),e}return o?t.reconcile(o,i,n,r):t.instantiate(n,r,void 0,i)}();return o&&o!==e&&(o instanceof ObjectNode&&o.createObservableInstanceIfNeeded(),o.die()),e}function areSame(e,t){if(!e.isAlive)return!1;if(isStateTreeNode(t)){var n=getStateTreeNode(t);return n.isAlive&&n===e}return e.snapshot===t||e instanceof ObjectNode&&null!==e.identifier&&e.identifierAttribute&&isPlainObject(t)&&e.identifier===normalizeIdentifier(t[e.identifierAttribute])&&e.type.is(t)}function isArrayType(e){return isType(e)&&0<(e.flags&TypeFlags.Array)}var PRE_PROCESS_SNAPSHOT="preProcessSnapshot",POST_PROCESS_SNAPSHOT="postProcessSnapshot";function objectTypeToString(){return getStateTreeNode(this).toString()}var defaultObjectOptions={name:"AnonymousModel",properties:{},initializers:EMPTY_ARRAY};function toPropertiesObject(e){return Object.keys(e).reduce(function(e,t){var n,r,i;if(t in Hook)throw fail$1("Hook '"+t+"' was defined as property. Hooks should be defined as part of the actions");var o=Object.getOwnPropertyDescriptor(e,t);if("get"in o)throw fail$1("Getters are not supported as properties. Please use views instead");var a=o.value;if(null==a)throw fail$1("The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?");if(isPrimitive(a))return Object.assign({},e,((n={})[t]=optional(getPrimitiveFactoryFromValue(a),a),n));if(a instanceof MapType)return Object.assign({},e,((r={})[t]=optional(a,{}),r));if(a instanceof ArrayType)return Object.assign({},e,((i={})[t]=optional(a,[]),i));if(isType(a))return e;throw"production"!==production&&"function"==typeof a?fail$1("Invalid type definition for property '"+t+"', it looks like you passed a function. Did you forget to invoke it, or did you intend to declare a view / action?"):"production"!==production&&"object"==typeof a?fail$1("Invalid type definition for property '"+t+"', it looks like you passed an object. Try passing another model type or a types.frozen."):fail$1("Invalid type definition for property '"+t+"', cannot infer a type from a value like '"+a+"' ("+typeof a+")")},e)}var ModelType=function(n){function t(e){var r=n.call(this,e.name||defaultObjectOptions.name)||this;r.flags=TypeFlags.Object,r.named=function(e){return r.cloneAndEnhance({name:e})},r.props=function(e){return r.cloneAndEnhance({properties:e})},r.preProcessSnapshot=function(t){var n=r.preProcessor;return n?r.cloneAndEnhance({preProcessor:function(e){return n(t(e))}}):r.cloneAndEnhance({preProcessor:t})},r.postProcessSnapshot=function(t){var n=r.postProcessor;return n?r.cloneAndEnhance({postProcessor:function(e){return t(n(e))}}):r.cloneAndEnhance({postProcessor:t})};var t=e.name||defaultObjectOptions.name;if(!/^\w[\w\d_]*$/.test(t))throw fail$1("Typename should be a valid identifier: "+t);return Object.assign(r,defaultObjectOptions,e),r.properties=toPropertiesObject(r.properties),freeze(r.properties),r.propertyNames=Object.keys(r.properties),r.identifierAttribute=r._getIdentifierAttribute(),r}return __extends(t,n),t.prototype._getIdentifierAttribute=function(){var n=void 0;return this.forAllProps(function(e,t){if(t.flags&TypeFlags.Identifier){if(n)throw fail$1("Cannot define property '"+e+"' as object identifier, property '"+n+"' is already defined as identifier property");n=e}}),n},t.prototype.cloneAndEnhance=function(e){return new t({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})},t.prototype.actions=function(t){var n=this;return this.cloneAndEnhance({initializers:[function(e){return n.instantiateActions(e,t(e)),e}]})},t.prototype.instantiateActions=function(s,p){if(!isPlainObject(p))throw fail$1("actions initializer should return a plain object containing actions");Object.keys(p).forEach(function(e){if(e===PRE_PROCESS_SNAPSHOT)throw fail$1("Cannot define action '"+PRE_PROCESS_SNAPSHOT+"', it should be defined using 'type.preProcessSnapshot(fn)' instead");if(e===POST_PROCESS_SNAPSHOT)throw fail$1("Cannot define action '"+POST_PROCESS_SNAPSHOT+"', it should be defined using 'type.postProcessSnapshot(fn)' instead");var t=p[e],n=s[e];if(e in Hook&&n){var r=t;t=function(){n.apply(null,arguments),r.apply(null,arguments)}}var i=t.$mst_middleware,o=t.bind(p);o.$mst_middleware=i;var a=createActionInvoker(s,e,o);p[e]=a,("production"===production?addHiddenFinalProp:addHiddenWritableProp)(s,e,a)})},t.prototype.volatile=function(t){var n=this;return this.cloneAndEnhance({initializers:[function(e){return n.instantiateVolatileState(e,t(e)),e}]})},t.prototype.instantiateVolatileState=function(e,t){if(!isPlainObject(t))throw fail$1("volatile state initializer should return a plain object containing state");mobx.set(e,t)},t.prototype.extend=function(s){var p=this;return this.cloneAndEnhance({initializers:[function(e){var t=s(e),n=t.actions,r=t.views,i=t.state,o=__rest(t,["actions","views","state"]);for(var a in o)throw fail$1("The `extend` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '"+a+"'");return i&&p.instantiateVolatileState(e,i),r&&p.instantiateViews(e,r),n&&p.instantiateActions(e,n),e}]})},t.prototype.views=function(t){var n=this;return this.cloneAndEnhance({initializers:[function(e){return n.instantiateViews(e,t(e)),e}]})},t.prototype.instantiateViews=function(i,o){if(!isPlainObject(o))throw fail$1("views initializer should return a plain object containing views");Object.keys(o).forEach(function(e){var t=Object.getOwnPropertyDescriptor(o,e),n=t.value;if("get"in t)if(mobx.isComputedProp(i,e)){var r=mobx._getAdministration(i,e);r.derivation=t.get,r.scope=i,t.set&&(r.setter=mobx.action(r.name+"-setter",t.set))}else mobx.computed(i,e,t,!0);else{if("function"!=typeof n)throw fail$1("A view member should either be a function or getter based property");("production"===production?addHiddenFinalProp:addHiddenWritableProp)(i,e,n)}})},t.prototype.instantiate=function(e,t,n,r){return createObjectNode(this,e,t,n,isStateTreeNode(r)?r:this.applySnapshotPreProcessor(r))},t.prototype.initializeChildNodes=function(n,r){void 0===r&&(r={});var e=n.type,i={};return e.forAllProps(function(e,t){i[e]=t.instantiate(n,e,void 0,r[e])}),i},t.prototype.createNewInstance=function(e){return mobx.observable.object(e,EMPTY_OBJECT,mobxShallow)},t.prototype.finalizeNewInstance=function(t,n){addHiddenFinalProp(n,"toString",objectTypeToString),this.forAllProps(function(e){mobx._interceptReads(n,e,t.unbox)}),this.initializers.reduce(function(e,t){return t(e)},n),mobx.intercept(n,this.willChange),mobx.observe(n,this.didChange)},t.prototype.willChange=function(e){var t=e,n=getStateTreeNode(t.object),r=t.name;n.assertWritable({subpath:r});var i=n.type.properties[r];return i&&(typecheckInternal(i,t.newValue),t.newValue=i.reconcile(n.getChildNode(r),t.newValue,n,r)),t},t.prototype.didChange=function(e){var t=e,n=getStateTreeNode(t.object);if(n.type.properties[t.name]){var r=t.oldValue?t.oldValue.snapshot:void 0;n.emitPatch({op:"replace",path:escapeJsonPath(t.name),value:t.newValue.snapshot,oldValue:r},n)}},t.prototype.getChildren=function(t){var n=this,r=[];return this.forAllProps(function(e){r.push(n.getChildNode(t,e))}),r},t.prototype.getChildNode=function(e,t){if(!(t in this.properties))throw fail$1("Not a value property: "+t);var n=mobx._getAdministration(e.storedValue,t).value;if(!n)throw fail$1("Node not available for property "+t);return n},t.prototype.getSnapshot=function(n,e){var r=this;void 0===e&&(e=!0);var i={};return this.forAllProps(function(e,t){mobx.getAtom(n.storedValue,e).reportObserved(),i[e]=r.getChildNode(n,e).snapshot}),e?this.applySnapshotPostProcessor(i):i},t.prototype.processInitialSnapshot=function(t){var n={};return Object.keys(t).forEach(function(e){n[e]=t[e].getSnapshot()}),this.applySnapshotPostProcessor(n)},t.prototype.applyPatchLocally=function(e,t,n){if("replace"!==n.op&&"add"!==n.op)throw fail$1("object does not support operation "+n.op);e.storedValue[t]=n.value},t.prototype.applySnapshot=function(t,e){var n=this.applySnapshotPreProcessor(e);typecheckInternal(this,n),this.forAllProps(function(e){t.storedValue[e]=n[e]})},t.prototype.applySnapshotPreProcessor=function(e){var t=this.preProcessor;return t?t.call(null,e):e},t.prototype.applySnapshotPostProcessor=function(e){var t=this.postProcessor;return t?t.call(null,e):e},t.prototype.getChildType=function(e){if("production"!==production&&null==e)throw fail$1("getChildType requires a property name when used over a model type");return this.properties[e]},t.prototype.isValidSnapshot=function(e,t){var n=this,r=this.applySnapshotPreProcessor(e);return isPlainObject(r)?flattenTypeErrors(this.propertyNames.map(function(e){return n.properties[e].validate(r[e],getContextForPath(t,e,n.properties[e]))})):typeCheckFailure(t,r,"Value is not a plain object")},t.prototype.forAllProps=function(t){var n=this;this.propertyNames.forEach(function(e){return t(e,n.properties[e])})},t.prototype.describe=function(){var t=this;return"{ "+this.propertyNames.map(function(e){return e+": "+t.properties[e].describe()}).join("; ")+" }"},t.prototype.getDefaultSnapshot=function(){return EMPTY_OBJECT},t.prototype.removeChild=function(e,t){e.storedValue[t]=void 0},__decorate([mobx.action],t.prototype,"applySnapshot",null),t}(ComplexType);function model(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="string"==typeof e[0]?e.shift():"AnonymousModel",r=e.shift()||{};return new ModelType({name:n,properties:r})}function compose(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="string"==typeof e[0]?e.shift():"AnonymousModel";return"production"!==production&&e.forEach(function(e){if(!isModelType(e))throw fail$1("expected a mobx-state-tree model type, got "+e+" instead")}),e.reduce(function(t,n){return t.cloneAndEnhance({name:t.name+"_"+n.name,properties:n.properties,initializers:n.initializers,preProcessor:function(e){return n.applySnapshotPreProcessor(t.applySnapshotPreProcessor(e))},postProcessor:function(e){return n.applySnapshotPostProcessor(t.applySnapshotPostProcessor(e))}})}).named(n)}function isModelType(e){return isType(e)&&0<(e.flags&TypeFlags.Object)}var CoreType=function(o){function e(e,t,n,r){void 0===r&&(r=identity);var i=o.call(this,e)||this;return i.flags=t,i.checker=n,i.initializer=r,i.flags=t,i}return __extends(e,o),e.prototype.describe=function(){return this.name},e.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,r)},e.prototype.createNewInstance=function(e){return this.initializer(e)},e.prototype.isValidSnapshot=function(e,t){return isPrimitive(e)&&this.checker(e)?typeCheckSuccess():typeCheckFailure(t,e,"Value is not a "+("Date"===this.name?"Date or a unix milliseconds timestamp":this.name))},e}(SimpleType),string=new CoreType("string",TypeFlags.String,function(e){return"string"==typeof e}),number=new CoreType("number",TypeFlags.Number,function(e){return"number"==typeof e}),integer=new CoreType("integer",TypeFlags.Integer,function(e){return isInteger(e)}),boolean=new CoreType("boolean",TypeFlags.Boolean,function(e){return"boolean"==typeof e}),nullType=new CoreType("null",TypeFlags.Null,function(e){return null===e}),undefinedType=new CoreType("undefined",TypeFlags.Undefined,function(e){return void 0===e}),_DatePrimitive=new CoreType("Date",TypeFlags.Date,function(e){return"number"==typeof e||e instanceof Date},function(e){return e instanceof Date?e:new Date(e)});_DatePrimitive.getSnapshot=function(e){return e.storedValue.getTime()};var DatePrimitive=_DatePrimitive;function getPrimitiveFactoryFromValue(e){switch(typeof e){case"string":return string;case"number":return number;case"boolean":return boolean;case"object":if(e instanceof Date)return DatePrimitive}throw fail$1("Cannot determine primitive type from value "+e)}function isPrimitiveType(e){return isType(e)&&0<(e.flags&(TypeFlags.String|TypeFlags.Number|TypeFlags.Integer|TypeFlags.Boolean|TypeFlags.Date))}var Literal=function(n){function e(e){var t=n.call(this,JSON.stringify(e))||this;return t.flags=TypeFlags.Literal,t.value=e,t}return __extends(e,n),e.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,r)},e.prototype.describe=function(){return JSON.stringify(this.value)},e.prototype.isValidSnapshot=function(e,t){return isPrimitive(e)&&e===this.value?typeCheckSuccess():typeCheckFailure(t,e,"Value is not a literal "+JSON.stringify(this.value))},e}(SimpleType);function literal(e){if("production"!==production&&!isPrimitive(e))throw fail$1("Literal types can be built only on top of primitives");return new Literal(e)}function isLiteralType(e){return isType(e)&&0<(e.flags&TypeFlags.Literal)}var Refinement=function(o){function e(e,t,n,r){var i=o.call(this,e)||this;return i._subtype=t,i._predicate=n,i._message=r,i}return __extends(e,o),Object.defineProperty(e.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.Refinement},enumerable:!0,configurable:!0}),e.prototype.describe=function(){return this.name},e.prototype.instantiate=function(e,t,n,r){return this._subtype.instantiate(e,t,n,r)},e.prototype.isAssignableFrom=function(e){return this._subtype.isAssignableFrom(e)},e.prototype.isValidSnapshot=function(e,t){var n=this._subtype.validate(e,t);if(0<n.length)return n;var r=isStateTreeNode(e)?getStateTreeNode(e).snapshot:e;return this._predicate(r)?typeCheckSuccess():typeCheckFailure(t,e,this._message(e))},e.prototype.reconcile=function(e,t,n,r){return this._subtype.reconcile(e,t,n,r)},e.prototype.getSubTypes=function(){return this._subtype},e}(BaseType);function refinement(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="string"==typeof e[0]?e.shift():isType(e[0])?e[0].name:null,r=e[0],i=e[1],o=e[2]?e[2]:function(e){return"Value does not respect the refinement predicate"};if(assertIsType(r,1),"production"!==production){if("string"!=typeof n)throw fail$1("expected a string as first argument, got "+n+" instead");if("function"!=typeof i)throw fail$1("expected a function as third argument, got "+i+" instead");if("function"!=typeof o)throw fail$1("expected a function as fourth argument, got "+o+" instead")}return new Refinement(n,r,i,o)}function isRefinementType(e){return 0<(e.flags&TypeFlags.Refinement)}function enumeration(e,t){var n="string"==typeof e?t:e;"production"!==production&&n.forEach(function(e){if("string"!=typeof e)throw fail$1("expected all options to be string, got "+r+" instead")});var r=union.apply(void 0,__spread(n.map(function(e){return literal(""+e)})));return"string"==typeof e&&(r.name=e),r}var Union=function(i){function e(e,t,n){var r=i.call(this,e)||this;return r._types=t,r._eager=!0,n=__assign({eager:!0,dispatcher:void 0},n),r._dispatcher=n.dispatcher,n.eager||(r._eager=!1),r}return __extends(e,i),Object.defineProperty(e.prototype,"flags",{get:function(){var t=TypeFlags.Union;return this._types.forEach(function(e){t|=e.flags}),t},enumerable:!0,configurable:!0}),e.prototype.isAssignableFrom=function(t){return this._types.some(function(e){return e.isAssignableFrom(t)})},e.prototype.describe=function(){return"("+this._types.map(function(e){return e.describe()}).join(" | ")+")"},e.prototype.instantiate=function(e,t,n,r){var i=this.determineType(r,void 0);if(!i)throw fail$1("No matching type for union "+this.describe());return i.instantiate(e,t,n,r)},e.prototype.reconcile=function(e,t,n,r){var i=this.determineType(t,e.type);if(!i)throw fail$1("No matching type for union "+this.describe());return i.reconcile(e,t,n,r)},e.prototype.determineType=function(t,n){return this._dispatcher?this._dispatcher(t):n?n.is(t)?n:this._types.filter(function(e){return e!==n}).find(function(e){return e.is(t)}):this._types.find(function(e){return e.is(t)})},e.prototype.isValidSnapshot=function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var n=[],r=0,i=0;i<this._types.length;i++){var o=this._types[i].validate(e,t);if(0===o.length){if(this._eager)return typeCheckSuccess();r++}else n.push(o)}return 1===r?typeCheckSuccess():typeCheckFailure(t,e,"No type is applicable for the union").concat(flattenTypeErrors(n))},e.prototype.getSubTypes=function(){return this._types},e}(BaseType);function union(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r=isType(e)?void 0:e,i=isType(e)?__spread([e],t):t,o="("+i.map(function(e){return e.name}).join(" | ")+")";if("production"!==production){if(!isType(e)&&!isPlainObject(e))throw fail$1("First argument to types.union should either be a type, or an objects object of the form: { eager?: boolean, dispatcher?: Function }");i.forEach(function(e){if(!isType(e))throw fail$1("expected all possible types to be a mobx-state-tree type, got "+e+" instead")})}return new Union(o,i,r)}function isUnionType(e){return 0<(e.flags&TypeFlags.Union)}var OptionalValue=function(i){function e(e,t,n){var r=i.call(this,e.name)||this;return r._subtype=e,r._defaultValue=t,r.optionalValues=n,r}return __extends(e,i),Object.defineProperty(e.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.Optional},enumerable:!0,configurable:!0}),e.prototype.describe=function(){return this._subtype.describe()+"?"},e.prototype.instantiate=function(e,t,n,r){if(0<=this.optionalValues.indexOf(r)){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,n,i)}return this._subtype.instantiate(e,t,n,r)},e.prototype.reconcile=function(e,t,n,r){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),n,r)},e.prototype.getDefaultInstanceOrSnapshot=function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&typecheckInternal(this,e),e},e.prototype.isValidSnapshot=function(e,t){return 0<=this.optionalValues.indexOf(e)?typeCheckSuccess():this._subtype.validate(e,t)},e.prototype.isAssignableFrom=function(e){return this._subtype.isAssignableFrom(e)},e.prototype.getSubTypes=function(){return this._subtype},e}(BaseType);function checkOptionalPreconditions(e,t){if("function"!=typeof t&&isStateTreeNode(t))throw fail$1("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead");assertIsType(e,1),"production"!==production&&"function"!=typeof t&&typecheckInternal(e,t)}function optional(e,t,n){return checkOptionalPreconditions(e,t),new OptionalValue(e,t,n||undefinedAsOptionalValues)}var undefinedAsOptionalValues=[void 0];function isOptionalType(e){return isType(e)&&0<(e.flags&TypeFlags.Optional)}var optionalUndefinedType=optional(undefinedType,void 0),optionalNullType=optional(nullType,null);function maybe(e){return assertIsType(e,1),union(e,optionalUndefinedType)}function maybeNull(e){return assertIsType(e,1),union(e,optionalNullType)}var Late=function(r){function e(e,t){var n=r.call(this,e)||this;return n._definition=t,n}return __extends(e,r),Object.defineProperty(e.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|TypeFlags.Late},enumerable:!0,configurable:!0}),e.prototype.getSubType=function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw fail$1("Late type seems to be used too early, the definition (still) returns undefined");if(t){if("production"!==production&&!isType(t))throw fail$1("Failed to determine subtype, make sure types.late returns a type definition.");this._subType=t}}return this._subType},e.prototype.instantiate=function(e,t,n,r){return this.getSubType(!0).instantiate(e,t,n,r)},e.prototype.reconcile=function(e,t,n,r){return this.getSubType(!0).reconcile(e,t,n,r)},e.prototype.describe=function(){var e=this.getSubType(!1);return e?e.name:"<uknown late type>"},e.prototype.isValidSnapshot=function(e,t){var n=this.getSubType(!1);return n?n.validate(e,t):typeCheckSuccess()},e.prototype.isAssignableFrom=function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)},e.prototype.getSubTypes=function(){var e=this.getSubType(!1);return e||cannotDetermineSubtype},e}(BaseType);function late(e,t){var n="string"==typeof e?e:"late("+e.toString()+")",r="string"==typeof e?t:e;if("production"!==production&&("function"!=typeof r||0!==r.length))throw fail$1("Invalid late type, expected a function with zero arguments that returns a type, got: "+r);return new Late(n,r)}function isLateType(e){return isType(e)&&0<(e.flags&TypeFlags.Late)}var Frozen=function(n){function e(e){var t=n.call(this,e?"frozen("+e.name+")":"frozen")||this;return t.subType=e,t.flags=TypeFlags.Frozen,t}return __extends(e,n),e.prototype.describe=function(){return"<any immutable value>"},e.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,deepFreeze(r))},e.prototype.isValidSnapshot=function(e,t){return isSerializable(e)?this.subType?this.subType.validate(e,t):typeCheckSuccess():typeCheckFailure(t,e,"Value is not serializable and cannot be frozen")},e}(SimpleType),untypedFrozenInstance=new Frozen;function frozen(e){return 0===arguments.length?untypedFrozenInstance:isType(e)?new Frozen(e):optional(untypedFrozenInstance,e)}function isFrozenType(e){return isType(e)&&0<(e.flags&TypeFlags.Frozen)}function getInvalidationCause(e){switch(e){case Hook.beforeDestroy:return"destroy";case Hook.beforeDetach:return"detach";default:return}}var StoredReference=function(){function e(e,t){if(this.targetType=t,isValidIdentifier(e))this.identifier=e;else{if(!isStateTreeNode(e))throw fail$1("Can only store references to tree nodes or identifiers, got: '"+e+"'");var n=getStateTreeNode(e);if(!n.identifierAttribute)throw fail$1("Can only store references with a defined identifier attribute.");var r=n.unnormalizedIdentifier;if(null==r)throw fail$1("Can only store references to tree nodes with a defined identifier.");this.identifier=r}}return e.prototype.updateResolvedReference=function(e){var t=normalizeIdentifier(this.identifier),n=e.root,r=n.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==r){var i=this.targetType,o=n.identifierCache.resolve(i,t);if(!o)throw new InvalidReferenceError("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:r}}},Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!0,configurable:!0}),e}(),InvalidReferenceError=function(n){function r(e){var t=n.call(this,e)||this;return Object.setPrototypeOf(t,r.prototype),t}return __extends(r,n),r}(Error),BaseReferenceType=function(r){function e(e,t){var n=r.call(this,"reference("+e.name+")")||this;return n.targetType=e,n.onInvalidated=t,n.flags=TypeFlags.Reference,n}return __extends(e,r),e.prototype.describe=function(){return this.name},e.prototype.isAssignableFrom=function(e){return this.targetType.isAssignableFrom(e)},e.prototype.isValidSnapshot=function(e,t){return isValidIdentifier(e)?typeCheckSuccess():typeCheckFailure(t,e,"Value is not a valid identifier, which is a string or a number")},e.prototype.fireInvalidated=function(e,t,n,r){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:r?r.storedValue:void 0,invalidId:n,replaceRef:function(e){applyPatch(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){isModelType(i.type)?this.replaceRef(void 0):applyPatch(t.root.storedValue,{op:"remove",path:t.path})}})}},e.prototype.addTargetNodeWatcher=function(r,i){var o=this,e=this.getValue(r);if(e){var a=getStateTreeNode(e),t=function(e,t){var n=getInvalidationCause(t);n&&o.fireInvalidated(n,r,i,a)},n=a.registerHook(Hook.beforeDetach,t),s=a.registerHook(Hook.beforeDestroy,t);return function(){n(),s()}}},e.prototype.watchTargetNodeForInvalidations=function(r,i,o){var a=this;if(this.onInvalidated){var s;r.registerHook(Hook.beforeDestroy,function(){s&&s()});var e=function(e){s&&s();var t=r.parent,n=t&&t.storedValue;if(t&&t.isAlive&&n){(o?!!o.get(i,n):r.root.identifierCache.has(a.targetType,normalizeIdentifier(i)))?s=a.addTargetNodeWatcher(r,i):e||a.fireInvalidated("invalidSnapshotReference",r,i,null)}};r.state===NodeLifeCycle.FINALIZED?e(!0):(r.isRoot||r.root.registerHook(Hook.afterCreationFinalization,function(){r.parent&&r.parent.createObservableInstanceIfNeeded()}),r.registerHook(Hook.afterAttach,function(){e(!1)}))}},e}(SimpleType),IdentifierReferenceType=function(n){function e(e,t){return n.call(this,e,t)||this}return __extends(e,n),e.prototype.getValue=function(e){if(e.isAlive)return e.storedValue.resolvedValue},e.prototype.getSnapshot=function(e){return e.storedValue.identifier},e.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?getIdentifier(r):r,o=new StoredReference(r,this.targetType),a=createScalarNode(this,e,t,n,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a},e.prototype.reconcile=function(e,t,n,r){if(!e.isDetaching&&e.type===this){var i=isStateTreeNode(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(n,r),e}var a=this.instantiate(n,r,void 0,t);return e.die(),a},e}(BaseReferenceType),CustomReferenceType=function(i){function e(e,t,n){var r=i.call(this,e,n)||this;return r.options=t,r}return __extends(e,i),e.prototype.getValue=function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)},e.prototype.getSnapshot=function(e){return e.storedValue},e.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?this.options.set(r,e?e.storedValue:null):r,o=createScalarNode(this,e,t,n,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o},e.prototype.reconcile=function(e,t,n,r){var i=isStateTreeNode(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(n,r),e;var o=this.instantiate(n,r,void 0,i);return e.die(),o},e}(BaseReferenceType);function reference(e,t){if(assertIsType(e,1),"production"!==production&&2===arguments.length&&"string"==typeof t)throw fail$1("References with base path are no longer supported. Please remove the base path.");var n=t||void 0,r=t?t.onInvalidated:void 0;if(n&&(n.get||n.set)){if(!("production"===production||n.get&&n.set))throw fail$1("reference options must either contain both a 'get' and a 'set' method or none of them");return new CustomReferenceType(e,{get:n.get,set:n.set},r)}return new IdentifierReferenceType(e,r)}function isReferenceType(e){return 0<(e.flags&TypeFlags.Reference)}function safeReference(e,t){return maybe(reference(e,__assign({},t,{onInvalidated:function(e){e.removeRef()}})))}var BaseIdentifierType=function(r){function e(e,t){var n=r.call(this,e)||this;return n.validType=t,n.flags=TypeFlags.Identifier,n}return __extends(e,r),e.prototype.instantiate=function(e,t,n,r){if(!(e&&e.type instanceof ModelType))throw fail$1("Identifier types can only be instantiated as direct child of a model type");return createScalarNode(this,e,t,n,r)},e.prototype.reconcile=function(e,t,n,r){if(e.storedValue!==t)throw fail$1("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(n,r),e},e.prototype.isValidSnapshot=function(e,t){return typeof e!==this.validType?typeCheckFailure(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):typeCheckSuccess()},e}(SimpleType),IdentifierType=function(t){function e(){var e=t.call(this,"identifier","string")||this;return e.flags=TypeFlags.Identifier,e}return __extends(e,t),e.prototype.describe=function(){return"identifier"},e}(BaseIdentifierType),IdentifierNumberType=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return __extends(t,e),t.prototype.getSnapshot=function(e){return e.storedValue},t.prototype.describe=function(){return"identifierNumber"},t}(BaseIdentifierType),identifier=new IdentifierType,identifierNumber=new IdentifierNumberType;function isIdentifierType(e){return isType(e)&&0<(e.flags&TypeFlags.Identifier)}function normalizeIdentifier(e){return""+e}function isValidIdentifier(e){return"string"==typeof e||"number"==typeof e}function custom(e){return new CustomType(e)}var CustomType=function(n){function e(e){var t=n.call(this,e.name)||this;return t.options=e,t.flags=TypeFlags.Custom,t}return __extends(e,n),e.prototype.describe=function(){return this.name},e.prototype.isValidSnapshot=function(e,t){if(this.options.isTargetType(e))return typeCheckSuccess();var n=this.options.getValidationMessage(e);return n?typeCheckFailure(t,e,"Invalid value for type '"+this.name+"': "+n):typeCheckSuccess()},e.prototype.getSnapshot=function(e){return this.options.toSnapshot(e.storedValue)},e.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,this.options.isTargetType(r)?r:this.options.fromSnapshot(r))},e.prototype.reconcile=function(e,t,n,r){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(n,r),e;var o=i?this.options.fromSnapshot(t):t,a=this.instantiate(n,r,void 0,o);return e.die(),a},e}(SimpleType),types={enumeration:enumeration,model:model,compose:compose,custom:custom,reference:reference,safeReference:safeReference,union:union,optional:optional,literal:literal,maybe:maybe,maybeNull:maybeNull,refinement:refinement,string:string,boolean:boolean,number:number,integer:integer,Date:DatePrimitive,map:map,array:array,frozen:frozen,identifier:identifier,identifierNumber:identifierNumber,late:late,undefined:undefinedType,null:nullType,snapshotProcessor:snapshotProcessor};exports.typecheck=typecheck,exports.escapeJsonPath=escapeJsonPath,exports.unescapeJsonPath=unescapeJsonPath,exports.joinJsonPath=joinJsonPath,exports.splitJsonPath=splitJsonPath,exports.decorate=decorate,exports.addMiddleware=addMiddleware,exports.process=process,exports.isStateTreeNode=isStateTreeNode,exports.flow=flow,exports.castFlowReturn=castFlowReturn,exports.applyAction=applyAction,exports.onAction=onAction,exports.recordActions=recordActions,exports.createActionTrackingMiddleware=createActionTrackingMiddleware,exports.setLivelinessChecking=setLivelinessChecking,exports.getLivelinessChecking=getLivelinessChecking,exports.setLivelynessChecking=setLivelynessChecking,exports.getType=getType,exports.getChildType=getChildType,exports.onPatch=onPatch,exports.onSnapshot=onSnapshot,exports.applyPatch=applyPatch,exports.recordPatches=recordPatches,exports.protect=protect,exports.unprotect=unprotect,exports.isProtected=isProtected,exports.applySnapshot=applySnapshot,exports.getSnapshot=getSnapshot,exports.hasParent=hasParent,exports.getParent=getParent,exports.hasParentOfType=hasParentOfType,exports.getParentOfType=getParentOfType,exports.getRoot=getRoot,exports.getPath=getPath,exports.getPathParts=getPathParts,exports.isRoot=isRoot,exports.resolvePath=resolvePath,exports.resolveIdentifier=resolveIdentifier,exports.getIdentifier=getIdentifier,exports.tryResolve=tryResolve,exports.getRelativePath=getRelativePath,exports.clone=clone,exports.detach=detach,exports.destroy=destroy,exports.isAlive=isAlive,exports.addDisposer=addDisposer,exports.getEnv=getEnv,exports.walk=walk,exports.getMembers=getMembers,exports.getPropertyMembers=getPropertyMembers,exports.cast=cast,exports.castToSnapshot=castToSnapshot,exports.castToReferenceSnapshot=castToReferenceSnapshot,exports.isType=isType,exports.isArrayType=isArrayType,exports.isFrozenType=isFrozenType,exports.isIdentifierType=isIdentifierType,exports.isLateType=isLateType,exports.isLiteralType=isLiteralType,exports.isMapType=isMapType,exports.isModelType=isModelType,exports.isOptionalType=isOptionalType,exports.isPrimitiveType=isPrimitiveType,exports.isReferenceType=isReferenceType,exports.isRefinementType=isRefinementType,exports.isUnionType=isUnionType,exports.tryReference=tryReference,exports.isValidReference=isValidReference,exports.getNodeId=getNodeId,exports.types=types;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var Hook,mobx=require("mobx"),livelinessChecking="warn";function setLivelinessChecking(e){livelinessChecking=e}function getLivelinessChecking(){return livelinessChecking}function setLivelynessChecking(e){setLivelinessChecking(e)}!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Hook||(Hook={}));
2
+ /*! *****************************************************************************
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
+ this file except in compliance with the License. You may obtain a copy of the
6
+ License at http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
9
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
10
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
11
+ MERCHANTABLITY OR NON-INFRINGEMENT.
12
+
13
+ See the Apache Version 2.0 License for specific language governing permissions
14
+ and limitations under the License.
15
+ ***************************************************************************** */
16
+ var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function __rest(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function __decorate(e,t,n,r){var i,o=arguments.length,a=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,n,a):i(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function __read(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}function getType(e){return getStateTreeNode(e).type}function getChildType(e,t){return getStateTreeNode(e).getChildType(t)}function onPatch(e,t){return getStateTreeNode(e).onPatch(t)}function onSnapshot(e,t){return getStateTreeNode(e).onSnapshot(t)}function applyPatch(e,t){getStateTreeNode(e).applyPatches(asArray(t))}function recordPatches(e,t){var n,r={patches:[],reversedInversePatches:[]},i={},o={get recording(){return!!n},get patches(){return i.patches||(i.patches=r.patches.slice()),i.patches},get reversedInversePatches(){return i.reversedInversePatches||(i.reversedInversePatches=r.reversedInversePatches.slice()),i.reversedInversePatches},get inversePatches(){return i.inversePatches||(i.inversePatches=r.reversedInversePatches.slice().reverse()),i.inversePatches},stop:function(){n&&(n(),n=void 0)},resume:function(){n||(n=onPatch(e,(function(e,n){t&&!t(e,n,getRunningActionContext())||(r.patches.push(e),r.reversedInversePatches.unshift(n),i.patches=void 0,i.inversePatches=void 0,i.reversedInversePatches=void 0)})))},replay:function(t){applyPatch(t||e,r.patches)},undo:function(t){applyPatch(t||e,r.reversedInversePatches)}};return o.resume(),o}function protect(e){var t=getStateTreeNode(e);if(!t.isRoot)throw fail("`protect` can only be invoked on root nodes");t.isProtectionEnabled=!0}function unprotect(e){var t=getStateTreeNode(e);if(!t.isRoot)throw fail("`unprotect` can only be invoked on root nodes");t.isProtectionEnabled=!1}function isProtected(e){return getStateTreeNode(e).isProtected}function applySnapshot(e,t){return getStateTreeNode(e).applySnapshot(t)}function getSnapshot(e,t){void 0===t&&(t=!0);var n=getStateTreeNode(e);return t?n.snapshot:freeze(n.type.getSnapshot(n,!1))}function hasParent(e,t){void 0===t&&(t=1);for(var n=getStateTreeNode(e).parent;n;){if(0==--t)return!0;n=n.parent}return!1}function getParent(e,t){void 0===t&&(t=1);for(var n=t,r=getStateTreeNode(e).parent;r;){if(0==--n)return r.storedValue;r=r.parent}throw fail("Failed to find the parent of "+getStateTreeNode(e)+" at depth "+t)}function hasParentOfType(e,t){for(var n=getStateTreeNode(e).parent;n;){if(t.is(n.storedValue))return!0;n=n.parent}return!1}function getParentOfType(e,t){for(var n=getStateTreeNode(e).parent;n;){if(t.is(n.storedValue))return n.storedValue;n=n.parent}throw fail("Failed to find the parent of "+getStateTreeNode(e)+" of a given type")}function getRoot(e){return getStateTreeNode(e).root.storedValue}function getPath(e){return getStateTreeNode(e).path}function getPathParts(e){return splitJsonPath(getStateTreeNode(e).path)}function isRoot(e){return getStateTreeNode(e).isRoot}function resolvePath(e,t){var n=resolveNodeByPath(getStateTreeNode(e),t);return n?n.value:void 0}function resolveIdentifier(e,t,n){var r=getStateTreeNode(t).root.identifierCache.resolve(e,normalizeIdentifier(n));return r?r.value:void 0}function getIdentifier(e){return getStateTreeNode(e).identifier}function tryReference(e,t){void 0===t&&(t=!0);try{var n=e();if(null==n)return;if(isStateTreeNode(n))return t?isAlive(n)?n:void 0:n;throw fail("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof InvalidReferenceError)return;throw e}}function isValidReference(e,t){void 0===t&&(t=!0);try{var n=e();if(null==n)return!1;if(isStateTreeNode(n))return!t||isAlive(n);throw fail("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof InvalidReferenceError)return!1;throw e}}function tryResolve(e,t){var n=resolveNodeByPath(getStateTreeNode(e),t,!1);if(void 0!==n)try{return n.value}catch(e){return}}function getRelativePath(e,t){return getRelativePathBetweenNodes(getStateTreeNode(e),getStateTreeNode(t))}function clone(e,t){void 0===t&&(t=!0);var n=getStateTreeNode(e);return n.type.create(n.snapshot,!0===t?n.root.environment:!1===t?void 0:t)}function detach(e){return getStateTreeNode(e).detach(),e}function destroy(e){var t=getStateTreeNode(e);t.isRoot?t.die():t.parent.removeChild(t.subpath)}function isAlive(e){return getStateTreeNode(e).observableIsAlive}function addDisposer(e,t){return getStateTreeNode(e).addDisposer(t),t}function getEnv(e){var t=getStateTreeNode(e).root.environment;return t||EMPTY_OBJECT}function walk(e,t){var n=getStateTreeNode(e);n.getChildren().forEach((function(e){isStateTreeNode(e.storedValue)&&walk(e.storedValue,t)})),t(n.storedValue)}function getPropertyMembers(e){var t;return{name:(t=isStateTreeNode(e)?getType(e):e).name,properties:__assign({},t.properties)}}function getMembers(e){var t=getStateTreeNode(e).type,n=__assign(__assign({},getPropertyMembers(t)),{actions:[],volatile:[],views:[]});return Object.getOwnPropertyNames(e).forEach((function(t){if(!(t in n.properties)){var r=Object.getOwnPropertyDescriptor(e,t);r.get?mobx.isComputedProp(e,t)?n.views.push(t):n.volatile.push(t):!0===r.value._isMSTAction?n.actions.push(t):mobx.isObservableProp(e,t)?n.volatile.push(t):n.views.push(t)}})),n}function cast(e){return e}function castToSnapshot(e){return e}function castToReferenceSnapshot(e){return e}function getNodeId(e){return getStateTreeNode(e).nodeId}var TypeFlags,BaseNode=function(){function e(e,t,n,r){this.type=e,this.environment=r,this._state=NodeLifeCycle.INITIALIZING,this.environment=r,this.baseSetParent(t,n)}return Object.defineProperty(e.prototype,"subpath",{get:function(){return this._subpath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"subpathUponDeath",{get:function(){return this._subpathUponDeath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pathUponDeath",{get:function(){return this._pathUponDeath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.type.getValue(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},set:function(e){var t=this.isAlive;this._state=e;var n=this.isAlive;this.aliveAtom&&t!==n&&this.aliveAtom.reportChanged()},enumerable:!0,configurable:!0}),e.prototype.fireInternalHook=function(e){this._hookSubscribers&&this._hookSubscribers.emit(e,this,e)},e.prototype.registerHook=function(e,t){return this._hookSubscribers||(this._hookSubscribers=new EventHandlers),this._hookSubscribers.register(e,t)},Object.defineProperty(e.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),e.prototype.baseSetParent=function(e,t){this._parent=e,this._subpath=t,this._escapedSubpath=void 0,this.pathAtom&&this.pathAtom.reportChanged()},Object.defineProperty(e.prototype,"path",{get:function(){return this.getEscapedPath(!0)},enumerable:!0,configurable:!0}),e.prototype.getEscapedPath=function(e){return e&&(this.pathAtom||(this.pathAtom=mobx.createAtom("path")),this.pathAtom.reportObserved()),this.parent?(void 0===this._escapedSubpath&&(this._escapedSubpath=this._subpath?escapeJsonPath(this._subpath):""),this.parent.getEscapedPath(e)+"/"+this._escapedSubpath):""},Object.defineProperty(e.prototype,"isRoot",{get:function(){return null===this.parent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAlive",{get:function(){return this.state!==NodeLifeCycle.DEAD},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isDetaching",{get:function(){return this.state===NodeLifeCycle.DETACHING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"observableIsAlive",{get:function(){return this.aliveAtom||(this.aliveAtom=mobx.createAtom("alive")),this.aliveAtom.reportObserved(),this.isAlive},enumerable:!0,configurable:!0}),e.prototype.baseFinalizeCreation=function(e){if(this.state===NodeLifeCycle.CREATED){if(this.parent){if(this.parent.state!==NodeLifeCycle.FINALIZED)return;this.fireHook(Hook.afterAttach)}this.state=NodeLifeCycle.FINALIZED,e&&e()}},e.prototype.baseFinalizeDeath=function(){this._hookSubscribers&&this._hookSubscribers.clearAll(),this._subpathUponDeath=this._subpath,this._pathUponDeath=this.getEscapedPath(!1),this.baseSetParent(null,""),this.state=NodeLifeCycle.DEAD},e.prototype.baseAboutToDie=function(){this.fireHook(Hook.beforeDestroy)},e}(),ScalarNode=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;try{a.storedValue=t.createNewInstance(o)}catch(e){throw a.state=NodeLifeCycle.DEAD,e}return a.state=NodeLifeCycle.CREATED,a.finalizeCreation(),a}return __extends(t,e),Object.defineProperty(t.prototype,"root",{get:function(){if(!this.parent)throw fail("This scalar node is not part of a tree");return this.parent.root},enumerable:!0,configurable:!0}),t.prototype.setParent=function(e,t){var n=this.parent!==e,r=this.subpath!==t;(n||r)&&(this.environment=void 0,this.baseSetParent(this.parent,t))},Object.defineProperty(t.prototype,"snapshot",{get:function(){return freeze(this.getSnapshot())},enumerable:!0,configurable:!0}),t.prototype.getSnapshot=function(){return this.type.getSnapshot(this)},t.prototype.toString=function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"<root>";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")},t.prototype.die=function(){this.isAlive&&this.state!==NodeLifeCycle.DETACHING&&(this.aboutToDie(),this.finalizeDeath())},t.prototype.finalizeCreation=function(){this.baseFinalizeCreation()},t.prototype.aboutToDie=function(){this.baseAboutToDie()},t.prototype.finalizeDeath=function(){this.baseFinalizeDeath()},t.prototype.fireHook=function(e){this.fireInternalHook(e)},__decorate([mobx.action],t.prototype,"die",null),t}(BaseNode),nextNodeId=1,snapshotReactionOptions={onError:function(e){throw e}},ObjectNode=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;if(a.nodeId=++nextNodeId,a.isProtectionEnabled=!0,a._autoUnbox=!0,a._isRunningAction=!1,a._hasSnapshotReaction=!1,a._observableInstanceState=0,a._cachedInitialSnapshotCreated=!1,a.unbox=a.unbox.bind(a),a._initialSnapshot=freeze(o),a.identifierAttribute=t.identifierAttribute,n||(a.identifierCache=new IdentifierCache),a._childNodes=t.initializeChildNodes(a,a._initialSnapshot),a.identifier=null,a.unnormalizedIdentifier=null,a.identifierAttribute&&a._initialSnapshot){var s=a._initialSnapshot[a.identifierAttribute];if(void 0===s){var p=a._childNodes[a.identifierAttribute];p&&(s=p.value)}if("string"!=typeof s&&"number"!=typeof s)throw fail("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=normalizeIdentifier(s),a.unnormalizedIdentifier=s}return n?n.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return __extends(t,e),t.prototype.applyPatches=function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)},t.prototype.applySnapshot=function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)},t.prototype.createObservableInstanceIfNeeded=function(){var e,t;if(0===this._observableInstanceState){this._observableInstanceState=1;for(var n=[],r=this.parent;r&&0===r._observableInstanceState;)n.unshift(r),r=r.parent;try{for(var i=__values(n),o=i.next();!o.done;o=i.next()){o.value.createObservableInstanceIfNeeded()}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}var a=this.type;try{this.storedValue=a.createNewInstance(this._childNodes),this.preboot(),this._isRunningAction=!0,a.finalizeNewInstance(this,this.storedValue)}catch(e){throw this.state=NodeLifeCycle.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,invalidateComputed(this,"snapshot"),this.isRoot&&this._addSnapshotReaction(),this._childNodes=EMPTY_OBJECT,this.state=NodeLifeCycle.CREATED,this.fireHook(Hook.afterCreate),this.finalizeCreation()}},Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!0,configurable:!0}),t.prototype.clearParent=function(){if(this.parent){this.fireHook(Hook.beforeDetach);var e=this.state;this.state=NodeLifeCycle.DETACHING;var t=this.root,n=t.environment,r=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=n,this.identifierCache=r}finally{this.state=e}}},t.prototype.setParent=function(e,t){var n=e!==this.parent,r=t!==this.subpath;(n||r)&&(n?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Hook.afterAttach)):r&&this.baseSetParent(this.parent,t))},t.prototype.fireHook=function(e){var t=this;this.fireInternalHook(e);var n=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof n&&(mobx._allowStateChangesInsideComputed?mobx._allowStateChangesInsideComputed((function(){n.apply(t.storedValue)})):n.apply(this.storedValue))},Object.defineProperty(t.prototype,"snapshot",{get:function(){return freeze(this.getSnapshot())},enumerable:!0,configurable:!0}),t.prototype.getSnapshot=function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath},t.prototype._getActualSnapshot=function(){return this.type.getSnapshot(this)},t.prototype._getCachedInitialSnapshot=function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,n=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,n),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot},t.prototype.isRunningAction=function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()},t.prototype.assertAlive=function(e){var t=getLivelinessChecking();if(!this.isAlive&&"ignore"!==t){var n=this._getAssertAliveError(e);switch(t){case"error":throw fail(n);case"warn":warnError(n)}}},t.prototype._getAssertAliveError=function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",n=e.subpath&&escapeJsonPath(e.subpath)||"",r=e.actionContext||getCurrentActionContext();r&&"action"!==r.type&&r.parentActionEvent&&(r=r.parentActionEvent);var i="";r&&null!=r.name&&(i=(r&&r.context&&getPath(r.context)||t)+"."+r.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: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."},t.prototype.getChildNode=function(e){this.assertAlive({subpath:e}),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildNode(this,e):this._childNodes[e]}finally{this._autoUnbox=!0}},t.prototype.getChildren=function(){this.assertAlive(EMPTY_OBJECT),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):convertChildNodesToArray(this._childNodes)}finally{this._autoUnbox=!0}},t.prototype.getChildType=function(e){return this.type.getChildType(e)},Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!0,configurable:!0}),t.prototype.assertWritable=function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw fail("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")},t.prototype.removeChild=function(e){this.type.removeChild(this,e)},t.prototype.unbox=function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e},t.prototype.toString=function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"<root>",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")},t.prototype.finalizeCreation=function(){var e=this;this.baseFinalizeCreation((function(){var t,n;try{for(var r=__values(e.getChildren()),i=r.next();!i.done;i=r.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}e.fireInternalHook(Hook.afterCreationFinalization)}))},t.prototype.detach=function(){if(!this.isAlive)throw fail("Error while detaching, node is not alive.");this.clearParent()},t.prototype.preboot=function(){var e=this;this._applyPatches=createActionInvoker(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){var n=splitJsonPath(t.path);resolveNodeByPathParts(e,n.slice(0,-1)).applyPatchLocally(n[n.length-1],t)}))})),this._applySnapshot=createActionInvoker(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),addHiddenFinalProp(this.storedValue,"$treenode",this),addHiddenFinalProp(this.storedValue,"toJSON",toJSON)},t.prototype.die=function(){this.isAlive&&this.state!==NodeLifeCycle.DETACHING&&(this.aboutToDie(),this.finalizeDeath())},t.prototype.aboutToDie=function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))},t.prototype.finalizeDeath=function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()},t.prototype.onSnapshot=function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)},t.prototype.emitSnapshot=function(e){this._internalEventsEmit("snapshot",e)},t.prototype.onPatch=function(e){return this._internalEventsRegister("patch",e)},t.prototype.emitPatch=function(e,t){if(this._internalEventsHasSubscribers("patch")){var n=__read(splitPatch(extend({},e,{path:t.path.substr(this.path.length)+"/"+e.path})),2),r=n[0],i=n[1];this._internalEventsEmit("patch",r,i)}this.parent&&this.parent.emitPatch(e,t)},t.prototype.hasDisposer=function(e){return this._internalEventsHas("dispose",e)},t.prototype.addDisposer=function(e){if(this.hasDisposer(e))throw fail("cannot add a disposer when it is already registered for execution");this._internalEventsRegister("dispose",e,!0)},t.prototype.removeDisposer=function(e){if(!this._internalEventsHas("dispose",e))throw fail("cannot remove a disposer which was never registered for execution");this._internalEventsUnregister("dispose",e)},t.prototype.removeMiddleware=function(e){if(this.middlewares){var t=this.middlewares.indexOf(e);t>=0&&this.middlewares.splice(t,1)}},t.prototype.addMiddleWare=function(e,t){var n=this;void 0===t&&(t=!0);var r={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(r):this.middlewares=[r],function(){n.removeMiddleware(r)}},t.prototype.applyPatchLocally=function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)},t.prototype._addSnapshotReaction=function(){var e=this;if(!this._hasSnapshotReaction){var t=mobx.reaction((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),snapshotReactionOptions);this.addDisposer(t),this._hasSnapshotReaction=!0}},t.prototype._internalEventsHasSubscribers=function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)},t.prototype._internalEventsRegister=function(e,t,n){return void 0===n&&(n=!1),this._internalEvents||(this._internalEvents=new EventHandlers),this._internalEvents.register(e,t,n)},t.prototype._internalEventsHas=function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)},t.prototype._internalEventsUnregister=function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)},t.prototype._internalEventsEmit=function(e){for(var t,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];this._internalEvents&&(t=this._internalEvents).emit.apply(t,__spread([e],n))},t.prototype._internalEventsClear=function(e){this._internalEvents&&this._internalEvents.clear(e)},t.prototype._internalEventsClearAll=function(){this._internalEvents&&this._internalEvents.clearAll()},__decorate([mobx.action],t.prototype,"createObservableInstanceIfNeeded",null),__decorate([mobx.computed],t.prototype,"snapshot",null),__decorate([mobx.action],t.prototype,"detach",null),__decorate([mobx.action],t.prototype,"die",null),t}(BaseNode);!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"}(TypeFlags||(TypeFlags={}));var cannotDetermineSubtype="cannotDetermine",BaseType=function(){function e(e){this.isType=!0,this.name=e}return e.prototype.create=function(e,t){return typecheckInternal(this,e),this.instantiate(null,"",t,e).value},e.prototype.getSnapshot=function(e,t){throw fail("unimplemented method")},e.prototype.isAssignableFrom=function(e){return e===this},e.prototype.validate=function(e,t){if(getStateTreeNodeSafe(e)){var n=getType(e);return this.isAssignableFrom(n)?typeCheckSuccess():typeCheckFailure(t,e)}return this.isValidSnapshot(e,t)},e.prototype.is=function(e){return 0===this.validate(e,[{path:"",type:this}]).length},Object.defineProperty(e.prototype,"Type",{get:function(){throw fail("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`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"TypeWithoutSTN",{get:function(){throw fail("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`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"SnapshotType",{get:function(){throw fail("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`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CreationType",{get:function(){throw fail("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`")},enumerable:!0,configurable:!0}),__decorate([mobx.action],e.prototype,"create",null),e}(),ComplexType=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.create=function(t,n){return void 0===t&&(t=this.getDefaultSnapshot()),e.prototype.create.call(this,t,n)},t.prototype.getValue=function(e){return e.createObservableInstanceIfNeeded(),e.storedValue},t.prototype.tryToReconcileNode=function(e,t){return!e.isDetaching&&(e.snapshot===t||(!(!isStateTreeNode(t)||getStateTreeNode(t)!==e)||!(e.type!==this||!isMutable(t)||isStateTreeNode(t)||e.identifierAttribute&&e.identifier!==normalizeIdentifier(t[e.identifierAttribute]))&&(e.applySnapshot(t),!0)))},t.prototype.reconcile=function(e,t,n,r){if(this.tryToReconcileNode(e,t))return e.setParent(n,r),e;if(e.die(),isStateTreeNode(t)&&this.isAssignableFrom(getType(t))){var i=getStateTreeNode(t);return i.setParent(n,r),i}return this.instantiate(n,r,void 0,t)},t.prototype.getSubTypes=function(){return null},__decorate([mobx.action],t.prototype,"create",null),t}(BaseType),SimpleType=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.createNewInstance=function(e){return e},t.prototype.getValue=function(e){return e.storedValue},t.prototype.getSnapshot=function(e){return e.storedValue},t.prototype.reconcile=function(e,t,n,r){if(!e.isDetaching&&e.type===this&&e.storedValue===t)return e;var i=this.instantiate(n,r,void 0,t);return e.die(),i},t.prototype.getSubTypes=function(){return null},t}(BaseType);function isType(e){return"object"==typeof e&&e&&!0===e.isType}var runningActions=new Map;function createActionTrackingMiddleware(e){return function(t,n,r){switch(t.type){case"action":if(e.filter&&!0!==e.filter(t))return n(t);var i=e.onStart(t);e.onResume(t,i),runningActions.set(t.id,{call:t,context:i,async:!1});try{var o=n(t);return e.onSuspend(t,i),!1===runningActions.get(t.id).async&&(runningActions.delete(t.id),e.onSuccess(t,i,o)),o}catch(n){throw runningActions.delete(t.id),e.onFail(t,i,n),n}case"flow_spawn":return(a=runningActions.get(t.rootId)).async=!0,n(t);case"flow_resume":case"flow_resume_error":var a=runningActions.get(t.rootId);e.onResume(t,a.context);try{return n(t)}finally{e.onSuspend(t,a.context)}case"flow_throw":a=runningActions.get(t.rootId);return runningActions.delete(t.rootId),e.onFail(t,a.context,t.args[0]),n(t);case"flow_return":a=runningActions.get(t.rootId);return runningActions.delete(t.rootId),e.onSuccess(t,a.context,t.args[0]),n(t)}}}var RunningAction=function(){function e(e,t){this.hooks=e,this.call=t,this.flowsPending=0,this.running=!0,e&&e.onStart(t)}return e.prototype.finish=function(e){this.running&&(this.running=!1,this.hooks&&this.hooks.onFinish(this.call,e))},e.prototype.incFlowsPending=function(){this.flowsPending++},e.prototype.decFlowsPending=function(){this.flowsPending--},Object.defineProperty(e.prototype,"hasFlowsPending",{get:function(){return this.flowsPending>0},enumerable:!0,configurable:!0}),e}();function createActionTrackingMiddleware2(e){var t=new WeakMap;return function(n,r){var i=n.parentActionEvent?t.get(n.parentActionEvent):void 0;if("action"===n.type){var o=__assign(__assign({},n),{env:i&&i.call.env,parentCall:i&&i.call}),a=!e.filter||e.filter(o),s=new RunningAction(a?e:void 0,o);t.set(n,s);var p=void 0;try{p=r(n)}catch(e){throw s.finish(e),e}return s.hasFlowsPending||s.finish(),p}if(!i)return r(n);switch(n.type){case"flow_spawn":return i.incFlowsPending(),r(n);case"flow_resume":case"flow_resume_error":return r(n);case"flow_throw":var c=n.args[0];try{return r(n)}finally{i.decFlowsPending(),i.hasFlowsPending||i.finish(c)}case"flow_return":try{return r(n)}finally{i.decFlowsPending(),i.hasFlowsPending||i.finish()}}}}function serializeArgument(e,t,n,r){if(r instanceof Date)return{$MST_DATE:r.getTime()};if(isPrimitive(r))return r;if(isStateTreeNode(r))return serializeTheUnserializable("[MSTNode: "+getType(r).name+"]");if("function"==typeof r)return serializeTheUnserializable("[function]");if("object"==typeof r&&!isPlainObject(r)&&!isArray(r))return serializeTheUnserializable("[object "+(r&&r.constructor&&r.constructor.name||"Complex Object")+"]");try{return JSON.stringify(r),r}catch(e){return serializeTheUnserializable(""+e)}}function deserializeArgument(e,t){return t&&"object"==typeof t&&"$MST_DATE"in t?new Date(t.$MST_DATE):t}function serializeTheUnserializable(e){return{$MST_UNSERIALIZABLE:!0,type:e}}function applyAction(e,t){mobx.runInAction((function(){asArray(t).forEach((function(t){return baseApplyAction(e,t)}))}))}function baseApplyAction(e,t){var n=tryResolve(e,t.path||"");if(!n)throw fail("Invalid action path: "+(t.path||""));var r=getStateTreeNode(n);if("@APPLY_PATCHES"===t.name)return applyPatch.call(null,n,t.args[0]);if("@APPLY_SNAPSHOT"===t.name)return applySnapshot.call(null,n,t.args[0]);if("function"!=typeof n[t.name])throw fail("Action '"+t.name+"' does not exist in '"+r.path+"'");return n[t.name].apply(n,t.args?t.args.map((function(e){return deserializeArgument(r,e)})):[])}function recordActions(e,t){var n,r=[],i=function(e){(!t||t(e,getRunningActionContext()))&&r.push(e)},o={actions:r,get recording(){return!!n},stop:function(){n&&(n(),n=void 0)},resume:function(){n||(n=onAction(e,i))},replay:function(e){applyAction(e,r)}};return o.resume(),o}function onAction(e,t,n){return void 0===n&&(n=!1),addMiddleware(e,(function(r,i){if("action"===r.type&&r.id===r.rootId){var o=getStateTreeNode(r.context),a={name:r.name,path:getRelativePathBetweenNodes(getStateTreeNode(e),o),args:r.args.map((function(e,t){return serializeArgument(o,r.name,t,e)}))};if(n){var s=i(r);return t(a),s}return t(a),i(r)}return i(r)}))}var currentActionContext,nextActionId=1;function getCurrentActionContext(){return currentActionContext}function getNextActionId(){return nextActionId++}function runWithActionContext(e,t){var n=getStateTreeNode(e.context);"action"===e.type&&n.assertAlive({actionContext:e});var r=n._isRunningAction;n._isRunningAction=!0;var i=currentActionContext;currentActionContext=e;try{return runMiddleWares(n,e,t)}finally{currentActionContext=i,n._isRunningAction=r}}function getParentActionContext(e){if(e)return"action"===e.type?e:e.parentActionEvent}function createActionInvoker(e,t,n){var r=function(){var r=getNextActionId(),i=currentActionContext,o=getParentActionContext(i);return runWithActionContext({type:"action",name:t,id:r,args:argsToArray(arguments),context:e,tree:getRoot(e),rootId:i?i.rootId:r,parentId:i?i.id:0,allParentIds:i?__spread(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},n)};return r._isMSTAction=!0,r}function addMiddleware(e,t,n){return void 0===n&&(n=!0),getStateTreeNode(e).addMiddleWare(t,n)}function decorate(e,t,n){void 0===n&&(n=!0);var r={handler:e,includeHooks:n};return t.$mst_middleware=t.$mst_middleware||[],t.$mst_middleware.push(r),t}var CollectedMiddlewares=function(){function e(e,t){this.arrayIndex=0,this.inArrayIndex=0,this.middlewares=[],t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var n=e;n;)n.middlewares&&this.middlewares.push(n.middlewares),n=n.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!0,configurable:!0}),e.prototype.getNextMiddleware=function(){var e=this.middlewares[this.arrayIndex];if(e){var t=e[this.inArrayIndex++];return t||(this.arrayIndex++,this.inArrayIndex=0,this.getNextMiddleware())}},e}();function runMiddleWares(e,t,n){var r=new CollectedMiddlewares(e,n);if(r.isEmpty)return mobx.action(n).apply(null,t.args);var i=null;return function e(t){var o=r.getNextMiddleware(),a=o&&o.handler;if(!a)return mobx.action(n).apply(null,t.args);if(!o.includeHooks&&Hook[t.name])return e(t);return a(t,(function(t,n){i=e(t),n&&(i=n(i))}),(function(e){i=e})),i}(t)}function getRunningActionContext(){for(var e=getCurrentActionContext();e&&"action"!==e.type;)e=e.parentActionEvent;return e}function _isActionContextThisOrChildOf(e,t,n){for(var r="number"==typeof t?t:t.id,i=n?e:e.parentActionEvent;i;){if(i.id===r)return!0;i=i.parentActionEvent}return!1}function isActionContextChildOf(e,t){return _isActionContextThisOrChildOf(e,t,!1)}function isActionContextThisOrChildOf(e,t){return _isActionContextThisOrChildOf(e,t,!0)}function safeStringify(e){try{return JSON.stringify(e)}catch(e){return"<Unserializable: "+e+">"}}function prettyPrintValue(e){return"function"==typeof e?"<function"+(e.name?" "+e.name:"")+">":isStateTreeNode(e)?"<"+e+">":"`"+safeStringify(e)+"`"}function shortenPrintValue(e){return e.length<280?e:e.substring(0,272)+"......"+e.substring(e.length-8)}function toErrorString(e){var t=e.value,n=e.context[e.context.length-1].type,r=e.context.map((function(e){return e.path})).filter((function(e){return e.length>0})).join("/"),i=r.length>0?'at path "/'+r+'" ':"",o=isStateTreeNode(t)?"value of type "+getStateTreeNode(t).type.name+":":isPrimitive(t)?"value":"snapshot",a=n&&isStateTreeNode(t)&&n.is(getStateTreeNode(t).snapshot);return""+i+o+" "+prettyPrintValue(t)+" is not assignable "+(n?"to type: `"+n.name+"`":"")+(e.message?" ("+e.message+")":"")+(n?isPrimitiveType(n)||isPrimitive(t)?".":", expected an instance of `"+n.name+"` or a snapshot like `"+n.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function getContextForPath(e,t,n){return e.concat([{path:t,type:n}])}function typeCheckSuccess(){return EMPTY_ARRAY}function typeCheckFailure(e,t,n){return[{context:e,value:t,message:n}]}function flattenTypeErrors(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function typecheckInternal(e,t){isTypeCheckingEnabled()&&typecheck(e,t)}function typecheck(e,t){var n=e.validate(t,[{path:"",type:e}]);if(n.length>0)throw fail(validationErrorsToString(e,t,n))}function validationErrorsToString(e,t,n){if(0!==n.length)return"Error while converting "+shortenPrintValue(prettyPrintValue(t))+" to `"+e.name+"`:\n\n "+n.map(toErrorString).join("\n ")}var NodeLifeCycle,identifierCacheId=0,IdentifierCache=function(){function e(){this.cacheId=identifierCacheId++,this.cache=mobx.observable.map(),this.lastCacheModificationPerId=mobx.observable.map()}return e.prototype.updateLastCacheModificationPerId=function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)},e.prototype.getLastCacheModificationPerId=function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t},e.prototype.addNodeToCache=function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var n=e.identifier;this.cache.has(n)||this.cache.set(n,mobx.observable.array([],mobxShallow));var r=this.cache.get(n);if(-1!==r.indexOf(e))throw fail("Already registered");r.push(e),t&&this.updateLastCacheModificationPerId(n)}},e.prototype.mergeCache=function(e){var t=this;mobx.values(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))},e.prototype.notifyDied=function(e){if(e.identifierAttribute){var t=e.identifier,n=this.cache.get(t);n&&(n.remove(e),n.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}},e.prototype.splitCache=function(t){var n=this,r=new e,i=t.path;return mobx.entries(this.cache).forEach((function(e){for(var t=__read(e,2),o=t[0],a=t[1],s=!1,p=a.length-1;p>=0;p--)0===a[p].path.indexOf(i)&&(r.addNodeToCache(a[p],!1),a.splice(p,1),s=!0);s&&n.updateLastCacheModificationPerId(o)})),r},e.prototype.has=function(e,t){var n=this.cache.get(t);return!!n&&n.some((function(t){return e.isAssignableFrom(t.type)}))},e.prototype.resolve=function(e,t){var n=this.cache.get(t);if(!n)return null;var r=n.filter((function(t){return e.isAssignableFrom(t.type)}));switch(r.length){case 0:return null;case 1:return r[0];default:throw fail("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+r.map((function(e){return e.path})).join(", "))}},e}();function createObjectNode(e,t,n,r,i){var o=getStateTreeNodeSafe(i);if(o){if(o.parent)throw fail("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 '"+o.path+"'");return t&&o.setParent(t,n),o}return new ObjectNode(e,t,n,r,i)}function createScalarNode(e,t,n,r,i){return new ScalarNode(e,t,n,r,i)}function isNode(e){return e instanceof ScalarNode||e instanceof ObjectNode}function isStateTreeNode(e){return!(!e||!e.$treenode)}function getStateTreeNode(e){if(!isStateTreeNode(e))throw fail("Value "+e+" is no MST Node");return e.$treenode}function getStateTreeNodeSafe(e){return e&&e.$treenode||null}function toJSON(){return getStateTreeNode(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"}(NodeLifeCycle||(NodeLifeCycle={}));var doubleDot=function(e){return".."};function getRelativePathBetweenNodes(e,t){if(e.root!==t.root)throw fail("Cannot calculate relative path: objects '"+e+"' and '"+t+"' are not part of the same object tree");for(var n=splitJsonPath(e.path),r=splitJsonPath(t.path),i=0;i<n.length&&n[i]===r[i];i++);return n.slice(i).map(doubleDot).join("/")+joinJsonPath(r.slice(i))}function resolveNodeByPath(e,t,n){return void 0===n&&(n=!0),resolveNodeByPathParts(e,splitJsonPath(t),n)}function resolveNodeByPathParts(e,t,n){void 0===n&&(n=!0);for(var r=e,i=0;i<t.length;i++){var o=t[i];if(".."===o){if(r=r.parent)continue}else{if("."===o)continue;if(r){if(r instanceof ScalarNode)try{var a=r.value;isStateTreeNode(a)&&(r=getStateTreeNode(a))}catch(e){if(!n)return;throw e}if(r instanceof ObjectNode)if(r.getChildType(o)&&(r=r.getChildNode(o)))continue}}if(n)throw fail("Could not resolve '"+o+"' in path '"+(joinJsonPath(t.slice(0,i))||"/")+"' while resolving '"+joinJsonPath(t)+"'");return}return r}function convertChildNodesToArray(e){if(!e)return EMPTY_ARRAY;var t=Object.keys(e);if(!t.length)return EMPTY_ARRAY;var n=new Array(t.length);return t.forEach((function(t,r){n[r]=e[t]})),n}function process$1(e){return flow(e)}var EMPTY_ARRAY=Object.freeze([]),EMPTY_OBJECT=Object.freeze({}),mobxShallow="string"==typeof mobx.$mobx?{deep:!1}:{deep:!1,proxy:!1};function fail(e){return void 0===e&&(e="Illegal state"),new Error("[mobx-state-tree] "+e)}function identity(e){return e}Object.freeze(mobxShallow);var isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function isArray(e){return Array.isArray(e)||mobx.isObservableArray(e)}function asArray(e){return e?isArray(e)?e:[e]:EMPTY_ARRAY}function extend(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0;r<t.length;r++){var i=t[r];for(var o in i)e[o]=i[o]}return e}function isPlainObject(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function isMutable(e){return!(null===e||"object"!=typeof e||e instanceof Date||e instanceof RegExp)}function isPrimitive(e,t){return void 0===t&&(t=!0),null==e||!!("string"==typeof e||"number"==typeof e||"boolean"==typeof e||t&&e instanceof Date)}function freeze(e){return e}function deepFreeze(e){return e}function isSerializable(e){return"function"!=typeof e}function addHiddenFinalProp(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}var EventHandler=function(){function e(){this.handlers=[]}return Object.defineProperty(e.prototype,"hasSubscribers",{get:function(){return this.handlers.length>0},enumerable:!0,configurable:!0}),e.prototype.register=function(e,t){var n=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){n.unregister(e)}},e.prototype.has=function(e){return this.handlers.indexOf(e)>=0},e.prototype.unregister=function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)},e.prototype.clear=function(){this.handlers.length=0},e.prototype.emit=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.handlers.slice();n.forEach((function(t){return t.apply(void 0,__spread(e))}))},e}(),EventHandlers=function(){function e(){}return e.prototype.hasSubscribers=function(e){var t=this.eventHandlers&&this.eventHandlers[e];return!!t&&t.hasSubscribers},e.prototype.register=function(e,t,n){void 0===n&&(n=!1),this.eventHandlers||(this.eventHandlers={});var r=this.eventHandlers[e];return r||(r=this.eventHandlers[e]=new EventHandler),r.register(t,n)},e.prototype.has=function(e,t){var n=this.eventHandlers&&this.eventHandlers[e];return!!n&&n.has(t)},e.prototype.unregister=function(e,t){var n=this.eventHandlers&&this.eventHandlers[e];n&&n.unregister(t)},e.prototype.clear=function(e){this.eventHandlers&&delete this.eventHandlers[e]},e.prototype.clearAll=function(){this.eventHandlers=void 0},e.prototype.emit=function(e){for(var t,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=this.eventHandlers&&this.eventHandlers[e];i&&(t=i).emit.apply(t,__spread(n))},e}();function argsToArray(e){for(var t=new Array(e.length),n=0;n<e.length;n++)t[n]=e[n];return t}function invalidateComputed(e,t){mobx.getAtom(e,t).trackAndCompute()}function stringStartsWith(e,t){return 0===e.indexOf(t)}function warnError(e){console.warn(new Error("[mobx-state-tree] "+e))}function isTypeCheckingEnabled(){return"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK}function flow(e){return createFlowSpawner(e.name,e)}function castFlowReturn(e){return e}function createFlowSpawner(e,t){var n=function(){var r=getNextActionId(),i=getCurrentActionContext();if(!i)throw fail("a mst flow must always have a parent context");var o=getParentActionContext(i);if(!o)throw fail("a mst flow must always have a parent action context");var a={name:e,id:r,tree:i.tree,context:i.context,parentId:i.id,allParentIds:__spread(i.allParentIds,[i.id]),rootId:i.rootId,parentEvent:i,parentActionEvent:o},s=arguments;function p(e,t,r){e.$mst_middleware=n.$mst_middleware,runWithActionContext(__assign(__assign({},a),{type:t,args:[r]}),e)}return new Promise((function(e,r){var i,o=function(){i=t.apply(null,arguments),c(void 0)};function c(e){var t;try{p((function(e){t=i.next(e)}),"flow_resume",e)}catch(e){return void setImmediate((function(){p((function(t){r(e)}),"flow_throw",e)}))}l(t)}function u(e){var t;try{p((function(e){t=i.throw(e)}),"flow_resume_error",e)}catch(e){return void setImmediate((function(){p((function(t){r(e)}),"flow_throw",e)}))}l(t)}function l(t){if(!t.done){if(!t.value||"function"!=typeof t.value.then)throw fail("Only promises can be yielded to `async`, got: "+t);return t.value.then(c,u)}setImmediate((function(){p((function(t){e(t)}),"flow_return",t.value)}))}o.$mst_middleware=n.$mst_middleware,runWithActionContext(__assign(__assign({},a),{type:"flow_spawn",args:argsToArray(s)}),o)}))};return n}function splitPatch(e){if(!("oldValue"in e))throw fail("Patches without `oldValue` field cannot be inversed");return[stripPatch(e),invertPatch(e)]}function stripPatch(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 invertPatch(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 isNumber(e){return"number"==typeof e}function escapeJsonPath(e){return!0===isNumber(e)?""+e:-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPath(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function joinJsonPath(e){if(0===e.length)return"";var t=function(e){return e.map(escapeJsonPath).join("/")};return"."===e[0]||".."===e[0]?t(e):"/"+t(e)}function splitJsonPath(e){var t=e.split("/").map(unescapeJsonPath);if(!(""===e||"."===e||".."===e||stringStartsWith(e,"/")||stringStartsWith(e,"./")||stringStartsWith(e,"../")))throw fail("a json path must be either rooted, empty or relative, but got '"+e+"'");return""===t[0]&&t.shift(),t}var SnapshotProcessor=function(e){function t(t,n,r){var i=e.call(this,r||t.name)||this;return i._subtype=t,i._processors=n,i}return __extends(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.SnapshotProcessor},enumerable:!0,configurable:!0}),t.prototype.describe=function(){return"snapshotProcessor("+this._subtype.describe()+")"},t.prototype.preProcessSnapshot=function(e){return this._processors.preProcessor?this._processors.preProcessor.call(null,e):e},t.prototype.postProcessSnapshot=function(e){return this._processors.postProcessor?this._processors.postProcessor.call(null,e):e},t.prototype._fixNode=function(e){var t=this;proxyNodeTypeMethods(e.type,this,"isAssignableFrom","create");var n=e.getSnapshot;e.getSnapshot=function(){return t.postProcessSnapshot(n.call(e))}},t.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?r:this.preProcessSnapshot(r),o=this._subtype.instantiate(e,t,n,i);return this._fixNode(o),o},t.prototype.reconcile=function(e,t,n,r){var i=this._subtype.reconcile(e,isStateTreeNode(t)?t:this.preProcessSnapshot(t),n,r);return i!==e&&this._fixNode(i),i},t.prototype.getSnapshot=function(e,t){void 0===t&&(t=!0);var n=this._subtype.getSnapshot(e);return t?this.postProcessSnapshot(n):n},t.prototype.isValidSnapshot=function(e,t){var n=this.preProcessSnapshot(e);return this._subtype.validate(n,t)},t.prototype.getSubTypes=function(){return this._subtype},t.prototype.is=function(e){return 0===this._subtype.validate(isType(e)?this._subtype:this.preProcessSnapshot(e),[{path:"",type:this._subtype}]).length},t}(BaseType);function proxyNodeTypeMethods(e,t){for(var n,r,i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];try{for(var a=__values(i),s=a.next();!s.done;s=a.next()){var p=s.value;e[p]=t[p].bind(t)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}function snapshotProcessor(e,t,n){return new SnapshotProcessor(e,t,n)}var MapIdentifierMode,needsIdentifierError="Map.put can only be used to store complex values that have an identifier type attribute";function tryCollectModelTypes(e,t){var n,r,i=e.getSubTypes();if(i===cannotDetermineSubtype)return!1;if(i){var o=asArray(i);try{for(var a=__values(o),s=a.next();!s.done;s=a.next()){if(!tryCollectModelTypes(s.value,t))return!1}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}return e instanceof ModelType&&t.push(e),!0}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.YES=1]="YES",e[e.NO=2]="NO"}(MapIdentifierMode||(MapIdentifierMode={}));var MSTMap=function(e){function t(t){return e.call(this,t,mobx.observable.ref.enhancer)||this}return __extends(t,e),t.prototype.get=function(t){return e.prototype.get.call(this,""+t)},t.prototype.has=function(t){return e.prototype.has.call(this,""+t)},t.prototype.delete=function(t){return e.prototype.delete.call(this,""+t)},t.prototype.set=function(t,n){return e.prototype.set.call(this,""+t,n)},t.prototype.put=function(e){if(!e)throw fail("Map.put cannot be used to set empty values");if(isStateTreeNode(e)){var t=getStateTreeNode(e);if(null===t.identifier)throw fail(needsIdentifierError);return this.set(t.identifier,e),e}if(isMutable(e)){var n=getStateTreeNode(this),r=n.type;if(r.identifierMode!==MapIdentifierMode.YES)throw fail(needsIdentifierError);var i=e[r.mapIdentifierAttribute];if(!isValidIdentifier(i)){var o=this.put(r.getChildType().create(e,n.environment));return this.put(getSnapshot(o))}var a=normalizeIdentifier(i);return this.set(a,e),this.get(a)}throw fail("Map.put can only be used to store complex values")},t}(mobx.ObservableMap),MapType=function(e){function t(t,n,r){void 0===r&&(r=[]);var i=e.call(this,t)||this;return i._subType=n,i.identifierMode=MapIdentifierMode.UNKNOWN,i.mapIdentifierAttribute=void 0,i.flags=TypeFlags.Map,i.hookInitializers=[],i._determineIdentifierMode(),i.hookInitializers=r,i}return __extends(t,e),t.prototype.hooks=function(e){var n=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,n)},t.prototype.instantiate=function(e,t,n,r){return this._determineIdentifierMode(),createObjectNode(this,e,t,n,r)},t.prototype._determineIdentifierMode=function(){if(this.identifierMode===MapIdentifierMode.UNKNOWN){var e=[];if(tryCollectModelTypes(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw fail("The objects in a map should all have the same identifier attribute, expected '"+t+"', but child of type '"+e.name+"' declared attribute '"+e.identifierAttribute+"' as identifier");t=e.identifierAttribute}})),t?(this.identifierMode=MapIdentifierMode.YES,this.mapIdentifierAttribute=t):this.identifierMode=MapIdentifierMode.NO}}},t.prototype.initializeChildNodes=function(e,t){void 0===t&&(t={});var n=e.type._subType,r={};return Object.keys(t).forEach((function(i){r[i]=n.instantiate(e,i,void 0,t[i])})),r},t.prototype.createNewInstance=function(e){return new MSTMap(e)},t.prototype.finalizeNewInstance=function(e,t){mobx._interceptReads(t,e.unbox),e.type.hookInitializers.forEach((function(e){var n=e(t);Object.keys(n).forEach((function(e){var r=n[e],i=createActionInvoker(t,e,r);addHiddenFinalProp(t,e,i)}))})),mobx.intercept(t,this.willChange),mobx.observe(t,this.didChange)},t.prototype.describe=function(){return"Map<string, "+this._subType.describe()+">"},t.prototype.getChildren=function(e){return mobx.values(e.storedValue)},t.prototype.getChildNode=function(e,t){var n=e.storedValue.get(""+t);if(!n)throw fail("Not a child "+t);return n},t.prototype.willChange=function(e){var t=getStateTreeNode(e.object),n=e.name;t.assertWritable({subpath:n});var r=t.type,i=r._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(n))return null;typecheckInternal(i,o),e.newValue=i.reconcile(t.getChildNode(n),e.newValue,t,n),r.processIdentifier(n,e.newValue);break;case"add":typecheckInternal(i,e.newValue),e.newValue=i.instantiate(t,n,void 0,e.newValue),r.processIdentifier(n,e.newValue)}return e},t.prototype.processIdentifier=function(e,t){if(this.identifierMode===MapIdentifierMode.YES&&t instanceof ObjectNode){var n=t.identifier;if(n!==e)throw fail("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+n+"', but expected: '"+e+"'")}},t.prototype.getSnapshot=function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t},t.prototype.processInitialSnapshot=function(e){var t={};return Object.keys(e).forEach((function(n){t[n]=e[n].getSnapshot()})),t},t.prototype.didChange=function(e){var t=getStateTreeNode(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:escapeJsonPath(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:escapeJsonPath(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var n=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:escapeJsonPath(e.name),oldValue:n},t)}},t.prototype.applyPatchLocally=function(e,t,n){var r=e.storedValue;switch(n.op){case"add":case"replace":r.set(t,n.value);break;case"remove":r.delete(t)}},t.prototype.applySnapshot=function(e,t){typecheckInternal(this,t);var n=e.storedValue,r={};if(Array.from(n.keys()).forEach((function(e){r[e]=!1})),t)for(var i in t)n.set(i,t[i]),r[""+i]=!0;Object.keys(r).forEach((function(e){!1===r[e]&&n.delete(e)}))},t.prototype.getChildType=function(){return this._subType},t.prototype.isValidSnapshot=function(e,t){var n=this;return isPlainObject(e)?flattenTypeErrors(Object.keys(e).map((function(r){return n._subType.validate(e[r],getContextForPath(t,r,n._subType))}))):typeCheckFailure(t,e,"Value is not a plain object")},t.prototype.getDefaultSnapshot=function(){return EMPTY_OBJECT},t.prototype.removeChild=function(e,t){e.storedValue.delete(t)},__decorate([mobx.action],t.prototype,"applySnapshot",null),t}(ComplexType);function map(e){return new MapType("map<string, "+e.name+">",e)}function isMapType(e){return isType(e)&&(e.flags&TypeFlags.Map)>0}var ArrayType=function(e){function t(t,n,r){void 0===r&&(r=[]);var i=e.call(this,t)||this;return i._subType=n,i.flags=TypeFlags.Array,i.hookInitializers=[],i.hookInitializers=r,i}return __extends(t,e),t.prototype.hooks=function(e){var n=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,n)},t.prototype.instantiate=function(e,t,n,r){return createObjectNode(this,e,t,n,r)},t.prototype.initializeChildNodes=function(e,t){void 0===t&&(t=[]);var n=e.type._subType,r={};return t.forEach((function(t,i){var o=""+i;r[o]=n.instantiate(e,o,void 0,t)})),r},t.prototype.createNewInstance=function(e){return mobx.observable.array(convertChildNodesToArray(e),mobxShallow)},t.prototype.finalizeNewInstance=function(e,t){mobx._getAdministration(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var n=e(t);Object.keys(n).forEach((function(e){var r=n[e],i=createActionInvoker(t,e,r);addHiddenFinalProp(t,e,i)}))})),mobx.intercept(t,this.willChange),mobx.observe(t,this.didChange)},t.prototype.describe=function(){return this._subType.describe()+"[]"},t.prototype.getChildren=function(e){return e.storedValue.slice()},t.prototype.getChildNode=function(e,t){var n=Number(t);if(n<e.storedValue.length)return e.storedValue[n];throw fail("Not a child: "+t)},t.prototype.willChange=function(e){var t=getStateTreeNode(e.object);t.assertWritable({subpath:""+e.index});var n=t.type._subType,r=t.getChildren();switch(e.type){case"update":if(e.newValue===e.object[e.index])return null;var i=reconcileArrayChildren(t,n,[r[e.index]],[e.newValue],[e.index]);if(!i)return null;e.newValue=i[0];break;case"splice":var o=e.index,a=e.removedCount,s=e.added,p=reconcileArrayChildren(t,n,r.slice(o,o+a),s,s.map((function(e,t){return o+t})));if(!p)return null;e.added=p;for(var c=o+a;c<r.length;c++)r[c].setParent(t,""+(c+s.length-a))}return e},t.prototype.getSnapshot=function(e){return e.getChildren().map((function(e){return e.snapshot}))},t.prototype.processInitialSnapshot=function(e){var t=[];return Object.keys(e).forEach((function(n){t.push(e[n].getSnapshot())})),t},t.prototype.didChange=function(e){var t=getStateTreeNode(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":for(var n=e.removedCount-1;n>=0;n--)t.emitPatch({op:"remove",path:""+(e.index+n),oldValue:e.removed[n].snapshot},t);for(n=0;n<e.addedCount;n++)t.emitPatch({op:"add",path:""+(e.index+n),value:t.getChildNode(""+(e.index+n)).snapshot,oldValue:void 0},t);return}},t.prototype.applyPatchLocally=function(e,t,n){var r=e.storedValue,i="-"===t?r.length:Number(t);switch(n.op){case"replace":r[i]=n.value;break;case"add":r.splice(i,0,n.value);break;case"remove":r.splice(i,1)}},t.prototype.applySnapshot=function(e,t){typecheckInternal(this,t),e.storedValue.replace(t)},t.prototype.getChildType=function(){return this._subType},t.prototype.isValidSnapshot=function(e,t){var n=this;return isArray(e)?flattenTypeErrors(e.map((function(e,r){return n._subType.validate(e,getContextForPath(t,""+r,n._subType))}))):typeCheckFailure(t,e,"Value is not an array")},t.prototype.getDefaultSnapshot=function(){return EMPTY_ARRAY},t.prototype.removeChild=function(e,t){e.storedValue.splice(Number(t),1)},__decorate([mobx.action],t.prototype,"applySnapshot",null),t}(ComplexType);function array(e){return new ArrayType(e.name+"[]",e)}function reconcileArrayChildren(e,t,n,r,i){for(var o=!0,a=0;;a++){var s=a<=r.length-1,p=n[a],c=s?r[a]:void 0,u=""+i[a];if(isNode(c)&&(c=c.storedValue),!p&&!s)break;if(s)if(p)if(areSame(p,c))n[a]=valueAsNode(t,e,u,c,p);else{for(var l=void 0,h=a;h<n.length;h++)if(areSame(n[h],c)){l=n.splice(h,1)[0];break}o=!1;f=valueAsNode(t,e,u,c,l);n.splice(a,0,f)}else{if(isStateTreeNode(c)&&getStateTreeNode(c).parent===e)throw fail("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 '"+getStateTreeNode(c).path+"'");o=!1;var f=valueAsNode(t,e,u,c);n.splice(a,0,f)}else o=!1,n.splice(a,1),p instanceof ObjectNode&&p.createObservableInstanceIfNeeded(),p.die(),a--}return o?null:n}function valueAsNode(e,t,n,r,i){typecheckInternal(e,r);var o=function(){if(isStateTreeNode(r)){var o=getStateTreeNode(r);if(o.assertAlive(EMPTY_OBJECT),null!==o.parent&&o.parent===t)return o.setParent(t,n),o}return i?e.reconcile(i,r,t,n):e.instantiate(t,n,void 0,r)}();return i&&i!==o&&(i instanceof ObjectNode&&i.createObservableInstanceIfNeeded(),i.die()),o}function areSame(e,t){if(!e.isAlive)return!1;if(isStateTreeNode(t)){var n=getStateTreeNode(t);return n.isAlive&&n===e}return e.snapshot===t||e instanceof ObjectNode&&null!==e.identifier&&e.identifierAttribute&&isPlainObject(t)&&e.identifier===normalizeIdentifier(t[e.identifierAttribute])&&e.type.is(t)}function isArrayType(e){return isType(e)&&(e.flags&TypeFlags.Array)>0}var PRE_PROCESS_SNAPSHOT="preProcessSnapshot",POST_PROCESS_SNAPSHOT="postProcessSnapshot";function objectTypeToString(){return getStateTreeNode(this).toString()}var defaultObjectOptions={name:"AnonymousModel",properties:{},initializers:EMPTY_ARRAY};function toPropertiesObject(e){return Object.keys(e).reduce((function(e,t){var n,r,i;if(t in Hook)throw fail("Hook '"+t+"' was defined as property. Hooks should be defined as part of the actions");var o=Object.getOwnPropertyDescriptor(e,t);if("get"in o)throw fail("Getters are not supported as properties. Please use views instead");var a=o.value;if(null==a)throw fail("The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?");if(isPrimitive(a))return Object.assign({},e,((n={})[t]=optional(getPrimitiveFactoryFromValue(a),a),n));if(a instanceof MapType)return Object.assign({},e,((r={})[t]=optional(a,{}),r));if(a instanceof ArrayType)return Object.assign({},e,((i={})[t]=optional(a,[]),i));if(isType(a))return e;throw fail("Invalid type definition for property '"+t+"', cannot infer a type from a value like '"+a+"' ("+typeof a+")")}),e)}var ModelType=function(e){function t(t){var n=e.call(this,t.name||defaultObjectOptions.name)||this;return n.flags=TypeFlags.Object,n.named=function(e){return n.cloneAndEnhance({name:e})},n.props=function(e){return n.cloneAndEnhance({properties:e})},n.preProcessSnapshot=function(e){var t=n.preProcessor;return t?n.cloneAndEnhance({preProcessor:function(n){return t(e(n))}}):n.cloneAndEnhance({preProcessor:e})},n.postProcessSnapshot=function(e){var t=n.postProcessor;return t?n.cloneAndEnhance({postProcessor:function(n){return e(t(n))}}):n.cloneAndEnhance({postProcessor:e})},Object.assign(n,defaultObjectOptions,t),n.properties=toPropertiesObject(n.properties),freeze(n.properties),n.propertyNames=Object.keys(n.properties),n.identifierAttribute=n._getIdentifierAttribute(),n}return __extends(t,e),t.prototype._getIdentifierAttribute=function(){var e=void 0;return this.forAllProps((function(t,n){if(n.flags&TypeFlags.Identifier){if(e)throw fail("Cannot define property '"+t+"' as object identifier, property '"+e+"' is already defined as identifier property");e=t}})),e},t.prototype.cloneAndEnhance=function(e){return new t({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})},t.prototype.actions=function(e){var t=this;return this.cloneAndEnhance({initializers:[function(n){return t.instantiateActions(n,e(n)),n}]})},t.prototype.instantiateActions=function(e,t){if(!isPlainObject(t))throw fail("actions initializer should return a plain object containing actions");Object.keys(t).forEach((function(n){if(n===PRE_PROCESS_SNAPSHOT)throw fail("Cannot define action '"+PRE_PROCESS_SNAPSHOT+"', it should be defined using 'type.preProcessSnapshot(fn)' instead");if(n===POST_PROCESS_SNAPSHOT)throw fail("Cannot define action '"+POST_PROCESS_SNAPSHOT+"', it should be defined using 'type.postProcessSnapshot(fn)' instead");var r=t[n],i=e[n];if(n in Hook&&i){var o=r;r=function(){i.apply(null,arguments),o.apply(null,arguments)}}var a=r.$mst_middleware,s=r.bind(t);s.$mst_middleware=a;var p=createActionInvoker(e,n,s);t[n]=p,addHiddenFinalProp(e,n,p)}))},t.prototype.volatile=function(e){var t=this;return this.cloneAndEnhance({initializers:[function(n){return t.instantiateVolatileState(n,e(n)),n}]})},t.prototype.instantiateVolatileState=function(e,t){if(!isPlainObject(t))throw fail("volatile state initializer should return a plain object containing state");mobx.set(e,t)},t.prototype.extend=function(e){var t=this;return this.cloneAndEnhance({initializers:[function(n){var r=e(n),i=r.actions,o=r.views,a=r.state,s=__rest(r,["actions","views","state"]);for(var p in s)throw fail("The `extend` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '"+p+"'");return a&&t.instantiateVolatileState(n,a),o&&t.instantiateViews(n,o),i&&t.instantiateActions(n,i),n}]})},t.prototype.views=function(e){var t=this;return this.cloneAndEnhance({initializers:[function(n){return t.instantiateViews(n,e(n)),n}]})},t.prototype.instantiateViews=function(e,t){if(!isPlainObject(t))throw fail("views initializer should return a plain object containing views");Object.keys(t).forEach((function(n){var r=Object.getOwnPropertyDescriptor(t,n);if("get"in r)if(mobx.isComputedProp(e,n)){var i=mobx._getAdministration(e,n);i.derivation=r.get,i.scope=e,r.set&&(i.setter=mobx.action(i.name+"-setter",r.set))}else mobx.computed(e,n,r,!0);else{if("function"!=typeof r.value)throw fail("A view member should either be a function or getter based property");addHiddenFinalProp(e,n,r.value)}}))},t.prototype.instantiate=function(e,t,n,r){return createObjectNode(this,e,t,n,isStateTreeNode(r)?r:this.applySnapshotPreProcessor(r))},t.prototype.initializeChildNodes=function(e,t){void 0===t&&(t={});var n=e.type,r={};return n.forAllProps((function(n,i){r[n]=i.instantiate(e,n,void 0,t[n])})),r},t.prototype.createNewInstance=function(e){return mobx.observable.object(e,EMPTY_OBJECT,mobxShallow)},t.prototype.finalizeNewInstance=function(e,t){addHiddenFinalProp(t,"toString",objectTypeToString),this.forAllProps((function(n){mobx._interceptReads(t,n,e.unbox)})),this.initializers.reduce((function(e,t){return t(e)}),t),mobx.intercept(t,this.willChange),mobx.observe(t,this.didChange)},t.prototype.willChange=function(e){var t=e,n=getStateTreeNode(t.object),r=t.name;n.assertWritable({subpath:r});var i=n.type.properties[r];return i&&(typecheckInternal(i,t.newValue),t.newValue=i.reconcile(n.getChildNode(r),t.newValue,n,r)),t},t.prototype.didChange=function(e){var t=e,n=getStateTreeNode(t.object);if(n.type.properties[t.name]){var r=t.oldValue?t.oldValue.snapshot:void 0;n.emitPatch({op:"replace",path:escapeJsonPath(t.name),value:t.newValue.snapshot,oldValue:r},n)}},t.prototype.getChildren=function(e){var t=this,n=[];return this.forAllProps((function(r){n.push(t.getChildNode(e,r))})),n},t.prototype.getChildNode=function(e,t){if(!(t in this.properties))throw fail("Not a value property: "+t);var n=mobx._getAdministration(e.storedValue,t).value;if(!n)throw fail("Node not available for property "+t);return n},t.prototype.getSnapshot=function(e,t){var n=this;void 0===t&&(t=!0);var r={};return this.forAllProps((function(t,i){mobx.getAtom(e.storedValue,t).reportObserved(),r[t]=n.getChildNode(e,t).snapshot})),t?this.applySnapshotPostProcessor(r):r},t.prototype.processInitialSnapshot=function(e){var t={};return Object.keys(e).forEach((function(n){t[n]=e[n].getSnapshot()})),this.applySnapshotPostProcessor(t)},t.prototype.applyPatchLocally=function(e,t,n){if("replace"!==n.op&&"add"!==n.op)throw fail("object does not support operation "+n.op);e.storedValue[t]=n.value},t.prototype.applySnapshot=function(e,t){var n=this.applySnapshotPreProcessor(t);typecheckInternal(this,n),this.forAllProps((function(t){e.storedValue[t]=n[t]}))},t.prototype.applySnapshotPreProcessor=function(e){var t=this.preProcessor;return t?t.call(null,e):e},t.prototype.applySnapshotPostProcessor=function(e){var t=this.postProcessor;return t?t.call(null,e):e},t.prototype.getChildType=function(e){return this.properties[e]},t.prototype.isValidSnapshot=function(e,t){var n=this,r=this.applySnapshotPreProcessor(e);return isPlainObject(r)?flattenTypeErrors(this.propertyNames.map((function(e){return n.properties[e].validate(r[e],getContextForPath(t,e,n.properties[e]))}))):typeCheckFailure(t,r,"Value is not a plain object")},t.prototype.forAllProps=function(e){var t=this;this.propertyNames.forEach((function(n){return e(n,t.properties[n])}))},t.prototype.describe=function(){var e=this;return"{ "+this.propertyNames.map((function(t){return t+": "+e.properties[t].describe()})).join("; ")+" }"},t.prototype.getDefaultSnapshot=function(){return EMPTY_OBJECT},t.prototype.removeChild=function(e,t){e.storedValue[t]=void 0},__decorate([mobx.action],t.prototype,"applySnapshot",null),t}(ComplexType);function model(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="string"==typeof e[0]?e.shift():"AnonymousModel",r=e.shift()||{};return new ModelType({name:n,properties:r})}function compose(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="string"==typeof e[0],r=n?e[0]:"AnonymousModel";return n&&e.shift(),e.reduce((function(e,t){return e.cloneAndEnhance({name:e.name+"_"+t.name,properties:t.properties,initializers:t.initializers,preProcessor:function(n){return t.applySnapshotPreProcessor(e.applySnapshotPreProcessor(n))},postProcessor:function(n){return t.applySnapshotPostProcessor(e.applySnapshotPostProcessor(n))}})})).named(r)}function isModelType(e){return isType(e)&&(e.flags&TypeFlags.Object)>0}var CoreType=function(e){function t(t,n,r,i){void 0===i&&(i=identity);var o=e.call(this,t)||this;return o.flags=n,o.checker=r,o.initializer=i,o.flags=n,o}return __extends(t,e),t.prototype.describe=function(){return this.name},t.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,r)},t.prototype.createNewInstance=function(e){return this.initializer(e)},t.prototype.isValidSnapshot=function(e,t){return isPrimitive(e)&&this.checker(e)?typeCheckSuccess():typeCheckFailure(t,e,"Value is not a "+("Date"===this.name?"Date or a unix milliseconds timestamp":this.name))},t}(SimpleType),string=new CoreType("string",TypeFlags.String,(function(e){return"string"==typeof e})),number=new CoreType("number",TypeFlags.Number,(function(e){return"number"==typeof e})),integer=new CoreType("integer",TypeFlags.Integer,(function(e){return isInteger(e)})),boolean=new CoreType("boolean",TypeFlags.Boolean,(function(e){return"boolean"==typeof e})),nullType=new CoreType("null",TypeFlags.Null,(function(e){return null===e})),undefinedType=new CoreType("undefined",TypeFlags.Undefined,(function(e){return void 0===e})),_DatePrimitive=new CoreType("Date",TypeFlags.Date,(function(e){return"number"==typeof e||e instanceof Date}),(function(e){return e instanceof Date?e:new Date(e)}));_DatePrimitive.getSnapshot=function(e){return e.storedValue.getTime()};var DatePrimitive=_DatePrimitive;function getPrimitiveFactoryFromValue(e){switch(typeof e){case"string":return string;case"number":return number;case"boolean":return boolean;case"object":if(e instanceof Date)return DatePrimitive}throw fail("Cannot determine primitive type from value "+e)}function isPrimitiveType(e){return isType(e)&&(e.flags&(TypeFlags.String|TypeFlags.Number|TypeFlags.Integer|TypeFlags.Boolean|TypeFlags.Date))>0}var Literal=function(e){function t(t){var n=e.call(this,JSON.stringify(t))||this;return n.flags=TypeFlags.Literal,n.value=t,n}return __extends(t,e),t.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,r)},t.prototype.describe=function(){return JSON.stringify(this.value)},t.prototype.isValidSnapshot=function(e,t){return isPrimitive(e)&&e===this.value?typeCheckSuccess():typeCheckFailure(t,e,"Value is not a literal "+JSON.stringify(this.value))},t}(SimpleType);function literal(e){return new Literal(e)}function isLiteralType(e){return isType(e)&&(e.flags&TypeFlags.Literal)>0}var Refinement=function(e){function t(t,n,r,i){var o=e.call(this,t)||this;return o._subtype=n,o._predicate=r,o._message=i,o}return __extends(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.Refinement},enumerable:!0,configurable:!0}),t.prototype.describe=function(){return this.name},t.prototype.instantiate=function(e,t,n,r){return this._subtype.instantiate(e,t,n,r)},t.prototype.isAssignableFrom=function(e){return this._subtype.isAssignableFrom(e)},t.prototype.isValidSnapshot=function(e,t){var n=this._subtype.validate(e,t);if(n.length>0)return n;var r=isStateTreeNode(e)?getStateTreeNode(e).snapshot:e;return this._predicate(r)?typeCheckSuccess():typeCheckFailure(t,e,this._message(e))},t.prototype.reconcile=function(e,t,n,r){return this._subtype.reconcile(e,t,n,r)},t.prototype.getSubTypes=function(){return this._subtype},t}(BaseType);function refinement(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="string"==typeof e[0]?e.shift():isType(e[0])?e[0].name:null,r=e[0],i=e[1],o=e[2]?e[2]:function(e){return"Value does not respect the refinement predicate"};return new Refinement(n,r,i,o)}function isRefinementType(e){return(e.flags&TypeFlags.Refinement)>0}function enumeration(e,t){var n="string"==typeof e?t:e,r=union.apply(void 0,__spread(n.map((function(e){return literal(""+e)}))));return"string"==typeof e&&(r.name=e),r}var Union=function(e){function t(t,n,r){var i=e.call(this,t)||this;return i._types=n,i._eager=!0,r=__assign({eager:!0,dispatcher:void 0},r),i._dispatcher=r.dispatcher,r.eager||(i._eager=!1),i}return __extends(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=TypeFlags.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!0,configurable:!0}),t.prototype.isAssignableFrom=function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))},t.prototype.describe=function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"},t.prototype.instantiate=function(e,t,n,r){var i=this.determineType(r,void 0);if(!i)throw fail("No matching type for union "+this.describe());return i.instantiate(e,t,n,r)},t.prototype.reconcile=function(e,t,n,r){var i=this.determineType(t,e.type);if(!i)throw fail("No matching type for union "+this.describe());return i.reconcile(e,t,n,r)},t.prototype.determineType=function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))},t.prototype.isValidSnapshot=function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var n=[],r=0,i=0;i<this._types.length;i++){var o=this._types[i].validate(e,t);if(0===o.length){if(this._eager)return typeCheckSuccess();r++}else n.push(o)}return 1===r?typeCheckSuccess():typeCheckFailure(t,e,"No type is applicable for the union").concat(flattenTypeErrors(n))},t.prototype.getSubTypes=function(){return this._types},t}(BaseType);function union(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r=isType(e)?void 0:e,i=isType(e)?__spread([e],t):t,o="("+i.map((function(e){return e.name})).join(" | ")+")";return new Union(o,i,r)}function isUnionType(e){return(e.flags&TypeFlags.Union)>0}var OptionalValue=function(e){function t(t,n,r){var i=e.call(this,t.name)||this;return i._subtype=t,i._defaultValue=n,i.optionalValues=r,i}return __extends(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.Optional},enumerable:!0,configurable:!0}),t.prototype.describe=function(){return this._subtype.describe()+"?"},t.prototype.instantiate=function(e,t,n,r){if(this.optionalValues.indexOf(r)>=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,n,i)}return this._subtype.instantiate(e,t,n,r)},t.prototype.reconcile=function(e,t,n,r){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),n,r)},t.prototype.getDefaultInstanceOrSnapshot=function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&typecheckInternal(this,e),e},t.prototype.isValidSnapshot=function(e,t){return this.optionalValues.indexOf(e)>=0?typeCheckSuccess():this._subtype.validate(e,t)},t.prototype.isAssignableFrom=function(e){return this._subtype.isAssignableFrom(e)},t.prototype.getSubTypes=function(){return this._subtype},t}(BaseType);function checkOptionalPreconditions(e,t){if("function"!=typeof t&&isStateTreeNode(t))throw fail("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}function optional(e,t,n){return checkOptionalPreconditions(e,t),new OptionalValue(e,t,n||undefinedAsOptionalValues)}var undefinedAsOptionalValues=[void 0];function isOptionalType(e){return isType(e)&&(e.flags&TypeFlags.Optional)>0}var optionalUndefinedType=optional(undefinedType,void 0),optionalNullType=optional(nullType,null);function maybe(e){return union(e,optionalUndefinedType)}function maybeNull(e){return union(e,optionalNullType)}var Late=function(e){function t(t,n){var r=e.call(this,t)||this;return r._definition=n,r}return __extends(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|TypeFlags.Late},enumerable:!0,configurable:!0}),t.prototype.getSubType=function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw fail("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType},t.prototype.instantiate=function(e,t,n,r){return this.getSubType(!0).instantiate(e,t,n,r)},t.prototype.reconcile=function(e,t,n,r){return this.getSubType(!0).reconcile(e,t,n,r)},t.prototype.describe=function(){var e=this.getSubType(!1);return e?e.name:"<uknown late type>"},t.prototype.isValidSnapshot=function(e,t){var n=this.getSubType(!1);return n?n.validate(e,t):typeCheckSuccess()},t.prototype.isAssignableFrom=function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)},t.prototype.getSubTypes=function(){var e=this.getSubType(!1);return e||cannotDetermineSubtype},t}(BaseType);function late(e,t){var n="string"==typeof e?e:"late("+e.toString()+")";return new Late(n,"string"==typeof e?t:e)}function isLateType(e){return isType(e)&&(e.flags&TypeFlags.Late)>0}var Frozen=function(e){function t(t){var n=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return n.subType=t,n.flags=TypeFlags.Frozen,n}return __extends(t,e),t.prototype.describe=function(){return"<any immutable value>"},t.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,deepFreeze(r))},t.prototype.isValidSnapshot=function(e,t){return isSerializable(e)?this.subType?this.subType.validate(e,t):typeCheckSuccess():typeCheckFailure(t,e,"Value is not serializable and cannot be frozen")},t}(SimpleType),untypedFrozenInstance=new Frozen;function frozen(e){return 0===arguments.length?untypedFrozenInstance:isType(e)?new Frozen(e):optional(untypedFrozenInstance,e)}function isFrozenType(e){return isType(e)&&(e.flags&TypeFlags.Frozen)>0}function getInvalidationCause(e){switch(e){case Hook.beforeDestroy:return"destroy";case Hook.beforeDetach:return"detach";default:return}}var StoredReference=function(){function e(e,t){if(this.targetType=t,isValidIdentifier(e))this.identifier=e;else{if(!isStateTreeNode(e))throw fail("Can only store references to tree nodes or identifiers, got: '"+e+"'");var n=getStateTreeNode(e);if(!n.identifierAttribute)throw fail("Can only store references with a defined identifier attribute.");var r=n.unnormalizedIdentifier;if(null==r)throw fail("Can only store references to tree nodes with a defined identifier.");this.identifier=r}}return e.prototype.updateResolvedReference=function(e){var t=normalizeIdentifier(this.identifier),n=e.root,r=n.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==r){var i=this.targetType,o=n.identifierCache.resolve(i,t);if(!o)throw new InvalidReferenceError("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:r}}},Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!0,configurable:!0}),e}(),InvalidReferenceError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return __extends(t,e),t}(Error),BaseReferenceType=function(e){function t(t,n){var r=e.call(this,"reference("+t.name+")")||this;return r.targetType=t,r.onInvalidated=n,r.flags=TypeFlags.Reference,r}return __extends(t,e),t.prototype.describe=function(){return this.name},t.prototype.isAssignableFrom=function(e){return this.targetType.isAssignableFrom(e)},t.prototype.isValidSnapshot=function(e,t){return isValidIdentifier(e)?typeCheckSuccess():typeCheckFailure(t,e,"Value is not a valid identifier, which is a string or a number")},t.prototype.fireInvalidated=function(e,t,n,r){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:r?r.storedValue:void 0,invalidId:n,replaceRef:function(e){applyPatch(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){isModelType(i.type)?this.replaceRef(void 0):applyPatch(t.root.storedValue,{op:"remove",path:t.path})}})}},t.prototype.addTargetNodeWatcher=function(e,t){var n=this,r=this.getValue(e);if(r){var i=getStateTreeNode(r),o=function(r,o){var a=getInvalidationCause(o);a&&n.fireInvalidated(a,e,t,i)},a=i.registerHook(Hook.beforeDetach,o),s=i.registerHook(Hook.beforeDestroy,o);return function(){a(),s()}}},t.prototype.watchTargetNodeForInvalidations=function(e,t,n){var r=this;if(this.onInvalidated){var i;e.registerHook(Hook.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(n?!!n.get(t,s):e.root.identifierCache.has(r.targetType,normalizeIdentifier(t)))?i=r.addTargetNodeWatcher(e,t):o||r.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===NodeLifeCycle.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(Hook.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(Hook.afterAttach,(function(){o(!1)})))}},t}(SimpleType),IdentifierReferenceType=function(e){function t(t,n){return e.call(this,t,n)||this}return __extends(t,e),t.prototype.getValue=function(e){if(e.isAlive)return e.storedValue.resolvedValue},t.prototype.getSnapshot=function(e){return e.storedValue.identifier},t.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?getIdentifier(r):r,o=new StoredReference(r,this.targetType),a=createScalarNode(this,e,t,n,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a},t.prototype.reconcile=function(e,t,n,r){if(!e.isDetaching&&e.type===this){var i=isStateTreeNode(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(n,r),e}var a=this.instantiate(n,r,void 0,t);return e.die(),a},t}(BaseReferenceType),CustomReferenceType=function(e){function t(t,n,r){var i=e.call(this,t,r)||this;return i.options=n,i}return __extends(t,e),t.prototype.getValue=function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)},t.prototype.getSnapshot=function(e){return e.storedValue},t.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?this.options.set(r,e?e.storedValue:null):r,o=createScalarNode(this,e,t,n,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o},t.prototype.reconcile=function(e,t,n,r){var i=isStateTreeNode(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(n,r),e;var o=this.instantiate(n,r,void 0,i);return e.die(),o},t}(BaseReferenceType);function reference(e,t){var n=t||void 0,r=t?t.onInvalidated:void 0;return n&&(n.get||n.set)?new CustomReferenceType(e,{get:n.get,set:n.set},r):new IdentifierReferenceType(e,r)}function isReferenceType(e){return(e.flags&TypeFlags.Reference)>0}function safeReference(e,t){var n=reference(e,__assign(__assign({},t),{onInvalidated:function(e){e.removeRef()}}));return t&&!1===t.acceptsUndefined?n:maybe(n)}var BaseIdentifierType=function(e){function t(t,n){var r=e.call(this,t)||this;return r.validType=n,r.flags=TypeFlags.Identifier,r}return __extends(t,e),t.prototype.instantiate=function(e,t,n,r){if(!(e&&e.type instanceof ModelType))throw fail("Identifier types can only be instantiated as direct child of a model type");return createScalarNode(this,e,t,n,r)},t.prototype.reconcile=function(e,t,n,r){if(e.storedValue!==t)throw fail("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(n,r),e},t.prototype.isValidSnapshot=function(e,t){return typeof e!==this.validType?typeCheckFailure(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):typeCheckSuccess()},t}(SimpleType),IdentifierType=function(e){function t(){var t=e.call(this,"identifier","string")||this;return t.flags=TypeFlags.Identifier,t}return __extends(t,e),t.prototype.describe=function(){return"identifier"},t}(BaseIdentifierType),IdentifierNumberType=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return __extends(t,e),t.prototype.getSnapshot=function(e){return e.storedValue},t.prototype.describe=function(){return"identifierNumber"},t}(BaseIdentifierType),identifier=new IdentifierType,identifierNumber=new IdentifierNumberType;function isIdentifierType(e){return isType(e)&&(e.flags&TypeFlags.Identifier)>0}function normalizeIdentifier(e){return""+e}function isValidIdentifier(e){return"string"==typeof e||"number"==typeof e}function custom(e){return new CustomType(e)}var CustomType=function(e){function t(t){var n=e.call(this,t.name)||this;return n.options=t,n.flags=TypeFlags.Custom,n}return __extends(t,e),t.prototype.describe=function(){return this.name},t.prototype.isValidSnapshot=function(e,t){if(this.options.isTargetType(e))return typeCheckSuccess();var n=this.options.getValidationMessage(e);return n?typeCheckFailure(t,e,"Invalid value for type '"+this.name+"': "+n):typeCheckSuccess()},t.prototype.getSnapshot=function(e){return this.options.toSnapshot(e.storedValue)},t.prototype.instantiate=function(e,t,n,r){return createScalarNode(this,e,t,n,this.options.isTargetType(r)?r:this.options.fromSnapshot(r))},t.prototype.reconcile=function(e,t,n,r){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(n,r),e;var o=i?this.options.fromSnapshot(t):t,a=this.instantiate(n,r,void 0,o);return e.die(),a},t}(SimpleType),types={enumeration:enumeration,model:model,compose:compose,custom:custom,reference:reference,safeReference:safeReference,union:union,optional:optional,literal:literal,maybe:maybe,maybeNull:maybeNull,refinement:refinement,string:string,boolean:boolean,number:number,integer:integer,Date:DatePrimitive,map:map,array:array,frozen:frozen,identifier:identifier,identifierNumber:identifierNumber,late:late,undefined:undefinedType,null:nullType,snapshotProcessor:snapshotProcessor};exports.addDisposer=addDisposer,exports.addMiddleware=addMiddleware,exports.applyAction=applyAction,exports.applyPatch=applyPatch,exports.applySnapshot=applySnapshot,exports.cast=cast,exports.castFlowReturn=castFlowReturn,exports.castToReferenceSnapshot=castToReferenceSnapshot,exports.castToSnapshot=castToSnapshot,exports.clone=clone,exports.createActionTrackingMiddleware=createActionTrackingMiddleware,exports.createActionTrackingMiddleware2=createActionTrackingMiddleware2,exports.decorate=decorate,exports.destroy=destroy,exports.detach=detach,exports.escapeJsonPath=escapeJsonPath,exports.flow=flow,exports.getChildType=getChildType,exports.getEnv=getEnv,exports.getIdentifier=getIdentifier,exports.getLivelinessChecking=getLivelinessChecking,exports.getMembers=getMembers,exports.getNodeId=getNodeId,exports.getParent=getParent,exports.getParentOfType=getParentOfType,exports.getPath=getPath,exports.getPathParts=getPathParts,exports.getPropertyMembers=getPropertyMembers,exports.getRelativePath=getRelativePath,exports.getRoot=getRoot,exports.getRunningActionContext=getRunningActionContext,exports.getSnapshot=getSnapshot,exports.getType=getType,exports.hasParent=hasParent,exports.hasParentOfType=hasParentOfType,exports.isActionContextChildOf=isActionContextChildOf,exports.isActionContextThisOrChildOf=isActionContextThisOrChildOf,exports.isAlive=isAlive,exports.isArrayType=isArrayType,exports.isFrozenType=isFrozenType,exports.isIdentifierType=isIdentifierType,exports.isLateType=isLateType,exports.isLiteralType=isLiteralType,exports.isMapType=isMapType,exports.isModelType=isModelType,exports.isOptionalType=isOptionalType,exports.isPrimitiveType=isPrimitiveType,exports.isProtected=isProtected,exports.isReferenceType=isReferenceType,exports.isRefinementType=isRefinementType,exports.isRoot=isRoot,exports.isStateTreeNode=isStateTreeNode,exports.isType=isType,exports.isUnionType=isUnionType,exports.isValidReference=isValidReference,exports.joinJsonPath=joinJsonPath,exports.onAction=onAction,exports.onPatch=onPatch,exports.onSnapshot=onSnapshot,exports.process=process$1,exports.protect=protect,exports.recordActions=recordActions,exports.recordPatches=recordPatches,exports.resolveIdentifier=resolveIdentifier,exports.resolvePath=resolvePath,exports.setLivelinessChecking=setLivelinessChecking,exports.setLivelynessChecking=setLivelynessChecking,exports.splitJsonPath=splitJsonPath,exports.tryReference=tryReference,exports.tryResolve=tryResolve,exports.typecheck=typecheck,exports.types=types,exports.unescapeJsonPath=unescapeJsonPath,exports.unprotect=unprotect,exports.walk=walk;