g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n if (process.env.NODE_ENV !== \"production\") {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n if (typeof window !== \"undefined\") {\n return window;\n }\n if (typeof global !== \"undefined\") {\n return global;\n }\n if (typeof self !== \"undefined\") {\n return self;\n }\n return mockGlobal;\n}\n\n// We shorten anything used > 5 times\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die(process.env.NODE_ENV !== \"production\" ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : \"Proxy not available\");\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if (process.env.NODE_ENV !== \"production\" && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\n * Makes sure that the provided function is invoked at most once.\n */\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n var proto = Object.getPrototypeOf(value);\n if (proto == null) {\n return true;\n }\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n}\n// https://stackoverflow.com/a/37865170\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n if (!constructor) {\n return false;\n }\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\n/**\n * Yields true for both native and observable Map, even across different windows.\n */\nfunction isES6Map(thing) {\n return thing != null && Object.prototype.toString.call(thing) === \"[object Map]\";\n}\n/**\n * Makes sure a Map is an instance of non-inherited native or observable Map.\n */\nfunction isPlainES6Map(thing) {\n var mapProto = Object.getPrototypeOf(thing);\n var objectProto = Object.getPrototypeOf(mapProto);\n var nullProto = Object.getPrototypeOf(objectProto);\n return nullProto === null;\n}\n/**\n * Yields true for both native and observable Set, even across different windows.\n */\nfunction isES6Set(thing) {\n return thing != null && Object.prototype.toString.call(thing) === \"[object Set]\";\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\n * Returns the following: own enumerable keys and symbols.\n */\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object);\n // Not supported in IE, so there are not going to be symbol props anyway...\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n var symbols = Object.getOwnPropertySymbols(object);\n if (!symbols.length) {\n return keys;\n }\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n}\n// From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} : /* istanbul ignore next */Object.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n}\n// From Immer utils\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {};\n // Note: without polyfill for ownKeys, symbols won't be picked up\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\nfunction getFlag(flags, mask) {\n return !!(flags & mask);\n}\nfunction setFlag(flags, mask, newValue) {\n if (newValue) {\n flags |= mask;\n } else {\n flags &= ~mask;\n }\n return flags;\n}\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _defineProperties(e, r) {\n for (var t = 0; t < r.length; t++) {\n var o = r[t];\n o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);\n }\n}\nfunction _createClass(e, r, t) {\n return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", {\n writable: !1\n }), e;\n}\nfunction _createForOfIteratorHelperLoose(r, e) {\n var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (t) return (t = t.call(r)).next.bind(t);\n if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && \"number\" == typeof r.length) {\n t && (r = t);\n var o = 0;\n return function () {\n return o >= r.length ? {\n done: !0\n } : {\n done: !1,\n value: r[o++]\n };\n };\n }\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nfunction _inheritsLoose(t, o) {\n t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);\n}\nfunction _setPrototypeOf(t, e) {\n return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {\n return t.__proto__ = e, t;\n }, _setPrototypeOf(t, e);\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\n * Creates a function that acts as\n * - decorator\n * - annotation object\n */\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n if (is20223Decorator(property)) {\n return annotation.decorate_20223_(target, property);\n } else {\n storeAnnotation(target, property, annotation);\n }\n }\n return Object.assign(decorator, annotation);\n}\n/**\n * Stores annotation to prototype,\n * so it can be inspected later by `makeObservable` called from constructor\n */\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n }\n // @override must override something\n if (process.env.NODE_ENV !== \"production\" && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n }\n // Cannot re-decorate\n assertNotDecorated(prototype, annotation, key);\n // Ignore override\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\nfunction assertNotDecorated(prototype, annotation, key) {\n if (process.env.NODE_ENV !== \"production\" && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\n * Collects annotations from prototypes and stores them on target (instance)\n */\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n // if (__DEV__ && !target[storedAnnotationsSymbol]) {\n // die(\n // `No annotations were passed to makeObservable, but no decorated members have been found either`\n // )\n // }\n // We need a copy as we will remove annotation from the list once it's applied.\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n return target[storedAnnotationsSymbol];\n}\nfunction is20223Decorator(context) {\n return typeof context == \"object\" && typeof context[\"kind\"] == \"string\";\n}\nfunction assert20223DecoratorType(context, types) {\n if (process.env.NODE_ENV !== \"production\" && !types.includes(context.kind)) {\n die(\"The decorator applied to '\" + String(context.name) + \"' cannot be used on a \" + context.kind + \" element\");\n }\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n /**\n * Create a new atom. For debugging purposes it is recommended to give it a name.\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"Atom@\" + getNextId() : \"Atom\";\n }\n this.name_ = void 0;\n this.flags_ = 0;\n this.observers_ = new Set();\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n // onBecomeObservedListeners\n this.onBOL = void 0;\n // onBecomeUnobservedListeners\n this.onBUOL = void 0;\n this.name_ = name_;\n }\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n var _proto = Atom.prototype;\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\n * Invoke this method to notify mobx that your atom has been used somehow.\n * Returns true if there is currently a reactive context.\n */;\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\n */;\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n _proto.toString = function toString() {\n return this.name_;\n };\n return _createClass(Atom, [{\n key: \"isBeingObserved\",\n get: function get() {\n return getFlag(this.flags_, Atom.isBeingObservedMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Atom.isBeingObservedMask_, newValue);\n }\n }, {\n key: \"isPendingUnobservation\",\n get: function get() {\n return getFlag(this.flags_, Atom.isPendingUnobservationMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Atom.isPendingUnobservationMask_, newValue);\n }\n }, {\n key: \"diffValue\",\n get: function get() {\n return getFlag(this.flags_, Atom.diffValueMask_) ? 1 : 0;\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Atom.diffValueMask_, newValue === 1 ? true : false);\n }\n }]);\n}();\nAtom.isBeingObservedMask_ = 1;\nAtom.isPendingUnobservationMask_ = 2;\nAtom.diffValueMask_ = 4;\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n var atom = new Atom(name);\n // default `noop` listener will not initialize the hook Set\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n }\n // something that can be converted and mutated?\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n if (process.env.NODE_ENV !== \"production\") {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if (process.env.NODE_ENV !== \"production\" && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_,\n decorate_20223_: decorate_20223_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\nfunction make_(adm, key) {\n // Must not be plain object\n if (process.env.NODE_ENV !== \"production\" && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n }\n // Must override something\n if (process.env.NODE_ENV !== \"production\" && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n return 0 /* MakeResult.Cancel */;\n}\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\nfunction decorate_20223_(desc, context) {\n console.warn(\"'\" + this.annotationType_ + \"' cannot be used with decorators - this is a no-op\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1,\n decorate_20223_: decorate_20223_$1\n };\n}\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */;\n }\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */;\n }\n // prototype\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1 /* MakeResult.Break */;\n }\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2 /* MakeResult.Continue */;\n}\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\nfunction decorate_20223_$1(mthd, context) {\n if (process.env.NODE_ENV !== \"production\") {\n assert20223DecoratorType(context, [\"method\", \"field\"]);\n }\n var kind = context.kind,\n name = context.name,\n addInitializer = context.addInitializer;\n var ann = this;\n var _createAction = function _createAction(m) {\n var _ann$options_$name, _ann$options_, _ann$options_$autoAct, _ann$options_2;\n return createAction((_ann$options_$name = (_ann$options_ = ann.options_) == null ? void 0 : _ann$options_.name) != null ? _ann$options_$name : name.toString(), m, (_ann$options_$autoAct = (_ann$options_2 = ann.options_) == null ? void 0 : _ann$options_2.autoAction) != null ? _ann$options_$autoAct : false);\n };\n // Backwards/Legacy behavior, expects makeObservable(this)\n if (kind == \"field\") {\n addInitializer(function () {\n storeAnnotation(this, name, ann);\n });\n return;\n }\n if (kind == \"method\") {\n var _this$options_2;\n if (!isAction(mthd)) {\n mthd = _createAction(mthd);\n }\n if ((_this$options_2 = this.options_) != null && _this$options_2.bound) {\n addInitializer(function () {\n var self = this;\n var bound = self[name].bind(self);\n bound.isMobxAction = true;\n self[name] = bound;\n });\n }\n return mthd;\n }\n die(\"Cannot apply '\" + ann.annotationType_ + \"' to '\" + String(name) + \"' (kind: \" + kind + \"):\" + (\"\\n'\" + ann.annotationType_ + \"' can only be used on properties with a function value.\"));\n}\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n if (process.env.NODE_ENV !== \"production\" && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\nfunction createActionDescriptor(adm, annotation, key, descriptor,\n// provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false,\n // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2,\n decorate_20223_: decorate_20223_$2\n };\n}\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */;\n }\n // prototype\n // bound - must annotate protos to support super.flow()\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0 /* MakeResult.Cancel */;\n }\n }\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1 /* MakeResult.Break */;\n }\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2 /* MakeResult.Continue */;\n}\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\nfunction decorate_20223_$2(mthd, context) {\n var _this$options_3;\n if (process.env.NODE_ENV !== \"production\") {\n assert20223DecoratorType(context, [\"method\"]);\n }\n var name = context.name,\n addInitializer = context.addInitializer;\n if (!isFlow(mthd)) {\n mthd = flow(mthd);\n }\n if ((_this$options_3 = this.options_) != null && _this$options_3.bound) {\n addInitializer(function () {\n var self = this;\n var bound = self[name].bind(self);\n bound.isMobXFlow = true;\n self[name] = bound;\n });\n }\n return mthd;\n}\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n if (process.env.NODE_ENV !== \"production\" && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound,\n// provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n // In case of flow.bound, the descriptor can be from already annotated prototype\n if (!isFlow(value)) {\n value = flow(value);\n }\n if (bound) {\n var _adm$proxy_;\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n // This is normally set by `flow`, but `bind` returns new function...\n value.isMobXFlow = true;\n }\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3,\n decorate_20223_: decorate_20223_$3\n };\n}\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */;\n}\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\nfunction decorate_20223_$3(get, context) {\n if (process.env.NODE_ENV !== \"production\") {\n assert20223DecoratorType(context, [\"getter\"]);\n }\n var ann = this;\n var key = context.name,\n addInitializer = context.addInitializer;\n addInitializer(function () {\n var adm = asObservableObject(this)[$mobx];\n var options = _extends({}, ann.options_, {\n get: get,\n context: this\n });\n options.name || (options.name = process.env.NODE_ENV !== \"production\" ? adm.name_ + \".\" + key.toString() : \"ObservableObject.\" + key.toString());\n adm.values_.set(key, new ComputedValue(options));\n });\n return function () {\n return this[$mobx].getObservablePropValue_(key);\n };\n}\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n if (process.env.NODE_ENV !== \"production\" && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4,\n decorate_20223_: decorate_20223_$4\n };\n}\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */;\n}\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\nfunction decorate_20223_$4(desc, context) {\n if (process.env.NODE_ENV !== \"production\") {\n if (context.kind === \"field\") {\n throw die(\"Please use `@observable accessor \" + String(context.name) + \"` instead of `@observable \" + String(context.name) + \"`\");\n }\n assert20223DecoratorType(context, [\"accessor\"]);\n }\n var ann = this;\n var kind = context.kind,\n name = context.name;\n // The laziness here is not ideal... It's a workaround to how 2022.3 Decorators are implemented:\n // `addInitializer` callbacks are executed _before_ any accessors are defined (instead of the ideal-for-us right after each).\n // This means that, if we were to do our stuff in an `addInitializer`, we'd attempt to read a private slot\n // before it has been initialized. The runtime doesn't like that and throws a `Cannot read private member\n // from an object whose class did not declare it` error.\n // TODO: it seems that this will not be required anymore in the final version of the spec\n // See TODO: link\n var initializedObjects = new WeakSet();\n function initializeObservable(target, value) {\n var _ann$options_$enhance, _ann$options_;\n var adm = asObservableObject(target)[$mobx];\n var observable = new ObservableValue(value, (_ann$options_$enhance = (_ann$options_ = ann.options_) == null ? void 0 : _ann$options_.enhancer) != null ? _ann$options_$enhance : deepEnhancer, process.env.NODE_ENV !== \"production\" ? adm.name_ + \".\" + name.toString() : \"ObservableObject.\" + name.toString(), false);\n adm.values_.set(name, observable);\n initializedObjects.add(target);\n }\n if (kind == \"accessor\") {\n return {\n get: function get() {\n if (!initializedObjects.has(this)) {\n initializeObservable(this, desc.get.call(this));\n }\n return this[$mobx].getObservablePropValue_(name);\n },\n set: function set(value) {\n if (!initializedObjects.has(this)) {\n initializeObservable(this, value);\n }\n return this[$mobx].setObservablePropValue_(name, value);\n },\n init: function init(value) {\n if (!initializedObjects.has(this)) {\n initializeObservable(this, value);\n }\n return value;\n }\n };\n }\n return;\n}\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n if (process.env.NODE_ENV !== \"production\" && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5,\n decorate_20223_: decorate_20223_$5\n };\n}\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n }\n // lone setter -> action setter\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set);\n // own\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */;\n }\n // proto\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2 /* MakeResult.Continue */;\n }\n // function on proto -> autoAction/flow\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n }\n // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable;\n // if function respect autoBind option\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n }\n // lone setter -> action setter\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n }\n // other -> observable\n // if function respect autoBind option\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\nfunction decorate_20223_$5(desc, context) {\n die(\"'\" + this.annotationType_ + \"' cannot be used as a decorator\");\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\";\n// Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\n * Turns an object, array or function into a reactive structure.\n * @param v the value which should become observable.\n */\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp; (2022.3 Decorators)\n if (is20223Decorator(arg2)) {\n return observableAnnotation.decorate_20223_(v, arg2);\n }\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n }\n // already observable - ignore\n if (isObservable(v)) {\n return v;\n }\n // plain object\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n }\n // Array\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n }\n // Map\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n }\n // Set\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n }\n // other object - ignore\n if (typeof v === \"object\" && v !== null) {\n return v;\n }\n // anything else\n return observable.box(v, arg2);\n}\nassign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return initObservable(function () {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n });\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n};\n// eslint-disable-next-line\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\n * Decorator for class properties: @computed get value() { return expr; }.\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\n */\nvar computed = function computed(arg1, arg2) {\n if (is20223Decorator(arg2)) {\n // @computed (2022.3 Decorators)\n return computedAnnotation.decorate_20223_(arg1, arg2);\n }\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n }\n // computed(expr, options?)\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\"); /* for generated name */\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// we don't use globalState for these in order to avoid possible issues with multiple\n// mobx versions\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false;\n// we can safely recycle this object\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n res.isMobxAction = true;\n res.toString = function () {\n return fn.toString();\n };\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n defineProperty(res, \"name\", tmpNameDescriptor);\n }\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation,\n// true for autoAction\nscope, args) {\n var notifySpy_ = process.env.NODE_ENV !== \"production\" && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n if (process.env.NODE_ENV !== \"production\" && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n currentActionId = runInfo.parentActionId_;\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n if (process.env.NODE_ENV !== \"production\" && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar CREATE = \"create\";\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"ObservableValue@\" + getNextId() : \"ObservableValue\";\n }\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n if (process.env.NODE_ENV !== \"production\" && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _this,\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n return _this;\n }\n _inheritsLoose(ObservableValue, _Atom);\n var _proto = ObservableValue.prototype;\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n this.setNewValue_(newValue);\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n };\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n if (!change) {\n return globalState.UNCHANGED;\n }\n newValue = change.newValue;\n }\n // apply modifier\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n return registerListener(this, listener);\n };\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n _proto[Symbol.toPrimitive] = function () {\n return this.valueOf();\n };\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\n/**\n * A node in the state dependency root that observes other nodes, and can be observed itself.\n *\n * ComputedValue will remember the result of the computation for the duration of the batch, or\n * while being observed.\n *\n * During this time it will recompute only when one of its direct dependencies changed,\n * but only when it is being accessed with `ComputedValue.get()`.\n *\n * Implementation description:\n * 1. First time it's being accessed it will compute and remember result\n * give back remembered result until 2. happens\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\n * 3. When it's being accessed, recompute if any shallow dependency changed.\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\n * go to step 2. either way\n *\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\n */\nvar ComputedValue = /*#__PURE__*/function () {\n /**\n * Create a new computed value based on a function expression.\n *\n * The `name` property is for debug purposes only.\n *\n * The `equals` property specifies the comparer function to use to determine if a newly produced\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\n * Structural comparison can be convenient if you always produce a new aggregated object and\n * don't want to notify observers if it is structurally the same.\n * This is useful for working with vectors, mouse coordinates etc.\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n // nodes we are looking at. Our value depends on these nodes\n this.newObserving_ = null;\n // during tracking it's an array with new observed observers\n this.observers_ = new Set();\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.flags_ = 0;\n this.derivation = void 0;\n // N.B: unminified as it is used by MST\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n if (!options.get) {\n die(31);\n }\n this.derivation = options.get;\n this.name_ = options.name || (process.env.NODE_ENV !== \"production\" ? \"ComputedValue@\" + getNextId() : \"ComputedValue\");\n if (options.set) {\n this.setter_ = createAction(process.env.NODE_ENV !== \"production\" ? this.name_ + \"-setter\" : \"ComputedValue-setter\", options.set);\n }\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n var _proto = ComputedValue.prototype;\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n // to check for cycles\n ;\n /**\n * Returns the current value of this computed value.\n * Will evaluate its computation first if needed.\n */\n _proto.get = function get() {\n if (this.isComputing) {\n die(32, this.name_, this.derivation);\n }\n if (globalState.inBatch === 0 &&\n // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n globalState.trackingContext = prevTrackingContext;\n }\n }\n var result = this.value_;\n if (isCaughtException(result)) {\n throw result.cause;\n }\n return result;\n };\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter) {\n die(33, this.name_);\n }\n this.isRunningSetter = true;\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended = /* see #1208 */this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n if (changed) {\n this.value_ = newValue;\n if (process.env.NODE_ENV !== \"production\" && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n return changed;\n };\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing = true;\n // don't allow state changes during computation\n var prev = allowStateChangesStart(false);\n var res;\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n allowStateChangesEnd(prev);\n this.isComputing = false;\n return res;\n };\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n if (process.env.NODE_ENV !== \"production\" && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n firstTime = false;\n prevValue = newValue;\n });\n };\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n _proto[Symbol.toPrimitive] = function () {\n return this.valueOf();\n };\n return _createClass(ComputedValue, [{\n key: \"isComputing\",\n get: function get() {\n return getFlag(this.flags_, ComputedValue.isComputingMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, ComputedValue.isComputingMask_, newValue);\n }\n }, {\n key: \"isRunningSetter\",\n get: function get() {\n return getFlag(this.flags_, ComputedValue.isRunningSetterMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, ComputedValue.isRunningSetterMask_, newValue);\n }\n }, {\n key: \"isBeingObserved\",\n get: function get() {\n return getFlag(this.flags_, ComputedValue.isBeingObservedMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, ComputedValue.isBeingObservedMask_, newValue);\n }\n }, {\n key: \"isPendingUnobservation\",\n get: function get() {\n return getFlag(this.flags_, ComputedValue.isPendingUnobservationMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, ComputedValue.isPendingUnobservationMask_, newValue);\n }\n }, {\n key: \"diffValue\",\n get: function get() {\n return getFlag(this.flags_, ComputedValue.diffValueMask_) ? 1 : 0;\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, ComputedValue.diffValueMask_, newValue === 1 ? true : false);\n }\n }]);\n}();\nComputedValue.isComputingMask_ = 1;\nComputedValue.isRunningSetterMask_ = 2;\nComputedValue.isBeingObservedMask_ = 4;\nComputedValue.isPendingUnobservationMask_ = 8;\nComputedValue.diffValueMask_ = 16;\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\";\n // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\";\n // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\";\n // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\nvar TraceMode;\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause;\n // Empty\n};\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\n * Finds out whether any dependency of the derivation has actually changed.\n * If dependenciesState is 1 then it will recalculate dependencies,\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\n *\n * By iterating over the dependencies in the same order that they were reported and\n * stopping on the first change, all the recalculations are only called for ComputedValues\n * that will be tracked by derivation. That is because we assume that if the first x\n * dependencies of the derivation doesn't change then the derivation should run the same way\n * up until accessing x-th dependency.\n */\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n var obs = derivation.observing_,\n l = obs.length;\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n var hasObservers = atom.observers_.size > 0;\n // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if (process.env.NODE_ENV !== \"production\" && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\n * Executes the provided function `f` and tracks which observables are being accessed.\n * The tracking information is stored on the `derivation` object and the derivation is registered\n * as observer of any of the accessed observables.\n */\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true);\n changeDependenciesStateTo0(derivation);\n // Preallocate array; will be trimmed by bindDependencies.\n derivation.newObserving_ = new Array(\n // Reserve constant space for initial dependencies, dynamic space otherwise.\n // See https://github.com/mobxjs/mobx/pull/3833\n derivation.runId_ === 0 ? 100 : derivation.observing_.length);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n if (derivation.observing_.length !== 0) {\n return;\n }\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\n * diffs newObserving with observing.\n * update observing to be newObserving with unique observables\n * notify observers that become observed/unobserved\n */\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_;\n // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n if (dep.diffValue === 0) {\n dep.diffValue = 1;\n if (i0 !== i) {\n observing[i0] = dep;\n }\n i0++;\n }\n // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n l = prevObserving.length;\n while (l--) {\n var _dep = prevObserving[l];\n if (_dep.diffValue === 0) {\n removeObserver(_dep, derivation);\n }\n _dep.diffValue = 0;\n }\n // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n while (i0--) {\n var _dep2 = observing[i0];\n if (_dep2.diffValue === 1) {\n _dep2.diffValue = 0;\n addObserver(_dep2, derivation);\n }\n }\n // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\n *\n */\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\n * These values will persist if global state is reset\n */\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n /**\n * MobXGlobals version.\n * MobX compatiblity with other versions loaded in memory as long as this version matches.\n * It indicates that the global state still stores similar information\n *\n * N.B: this version is unrelated to the package version of MobX, and is only the version of the\n * internal state storage of MobX, and can be the same across many different package versions\n */\n this.version = 6;\n /**\n * globally unique token to signal unchanged\n */\n this.UNCHANGED = {};\n /**\n * Currently running derivation\n */\n this.trackingDerivation = null;\n /**\n * Currently running reaction. This determines if we currently have a reactive context.\n * (Tracking derivation is also set for temporal tracking of computed values inside actions,\n * but trackingReaction can only be set by a form of Reaction)\n */\n this.trackingContext = null;\n /**\n * Each time a derivation is tracked, it is assigned a unique run-id\n */\n this.runId = 0;\n /**\n * 'guid' for general purpose. Will be persisted amongst resets.\n */\n this.mobxGuid = 0;\n /**\n * Are we in a batch block? (and how many of them)\n */\n this.inBatch = 0;\n /**\n * Observables that don't have observers anymore, and are about to be\n * suspended, unless somebody else accesses it in the same batch\n *\n * @type {IObservable[]}\n */\n this.pendingUnobservations = [];\n /**\n * List of scheduled, not yet executed, reactions.\n */\n this.pendingReactions = [];\n /**\n * Are we currently processing reactions?\n */\n this.isRunningReactions = false;\n /**\n * Is it allowed to change observables at this point?\n * In general, MobX doesn't allow that when running computations and React.render.\n * To ensure that those functions stay pure.\n */\n this.allowStateChanges = false;\n /**\n * Is it allowed to read observables at this point?\n * Used to hold the state needed for `observableRequiresReaction`\n */\n this.allowStateReads = true;\n /**\n * If strict mode is enabled, state changes are by default not allowed\n */\n this.enforceActions = true;\n /**\n * Spy callbacks\n */\n this.spyListeners = [];\n /**\n * Globally attached error handlers that react specifically to errors in reactions\n */\n this.globalReactionErrorHandlers = [];\n /**\n * Warn if computed values are accessed outside a reactive context\n */\n this.computedRequiresReaction = false;\n /**\n * (Experimental)\n * Warn if you try to create to derivation / reactive context without accessing any observable.\n */\n this.reactionRequiresObservable = false;\n /**\n * (Experimental)\n * Warn if observables are accessed outside a reactive context\n */\n this.observableRequiresReaction = false;\n /*\n * Don't catch and rethrow exceptions. This is useful for inspecting the state of\n * the stack when an exception occurs while debugging.\n */\n this.disableErrorBoundaries = false;\n /*\n * If true, we are already handling an exception in an action. Any errors in reactions should be suppressed, as\n * they are not the cause, see: https://github.com/mobxjs/mobx/issues/1836\n */\n this.suppressReactionErrors = false;\n this.useProxies = true;\n /*\n * print warnings about code that would fail if proxies weren't available\n */\n this.verifyProxies = false;\n /**\n * False forces all object's descriptors to\n * writable: true\n * configurable: true\n */\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n isolateCalled = true;\n if (canMergeGlobalState) {\n var global = getGlobal();\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\n * For testing purposes only; this will break the internal state of existing observables,\n * but can be used to get back at a stable state after throwing errors\n */\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n}\n// function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n }\n // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n}\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n }\n // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n}\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\n * Avoids unnecessary recalculations.\n */\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions();\n // the batch is actually about to finish, all unobserving should happen here.\n var list = globalState.pendingUnobservations;\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation = false;\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved = false;\n observable.onBUO();\n }\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n if (derivation !== null) {\n /**\n * Simple optimization, give each derivation run an unique id (runId)\n * Check if last time this observable was accessed the same runId is used\n * if this is the case, the relation is already known\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_;\n // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n if (!observable.isBeingObserved && globalState.trackingContext) {\n observable.isBeingObserved = true;\n observable.onBO();\n }\n }\n return observable.isBeingObserved;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n return false;\n}\n// function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n/**\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\n * It will propagate changes to observers from previous run\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\n * Hopefully self reruning autoruns aren't a feature people should depend on\n * Also most basic use cases should be ok\n */\n// Called by Atom when its value changes\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n // Ideally we use for..of here, but the downcompiled version is really slow...\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if (process.env.NODE_ENV !== \"production\" && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n d.onBecomeStale_();\n }\n d.dependenciesState_ = IDerivationState_.STALE_;\n });\n // invariantLOS(observable, \"changed end\");\n}\n// Called by ComputedValue when it recalculate and its value changed\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n if (process.env.NODE_ENV !== \"production\" && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n });\n // invariantLOS(observable, \"confirmed end\");\n}\n// Used by computed when its dependency changed, but we don't wan't to immediately recompute.\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n });\n // invariantLOS(observable, \"maybe end\");\n}\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1);\n // prettier-ignore\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"Reaction@\" + getNextId() : \"Reaction\";\n }\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n // nodes we are looking at. Our value depends on these nodes\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.flags_ = 0;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n var _proto = Reaction.prototype;\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled) {\n this.isScheduled = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n }\n /**\n * internal, use schedule() if you intend to kick off a reaction\n */;\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed) {\n startBatch();\n this.isScheduled = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n if (shouldCompute(this)) {\n this.isTrackPending = true;\n try {\n this.onInvalidate_();\n if (process.env.NODE_ENV !== \"production\" && this.isTrackPending && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n _proto.track = function track(fn) {\n if (this.isDisposed) {\n return;\n // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n if (process.env.NODE_ENV !== \"production\" && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n this.isRunning = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning = false;\n this.isTrackPending = false;\n if (this.isDisposed) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n if (process.env.NODE_ENV !== \"production\" && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n endBatch();\n };\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n var message = process.env.NODE_ENV !== \"production\" ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : \"[mobx] uncaught error in '\" + this + \"'\";\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n if (process.env.NODE_ENV !== \"production\" && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n _proto.dispose = function dispose() {\n if (!this.isDisposed) {\n this.isDisposed = true;\n if (!this.isRunning) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n _proto.getDisposer_ = function getDisposer_(abortSignal) {\n var _this2 = this;\n var dispose = function dispose() {\n _this2.dispose();\n abortSignal == null || abortSignal.removeEventListener == null || abortSignal.removeEventListener(\"abort\", dispose);\n };\n abortSignal == null || abortSignal.addEventListener == null || abortSignal.addEventListener(\"abort\", dispose);\n dispose[$mobx] = this;\n return dispose;\n };\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n trace(this, enterBreakPoint);\n };\n return _createClass(Reaction, [{\n key: \"isDisposed\",\n get: function get() {\n return getFlag(this.flags_, Reaction.isDisposedMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Reaction.isDisposedMask_, newValue);\n }\n }, {\n key: \"isScheduled\",\n get: function get() {\n return getFlag(this.flags_, Reaction.isScheduledMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Reaction.isScheduledMask_, newValue);\n }\n }, {\n key: \"isTrackPending\",\n get: function get() {\n return getFlag(this.flags_, Reaction.isTrackPendingMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Reaction.isTrackPendingMask_, newValue);\n }\n }, {\n key: \"isRunning\",\n get: function get() {\n return getFlag(this.flags_, Reaction.isRunningMask_);\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Reaction.isRunningMask_, newValue);\n }\n }, {\n key: \"diffValue\",\n get: function get() {\n return getFlag(this.flags_, Reaction.diffValueMask_) ? 1 : 0;\n },\n set: function set(newValue) {\n this.flags_ = setFlag(this.flags_, Reaction.diffValueMask_, newValue === 1 ? true : false);\n }\n }]);\n}();\nReaction.isDisposedMask_ = 1;\nReaction.isScheduledMask_ = 2;\nReaction.isTrackPendingMask_ = 4;\nReaction.isRunningMask_ = 8;\nReaction.diffValueMask_ = 16;\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\n * Magic number alert!\n * Defines within how many times a reaction is allowed to re-trigger itself\n * until it is assumed that this is gonna be a never ending loop...\n */\nvar MAX_REACTION_ITERATIONS = 100;\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n reactionScheduler(runReactionsHelper);\n}\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0;\n // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error(process.env.NODE_ENV !== \"production\" ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : \"[mobx] cycle in reaction: \" + allReactions[0]);\n allReactions.splice(0); // clear reactions\n }\n var remainingReactions = allReactions.splice(0);\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n globalState.isRunningReactions = false;\n}\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return process.env.NODE_ENV !== \"production\" && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n } // dead code elimination can do the rest\n if (!globalState.spyListeners.length) {\n return;\n }\n var listeners = globalState.spyListeners;\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n var change = _extends({}, event, {\n spyReportStart: true\n });\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n console.warn(\"[mobx.spy] Is a no-op in production builds\");\n return function () {};\n } else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n }\n // action(\"name\", fn() {})\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n }\n // @action (2022.3 Decorators)\n if (is20223Decorator(arg2)) {\n return (autoAction ? autoActionAnnotation : actionAnnotation).decorate_20223_(arg1, arg2);\n }\n // @action\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n }\n // action(\"name\") & @action(\"name\")\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n if (process.env.NODE_ENV !== \"production\") {\n die(\"Invalid arguments for `action`\");\n }\n };\n return res;\n}\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\n * Creates a named reactive view and keeps it alive, so that the view is always\n * updated if one of the dependencies changes, even when the view is not further used by something else.\n * @param view The reactive view\n * @returns disposer function, which can be used to stop the view from being updated in the future.\n */\nfunction autorun(view, opts) {\n var _opts$name, _opts, _opts2, _opts3;\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : process.env.NODE_ENV !== \"production\" ? view.name || \"Autorun@\" + getNextId() : \"Autorun\";\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts);\n // debounced autorun\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n if (!reaction.isDisposed) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n function reactionRunner() {\n view(reaction);\n }\n if (!((_opts2 = opts) != null && (_opts2 = _opts2.signal) != null && _opts2.aborted)) {\n reaction.schedule_();\n }\n return reaction.getDisposer_((_opts3 = opts) == null ? void 0 : _opts3.signal);\n}\nvar run = function run(f) {\n return f();\n};\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\nfunction reaction(expression, effect, opts) {\n var _opts$name2, _opts4, _opts5;\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : process.env.NODE_ENV !== \"production\" ? \"Reaction@\" + getNextId() : \"Reaction\";\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n function reactionRunner() {\n isScheduled = false;\n if (r.isDisposed) {\n return;\n }\n var changed = false;\n var oldValue = value;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n value = nextValue;\n });\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n firstTime = false;\n }\n if (!((_opts4 = opts) != null && (_opts4 = _opts4.signal) != null && _opts4.aborted)) {\n r.schedule_();\n }\n return r.getDisposer_((_opts5 = opts) == null ? void 0 : _opts5.signal);\n}\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n return function () {\n var hookListeners = atom[listenersKey];\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\";\n// const IF_AVAILABLE = \"ifavailable\"\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n if (process.env.NODE_ENV !== \"production\" && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (process.env.NODE_ENV !== \"production\") {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n }\n // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n var descriptors = getOwnPropertyDescriptors(properties);\n initObservable(function () {\n var adm = asObservableObject(target, options)[$mobx];\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key],\n // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n });\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n return result;\n}\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n return result;\n}\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow (2022.3 Decorators)\n if (is20223Decorator(arg2)) {\n return flowAnnotation.decorate_20223_(arg1, arg2);\n }\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n }\n // flow(fn)\n if (process.env.NODE_ENV !== \"production\" && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n var generator = arg1;\n var name = generator.name || \"\";\n // Implementation based on https://github.com/tj/co/blob/master/index.js\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n next(ret);\n }\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n next(ret);\n }\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n if (ret.done) {\n return resolve(ret.value);\n }\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n onFulfilled(undefined); // kick off the process\n });\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n }\n // Finally block can return (or yield) stuff..\n var _res = gen[\"return\"](undefined);\n // eat anything that promise would do, it's cancelled!\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n return promise;\n };\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if (process.env.NODE_ENV !== \"production\" && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n target = getAdministration(thing, propOrHandler);\n } else if (process.env.NODE_ENV !== \"production\") {\n return die(\"Expected observable map, object or array as first array\");\n }\n if (process.env.NODE_ENV !== \"production\" && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n if (isObservableObject(value) === false) {\n return false;\n }\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if (process.env.NODE_ENV !== \"production\" && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if (process.env.NODE_ENV !== \"production\" && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n if (property !== undefined) {\n if (process.env.NODE_ENV !== \"production\" && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n return false;\n }\n // For first check, see #701\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\nfunction isObservable(value) {\n if (process.env.NODE_ENV !== \"production\" && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if (process.env.NODE_ENV !== \"production\" && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n return;\n }\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n startBatch();\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\n * Recursively converts an observable to it's non-observable native counterpart.\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\n * Computed and other non-enumerable properties are completely ignored.\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\n */\nfunction toJS(source, options) {\n if (process.env.NODE_ENV !== \"production\" && options) {\n die(\"toJS no longer supports options\");\n }\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n var enterBreakPoint = false;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n var derivation = getAtomFromArgs(args);\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n case 1:\n return getAtom(args[0]);\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\n * During a transaction no views are updated until the end of the transaction.\n * The transaction will be run synchronously nonetheless.\n *\n * @param action a function that updates some reactive state\n * @returns any value that was returned by the 'action' parameter.\n */\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n startBatch();\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n return _when(predicate, arg1, arg2 || {});\n}\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed) {\n disposer();\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n opts.name = process.env.NODE_ENV !== \"production\" ? opts.name || \"When@\" + getNextId() : \"When\";\n var effectAction = createAction(process.env.NODE_ENV !== \"production\" ? opts.name + \"-effect\" : \"When-effect\", effect);\n // eslint-disable-next-line\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n if (cond) {\n r.dispose();\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n effectAction();\n }\n }, opts);\n return disposer;\n}\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n if (process.env.NODE_ENV !== \"production\" && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n opts == null || (_opts$signal2 = opts.signal) == null || _opts$signal2.addEventListener == null || _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n return opts == null || (_opts$signal3 = opts.signal) == null || _opts$signal3.removeEventListener == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n}\n// Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\nvar objectProxyTraps = {\n has: function has(target, name) {\n if (process.env.NODE_ENV !== \"production\" && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n if (!isStringish(name)) {\n return false;\n }\n if (process.env.NODE_ENV !== \"production\" && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n }\n // null (intercepted) -> true (success)\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n if (process.env.NODE_ENV !== \"production\") {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n if (!isStringish(name)) {\n return false;\n }\n // null (intercepted) -> true (success)\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n if (process.env.NODE_ENV !== \"production\") {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n }\n // null (intercepted) -> true (success)\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if (process.env.NODE_ENV !== \"production\" && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n if (change && !change.type) {\n die(14);\n }\n if (!change) {\n break;\n }\n }\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n if (!listeners) {\n return;\n }\n listeners = listeners.slice();\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n initObservable(function () {\n var _annotations;\n var adm = asObservableObject(target, options)[$mobx];\n if (process.env.NODE_ENV !== \"production\" && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n }\n // Default to decorators\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target);\n // Annotate\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n });\n return target;\n}\n// proto[keysSymbol] = new Set()\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n }\n // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n initObservable(function () {\n var adm = asObservableObject(target, options)[$mobx];\n // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key,\n // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n });\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n if (name === $mobx) {\n return adm;\n }\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = process.env.NODE_ENV !== \"production\" ? \"ObservableArray@\" + getNextId() : \"ObservableArray\";\n }\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n // this is the prop that gets proxied, so can't replace it!\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, process.env.NODE_ENV !== \"production\" ? name + \"[..]\" : \"ObservableArray[..]\");\n };\n }\n var _proto = ObservableArrayAdministration.prototype;\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n return values;\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n return registerListener(this, listener);\n };\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n var currentLength = this.values_.length;\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n this.lastKnownLength_ += delta;\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n if (!change) {\n return EMPTY_ARRAY;\n }\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n if (this.legacyMode_ || process.env.NODE_ENV !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n return this.dehanceValues_(res);\n };\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount);\n // The items that that should remain at the end of the array\n var oldItems = this.values_.slice(index + deleteCount);\n // New length is the previous length + addition count - deletion count\n this.values_.length += newItems.length - deleteCount;\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n return res;\n }\n };\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null;\n // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n }\n this.atom_.reportChanged();\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n };\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n }\n this.atom_.reportChanged();\n // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n };\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn(process.env.NODE_ENV !== \"production\" ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : \"[mobx] Out of bounds read: \" + index);\n return undefined;\n }\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n // since \"this\" is the real array we need to pass its proxy\n index: index,\n newValue: newValue\n });\n if (!change) {\n return;\n }\n newValue = change.newValue;\n }\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = process.env.NODE_ENV !== \"production\" ? \"ObservableArray@\" + getNextId() : \"ObservableArray\";\n }\n if (owned === void 0) {\n owned = false;\n }\n assertProxies();\n return initObservable(function () {\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n if (initialValues && initialValues.length) {\n adm.spliceWithArray_(0, 0, initialValues);\n }\n return proxy;\n });\n}\n// eslint-disable-next-line\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n /*\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\n * since these functions alter the inner structure of the array, the have side effects.\n * Because the have side effects, they should not be used in computed function,\n * and for that reason the do not call dependencyState.notifyObserved\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n var adm = this[$mobx];\n switch (arguments.length) {\n case 0:\n return [];\n case 1:\n return adm.spliceWithArray_(index);\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n return false;\n }\n};\n/**\n * Wrap function from prototype\n * Without this, everything works as well, but this works\n * faster as everything works on unproxied values\n */\naddArrayExtension(\"at\", simpleFunc);\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc);\naddArrayExtension(\"toSorted\", simpleFunc);\naddArrayExtension(\"toSpliced\", simpleFunc);\naddArrayExtension(\"with\", simpleFunc);\n// map\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"findLast\", mapLikeFunc);\naddArrayExtension(\"findLastIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc);\naddArrayExtension(\"toReversed\", mapLikeFunc);\n// reduce\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n}\n// Report and delegate to dehanced array\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n// Make sure callbacks receive correct array arg #2326\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n}\n// Make sure callbacks receive correct array arg #2326\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n // #2432 - reduce behavior depends on arguments.length\n var callback = arguments[0];\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\";\n// just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\nvar ObservableMap = /*#__PURE__*/function () {\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"ObservableMap@\" + getNextId() : \"ObservableMap\";\n }\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n // hasMap, not hashMap >-).\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n if (!isFunction(Map)) {\n die(18);\n }\n initObservable(function () {\n _this.keysAtom_ = createAtom(process.env.NODE_ENV !== \"production\" ? _this.name_ + \".keys()\" : \"ObservableMap.keys()\");\n _this.data_ = new Map();\n _this.hasMap_ = new Map();\n if (initialData) {\n _this.merge(initialData);\n }\n });\n }\n var _proto = ObservableMap.prototype;\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n _proto.has = function has(key) {\n var _this2 = this;\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n var entry = this.hasMap_.get(key);\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + stringifyKey(key) + \"?\" : \"ObservableMap.key?\", false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n return entry.get();\n };\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n if (!change) {\n return this;\n }\n value = change.newValue;\n }\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n return this;\n };\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n if (!change) {\n return false;\n }\n }\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n transaction(function () {\n var _this3$hasMap_$get;\n _this3.keysAtom_.reportChanged();\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null || _this3$hasMap_$get.setNewValue_(false);\n var observable = _this3.data_.get(key);\n observable.setNewValue_(undefined);\n _this3.data_[\"delete\"](key);\n });\n if (notify) {\n notifyListeners(this, _change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n return true;\n }\n return false;\n };\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n observable.setNewValue_(newValue);\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n };\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n var observable = new ObservableValue(newValue, _this4.enhancer_, process.env.NODE_ENV !== \"production\" ? _this4.name_ + \".\" + stringifyKey(key) : \"ObservableMap.key\", false);\n _this4.data_.set(key, observable);\n newValue = observable.value_; // value might have been changed\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null || _this4$hasMap_$get.setNewValue_(true);\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n };\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n return this.dehanceValue_(undefined);\n };\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n _proto[Symbol.iterator] = function () {\n return this.entries();\n };\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */;\n _proto.merge = function merge(other) {\n var _this5 = this;\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (!isPlainES6Map(other)) {\n die(19, other);\n }\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n _proto.clear = function clear() {\n var _this6 = this;\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n _this6[\"delete\"](key);\n }\n });\n });\n };\n _proto.replace = function replace(values) {\n var _this7 = this;\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map();\n // Used for optimization\n var keysReportChangedCalled = false;\n // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key);\n // Was the key removed?\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n orderedData.set(key, value);\n }\n }\n }\n // Merge entries\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key);\n // Add or update value\n _this7.set(_key, _value);\n // The addition could have been prevent by interceptor\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n orderedData.set(_key, _value2);\n // Was a new key added?\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n }\n // Check for possible key order change\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n break;\n }\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n }\n // Use correctly ordered map\n _this7.data_ = orderedData;\n });\n return this;\n };\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n /**\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\n * for callback details\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (process.env.NODE_ENV !== \"production\" && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n return registerListener(this, listener);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n return _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: Symbol.toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n}();\n// eslint-disable-next-line\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar ObservableSetMarker = {};\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n var _this = this;\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"ObservableSet@\" + getNextId() : \"ObservableSet\";\n }\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n if (!isFunction(Set)) {\n die(22);\n }\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n initObservable(function () {\n _this.atom_ = createAtom(_this.name_);\n if (initialData) {\n _this.replace(initialData);\n }\n });\n }\n var _proto = ObservableSet.prototype;\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.clear = function clear() {\n var _this2 = this;\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this2.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n _this2[\"delete\"](value);\n }\n });\n });\n };\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n _proto.add = function add(value) {\n var _this3 = this;\n checkIfStateModificationsAreAllowed(this.atom_);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n if (!change) {\n return this;\n }\n // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n }\n if (!this.has(value)) {\n transaction(function () {\n _this3.data_.add(_this3.enhancer_(value, undefined));\n _this3.atom_.reportChanged();\n });\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var notify = hasListeners(this);\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportStart(_change);\n }\n if (notify) {\n notifyListeners(this, _change);\n }\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportEnd();\n }\n }\n return this;\n };\n _proto[\"delete\"] = function _delete(value) {\n var _this4 = this;\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n if (!change) {\n return false;\n }\n }\n if (this.has(value)) {\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var notify = hasListeners(this);\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportStart(_change2);\n }\n transaction(function () {\n _this4.atom_.reportChanged();\n _this4.data_[\"delete\"](value);\n });\n if (notify) {\n notifyListeners(this, _change2);\n }\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportEnd();\n }\n return true;\n }\n return false;\n };\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n _proto.keys = function keys() {\n return this.values();\n };\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n _proto.intersection = function intersection(otherSet) {\n if (isES6Set(otherSet) && !isObservableSet(otherSet)) {\n return otherSet.intersection(this);\n } else {\n var dehancedSet = new Set(this);\n return dehancedSet.intersection(otherSet);\n }\n };\n _proto.union = function union(otherSet) {\n if (isES6Set(otherSet) && !isObservableSet(otherSet)) {\n return otherSet.union(this);\n } else {\n var dehancedSet = new Set(this);\n return dehancedSet.union(otherSet);\n }\n };\n _proto.difference = function difference(otherSet) {\n return new Set(this).difference(otherSet);\n };\n _proto.symmetricDifference = function symmetricDifference(otherSet) {\n if (isES6Set(otherSet) && !isObservableSet(otherSet)) {\n return otherSet.symmetricDifference(this);\n } else {\n var dehancedSet = new Set(this);\n return dehancedSet.symmetricDifference(otherSet);\n }\n };\n _proto.isSubsetOf = function isSubsetOf(otherSet) {\n return new Set(this).isSubsetOf(otherSet);\n };\n _proto.isSupersetOf = function isSupersetOf(otherSet) {\n return new Set(this).isSupersetOf(otherSet);\n };\n _proto.isDisjointFrom = function isDisjointFrom(otherSet) {\n if (isES6Set(otherSet) && !isObservableSet(otherSet)) {\n return otherSet.isDisjointFrom(this);\n } else {\n var dehancedSet = new Set(this);\n return dehancedSet.isDisjointFrom(otherSet);\n }\n };\n _proto.replace = function replace(other) {\n var _this5 = this;\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n transaction(function () {\n if (Array.isArray(other)) {\n _this5.clear();\n other.forEach(function (value) {\n return _this5.add(value);\n });\n } else if (isES6Set(other)) {\n _this5.clear();\n other.forEach(function (value) {\n return _this5.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if (process.env.NODE_ENV !== \"production\" && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n return registerListener(this, listener);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n _proto[Symbol.iterator] = function () {\n return this.values();\n };\n return _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: Symbol.toStringTag,\n get: function get() {\n return \"Set\";\n }\n }]);\n}();\n// eslint-disable-next-line\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_,\n // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom(process.env.NODE_ENV !== \"production\" ? this.name_ + \".keys\" : \"ObservableObject.keys\");\n // Optimization: we use this frequently\n this.isPlainObject_ = isPlainObject(this.target_);\n if (process.env.NODE_ENV !== \"production\" && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n if (process.env.NODE_ENV !== \"production\") {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n var _proto = ObservableObjectAdministration.prototype;\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n }\n // intercept\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n if (!change) {\n return null;\n }\n newValue = change.newValue;\n }\n newValue = observable.prepareNewValue_(newValue);\n // notify spy & observers\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n if (notify) {\n notifyListeners(this, _change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n return true;\n };\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n return this.target_[key];\n }\n /**\n * @param {PropertyKey} key\n * @param {any} value\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n }\n // Trap for \"in\"\n ;\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + stringifyKey(key) + \"?\" : \"ObservableObject.key?\", false);\n this.pendingKeys_.set(key, entry);\n }\n return entry.get();\n }\n /**\n * @param {PropertyKey} key\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\n */;\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n if (annotation === false) {\n return;\n }\n assertAnnotable(this, annotation, key);\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n var source = this.target_;\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n if (outcome === 0 /* MakeResult.Cancel */) {\n return;\n }\n if (outcome === 1 /* MakeResult.Break */) {\n break;\n }\n }\n source = Object.getPrototypeOf(source);\n }\n recordAnnotationApplied(this, annotation, key);\n }\n /**\n * @param {PropertyKey} key\n * @param {PropertyDescriptor} descriptor\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n return outcome;\n }\n /**\n * @param {PropertyKey} key\n * @param {PropertyDescriptor} descriptor\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n try {\n startBatch();\n // Delete\n var deleteOutcome = this.delete_(key);\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n }\n // ADD interceptor\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n if (!change) {\n return null;\n }\n var newValue = change.newValue;\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n }\n // Define\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n // Notify\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n return true;\n }\n // If original descriptor becomes relevant, move this to annotation directly\n ;\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n try {\n startBatch();\n // Delete\n var deleteOutcome = this.delete_(key);\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n }\n // ADD interceptor\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n if (!change) {\n return null;\n }\n value = change.newValue;\n }\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n };\n // Define\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n var observable = new ObservableValue(value, enhancer, process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + key.toString() : \"ObservableObject.key\", false);\n this.values_.set(key, observable);\n // Notify (value possibly changed by ObservableValue)\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n return true;\n }\n // If original descriptor becomes relevant, move this to annotation directly\n ;\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n try {\n startBatch();\n // Delete\n var deleteOutcome = this.delete_(key);\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n }\n // ADD interceptor\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n if (!change) {\n return null;\n }\n }\n options.name || (options.name = process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + key.toString() : \"ObservableObject.key\");\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n };\n // Define\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n this.values_.set(key, new ComputedValue(options));\n // Notify\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n return true;\n }\n /**\n * @param {PropertyKey} key\n * @param {PropertyDescriptor} descriptor\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n }\n // Intercept\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n });\n // Cancelled\n if (!change) {\n return null;\n }\n }\n // Delete\n try {\n var _this$pendingKeys_;\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var observable = this.values_.get(key);\n // Value needed for spies/listeners\n var value = undefined;\n // Optimization: don't pull the value unless we will need it\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n }\n // delete prop (do first, may fail)\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n }\n // Allow re-annotating this field\n if (process.env.NODE_ENV !== \"production\") {\n delete this.appliedAnnotations_[key];\n }\n // Clear observable\n if (observable) {\n this.values_[\"delete\"](key);\n // for computed, value is undefined\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n }\n // Notify: autorun(() => obj[key]), see #1796\n propagateChanged(observable);\n }\n // Notify \"keys/entries/values\" observers\n this.keysAtom_.reportChanged();\n // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n (_this$pendingKeys_ = this.pendingKeys_) == null || (_this$pendingKeys_ = _this$pendingKeys_.get(key)) == null || _this$pendingKeys_.set(key in this.target_);\n // Notify spies/listeners\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(_change2);\n }\n if (notify) {\n notifyListeners(this, _change2);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n return true;\n }\n /**\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\n * for callback details\n */;\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if (process.env.NODE_ENV !== \"production\" && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n return registerListener(this, callback);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2;\n var notify = hasListeners(this);\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n }\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n (_this$pendingKeys_2 = this.pendingKeys_) == null || (_this$pendingKeys_2 = _this$pendingKeys_2.get(key)) == null || _this$pendingKeys_2.set(true);\n // Notify \"keys/entries/values\" observers\n this.keysAtom_.reportChanged();\n };\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n if (process.env.NODE_ENV !== \"production\" && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n if (hasProp(target, $mobx)) {\n if (process.env.NODE_ENV !== \"production\" && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n return target;\n }\n if (process.env.NODE_ENV !== \"production\" && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : process.env.NODE_ENV !== \"production\" ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : \"ObservableObject\";\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n if (process.env.NODE_ENV !== \"production\") {\n adm.appliedAnnotations_[key] = annotation;\n }\n // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null || delete _adm$target_$storedAn[key];\n}\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if (process.env.NODE_ENV !== \"production\" && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\n // Configurable, not sealed, not frozen\n // Possibly not needed, just a little better error then the one thrown by engine.\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\n if (__DEV__) {\n const configurable = getDescriptor(adm.target_, key)?.configurable\n const frozen = Object.isFrozen(adm.target_)\n const sealed = Object.isSealed(adm.target_)\n if (!configurable || frozen || sealed) {\n const fieldName = `${adm.name_}.${key.toString()}`\n const requestedAnnotationType = annotation.annotationType_\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\n if (frozen) {\n error += `\\nObject is frozen.`\n }\n if (sealed) {\n error += `\\nObject is sealed.`\n }\n if (!configurable) {\n error += `\\nproperty is not configurable.`\n // Mention only if caused by us to avoid confusion\n if (hasProp(adm.appliedAnnotations!, key)) {\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\n }\n }\n die(error)\n }\n }\n */\n // Not annotated\n if (process.env.NODE_ENV !== \"production\" && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\n// Bug in safari 9.* (or iOS 9 safari mobile). See #364\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\nvar safariPrototypeSetterInheritanceBug = /*#__PURE__*/function () {\n var v = false;\n var p = {};\n Object.defineProperty(p, \"0\", {\n set: function set() {\n v = true;\n }\n });\n /*#__PURE__*/Object.create(p)[\"0\"] = 1;\n return v === false;\n}();\n/**\n * This array buffer contains two lists of properties, so that all arrays\n * can recycle their property definitions, which significantly improves performance of creating\n * properties on the fly.\n */\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0;\n// Typescript workaround to make sure ObservableArray extends Array\nvar StubArray = function StubArray() {};\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\ninherit(StubArray, Array.prototype);\n// Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray) {\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n if (name === void 0) {\n name = process.env.NODE_ENV !== \"production\" ? \"ObservableArray@\" + getNextId() : \"ObservableArray\";\n }\n if (owned === void 0) {\n owned = false;\n }\n _this = _StubArray.call(this) || this;\n initObservable(function () {\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _this;\n addHiddenFinalProp(_this, $mobx, adm);\n if (initialValues && initialValues.length) {\n // @ts-ignore\n _this.spliceWithArray(0, 0, initialValues);\n }\n if (safariPrototypeSetterInheritanceBug) {\n // Seems that Safari won't use numeric prototype setter until any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_this, \"0\", ENTRY_0);\n }\n });\n return _this;\n }\n _inheritsLoose(LegacyObservableArray, _StubArray);\n var _proto = LegacyObservableArray.prototype;\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n return Array.prototype.concat.apply(this.slice(),\n //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n _proto[Symbol.iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n return _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: Symbol.toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n}(StubArray);\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n return thing[$mobx].atom_;\n }\n if (isObservableSet(thing)) {\n return thing.atom_;\n }\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n return observable;\n }\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n var _observable = thing[$mobx].values_.get(property);\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n return _observable;\n }\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n return named.name_;\n}\n/**\n * Helper function for initializing observable structures, it applies:\n * 1. allowStateChanges so we don't violate enforceActions.\n * 2. untracked so we don't accidentaly subscribe to anything observable accessed during init in case the observable is created inside derivation.\n * 3. batch to avoid state version updates\n */\nfunction initObservable(cb) {\n var derivation = untrackedStart();\n var allowStateChanges = allowStateChangesStart(true);\n startBatch();\n try {\n return cb();\n } finally {\n endBatch();\n allowStateChangesEnd(allowStateChanges);\n untrackedEnd(derivation);\n }\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n return eq(a, b, depth);\n}\n// Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n }\n // `null` or `undefined` only equal to itself (strict comparison).\n if (a == null || b == null) {\n return false;\n }\n // `NaN`s are equivalent, but non-reflexive.\n if (a !== a) {\n return b !== b;\n }\n // Exhaust primitive checks\n var type = typeof a;\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n }\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) {\n return false;\n }\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\":\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n }\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n break;\n }\n // Unwrap any wrapped objects.\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n }\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor,\n bCtor = b.constructor;\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n }\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) {\n return false;\n }\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (Object.keys(b).length !== length) {\n return false;\n }\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n}\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (\n // Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\n * (c) Michel Weststrate 2015 - 2020\n * MIT Licensed\n *\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\n * this is a good place to start:\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\n *\n * Source folders:\n * ===============\n *\n * - api/ Most of the public static methods exposed by the module can be found here.\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\n * - utils/ Utility stuff.\n *\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\nexport { $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, allowStateChanges as _allowStateChanges, runInAction as _allowStateChangesInsideComputed, allowStateReadsEnd as _allowStateReadsEnd, allowStateReadsStart as _allowStateReadsStart, autoAction as _autoAction, _endAction, getAdministration as _getAdministration, getGlobalState as _getGlobalState, interceptReads as _interceptReads, isComputingDerivation as _isComputingDerivation, resetGlobalState as _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, apiDefineProperty as defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isObservableValue as isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, apiOwnKeys as ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when };\n//# sourceMappingURL=mobx.esm.js.map\n","import { makeObservable } from \"mobx\";\nimport { useState } from \"react\";\nif (!useState) {\n throw new Error(\"mobx-react-lite requires React with Hooks support\");\n}\nif (!makeObservable) {\n throw new Error(\"mobx-react-lite@3 requires mobx at least version 6 to be available\");\n}\n//# sourceMappingURL=assertEnvironment.js.map","import { configure } from \"mobx\";\nexport function defaultNoopBatch(callback) {\n callback();\n}\nexport function observerBatching(reactionScheduler) {\n if (!reactionScheduler) {\n reactionScheduler = defaultNoopBatch;\n if (\"production\" !== process.env.NODE_ENV) {\n console.warn(\"[MobX] Failed to get unstable_batched updates from react-dom / react-native\");\n }\n }\n configure({ reactionScheduler: reactionScheduler });\n}\nexport var isObserverBatched = function () {\n if (\"production\" !== process.env.NODE_ENV) {\n console.warn(\"[MobX] Deprecated\");\n }\n return true;\n};\n//# sourceMappingURL=observerBatching.js.map","import { getDependencyTree } from \"mobx\";\nexport function printDebugValue(v) {\n return getDependencyTree(v);\n}\n//# sourceMappingURL=printDebugValue.js.map","var globalIsUsingStaticRendering = false;\nexport function enableStaticRendering(enable) {\n globalIsUsingStaticRendering = enable;\n}\nexport function isUsingStaticRendering() {\n return globalIsUsingStaticRendering;\n}\n//# sourceMappingURL=staticRendering.js.map","export var REGISTRY_FINALIZE_AFTER = 10000;\nexport var REGISTRY_SWEEP_INTERVAL = 10000;\nvar TimerBasedFinalizationRegistry = /** @class */ (function () {\n function TimerBasedFinalizationRegistry(finalize) {\n var _this = this;\n Object.defineProperty(this, \"finalize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: finalize\n });\n Object.defineProperty(this, \"registrations\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n Object.defineProperty(this, \"sweepTimeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // Bound so it can be used directly as setTimeout callback.\n Object.defineProperty(this, \"sweep\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (maxAge) {\n if (maxAge === void 0) { maxAge = REGISTRY_FINALIZE_AFTER; }\n // cancel timeout so we can force sweep anytime\n clearTimeout(_this.sweepTimeout);\n _this.sweepTimeout = undefined;\n var now = Date.now();\n _this.registrations.forEach(function (registration, token) {\n if (now - registration.registeredAt >= maxAge) {\n _this.finalize(registration.value);\n _this.registrations.delete(token);\n }\n });\n if (_this.registrations.size > 0) {\n _this.scheduleSweep();\n }\n }\n });\n // Bound so it can be exported directly as clearTimers test utility.\n Object.defineProperty(this, \"finalizeAllImmediately\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function () {\n _this.sweep(0);\n }\n });\n }\n // Token is actually required with this impl\n Object.defineProperty(TimerBasedFinalizationRegistry.prototype, \"register\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (target, value, token) {\n this.registrations.set(token, {\n value: value,\n registeredAt: Date.now()\n });\n this.scheduleSweep();\n }\n });\n Object.defineProperty(TimerBasedFinalizationRegistry.prototype, \"unregister\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (token) {\n this.registrations.delete(token);\n }\n });\n Object.defineProperty(TimerBasedFinalizationRegistry.prototype, \"scheduleSweep\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this.sweepTimeout === undefined) {\n this.sweepTimeout = setTimeout(this.sweep, REGISTRY_SWEEP_INTERVAL);\n }\n }\n });\n return TimerBasedFinalizationRegistry;\n}());\nexport { TimerBasedFinalizationRegistry };\nexport var UniversalFinalizationRegistry = typeof FinalizationRegistry !== \"undefined\"\n ? FinalizationRegistry\n : TimerBasedFinalizationRegistry;\n//# sourceMappingURL=UniversalFinalizationRegistry.js.map","import { UniversalFinalizationRegistry } from \"./UniversalFinalizationRegistry\";\nexport var observerFinalizationRegistry = new UniversalFinalizationRegistry(function (adm) {\n var _a;\n (_a = adm.reaction) === null || _a === void 0 ? void 0 : _a.dispose();\n adm.reaction = null;\n});\n//# sourceMappingURL=observerFinalizationRegistry.js.map","/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","import { Reaction } from \"mobx\";\nimport React from \"react\";\nimport { printDebugValue } from \"./utils/printDebugValue\";\nimport { isUsingStaticRendering } from \"./staticRendering\";\nimport { observerFinalizationRegistry } from \"./utils/observerFinalizationRegistry\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim\";\nfunction createReaction(adm) {\n adm.reaction = new Reaction(\"observer\".concat(adm.name), function () {\n var _a;\n adm.stateVersion = Symbol();\n // onStoreChange won't be available until the component \"mounts\".\n // If state changes in between initial render and mount,\n // `useSyncExternalStore` should handle that by checking the state version and issuing update.\n (_a = adm.onStoreChange) === null || _a === void 0 ? void 0 : _a.call(adm);\n });\n}\nexport function useObserver(render, baseComponentName) {\n if (baseComponentName === void 0) { baseComponentName = \"observed\"; }\n if (isUsingStaticRendering()) {\n return render();\n }\n var admRef = React.useRef(null);\n if (!admRef.current) {\n // First render\n var adm_1 = {\n reaction: null,\n onStoreChange: null,\n stateVersion: Symbol(),\n name: baseComponentName,\n subscribe: function (onStoreChange) {\n // Do NOT access admRef here!\n observerFinalizationRegistry.unregister(adm_1);\n adm_1.onStoreChange = onStoreChange;\n if (!adm_1.reaction) {\n // We've lost our reaction and therefore all subscriptions, occurs when:\n // 1. Timer based finalization registry disposed reaction before component mounted.\n // 2. React \"re-mounts\" same component without calling render in between (typically ).\n // We have to recreate reaction and schedule re-render to recreate subscriptions,\n // even if state did not change.\n createReaction(adm_1);\n // `onStoreChange` won't force update if subsequent `getSnapshot` returns same value.\n // So we make sure that is not the case\n adm_1.stateVersion = Symbol();\n }\n return function () {\n var _a;\n // Do NOT access admRef here!\n adm_1.onStoreChange = null;\n (_a = adm_1.reaction) === null || _a === void 0 ? void 0 : _a.dispose();\n adm_1.reaction = null;\n };\n },\n getSnapshot: function () {\n // Do NOT access admRef here!\n return adm_1.stateVersion;\n }\n };\n admRef.current = adm_1;\n }\n var adm = admRef.current;\n if (!adm.reaction) {\n // First render or reaction was disposed by registry before subscribe\n createReaction(adm);\n // StrictMode/ConcurrentMode/Suspense may mean that our component is\n // rendered and abandoned multiple times, so we need to track leaked\n // Reactions.\n observerFinalizationRegistry.register(admRef, adm, adm);\n }\n React.useDebugValue(adm.reaction, printDebugValue);\n useSyncExternalStore(\n // Both of these must be stable, otherwise it would keep resubscribing every render.\n adm.subscribe, adm.getSnapshot, adm.getSnapshot);\n // render the original component, but have the\n // reaction track the observables, so that rendering\n // can be invalidated (see above) once a dependency changes\n var renderResult;\n var exception;\n adm.reaction.track(function () {\n try {\n renderResult = render();\n }\n catch (e) {\n exception = e;\n }\n });\n if (exception) {\n throw exception; // re-throw any exceptions caught during rendering\n }\n return renderResult;\n}\n//# sourceMappingURL=useObserver.js.map","var _a, _b;\nimport { forwardRef, memo } from \"react\";\nimport { isUsingStaticRendering } from \"./staticRendering\";\nimport { useObserver } from \"./useObserver\";\nvar warnObserverOptionsDeprecated = true;\nvar hasSymbol = typeof Symbol === \"function\" && Symbol.for;\nvar isFunctionNameConfigurable = (_b = (_a = Object.getOwnPropertyDescriptor(function () { }, \"name\")) === null || _a === void 0 ? void 0 : _a.configurable) !== null && _b !== void 0 ? _b : false;\n// Using react-is had some issues (and operates on elements, not on types), see #608 / #609\nvar ReactForwardRefSymbol = hasSymbol\n ? Symbol.for(\"react.forward_ref\")\n : typeof forwardRef === \"function\" && forwardRef(function (props) { return null; })[\"$$typeof\"];\nvar ReactMemoSymbol = hasSymbol\n ? Symbol.for(\"react.memo\")\n : typeof memo === \"function\" && memo(function (props) { return null; })[\"$$typeof\"];\n// n.b. base case is not used for actual typings or exported in the typing files\nexport function observer(baseComponent, \n// TODO remove in next major\noptions) {\n var _a;\n if (process.env.NODE_ENV !== \"production\" && warnObserverOptionsDeprecated && options) {\n warnObserverOptionsDeprecated = false;\n console.warn(\"[mobx-react-lite] `observer(fn, { forwardRef: true })` is deprecated, use `observer(React.forwardRef(fn))`\");\n }\n if (ReactMemoSymbol && baseComponent[\"$$typeof\"] === ReactMemoSymbol) {\n throw new Error(\"[mobx-react-lite] You are trying to use `observer` on a function component wrapped in either another `observer` or `React.memo`. The observer already applies 'React.memo' for you.\");\n }\n // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307\n if (isUsingStaticRendering()) {\n return baseComponent;\n }\n var useForwardRef = (_a = options === null || options === void 0 ? void 0 : options.forwardRef) !== null && _a !== void 0 ? _a : false;\n var render = baseComponent;\n var baseComponentName = baseComponent.displayName || baseComponent.name;\n // If already wrapped with forwardRef, unwrap,\n // so we can patch render and apply memo\n if (ReactForwardRefSymbol && baseComponent[\"$$typeof\"] === ReactForwardRefSymbol) {\n useForwardRef = true;\n render = baseComponent[\"render\"];\n if (typeof render !== \"function\") {\n throw new Error(\"[mobx-react-lite] `render` property of ForwardRef was not a function\");\n }\n }\n var observerComponent = function (props, ref) {\n return useObserver(function () { return render(props, ref); }, baseComponentName);\n };\n observerComponent.displayName = baseComponent.displayName;\n if (isFunctionNameConfigurable) {\n Object.defineProperty(observerComponent, \"name\", {\n value: baseComponent.name,\n writable: true,\n configurable: true\n });\n }\n // Support legacy context: `contextTypes` must be applied before `memo`\n if (baseComponent.contextTypes) {\n ;\n observerComponent.contextTypes = baseComponent.contextTypes;\n }\n if (useForwardRef) {\n // `forwardRef` must be applied prior `memo`\n // `forwardRef(observer(cmp))` throws:\n // \"forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))\"\n observerComponent = forwardRef(observerComponent);\n }\n // memo; we are not interested in deep updates\n // in props; we assume that if deep objects are changed,\n // this is in observables, which would have been tracked anyway\n observerComponent = memo(observerComponent);\n copyStaticProperties(baseComponent, observerComponent);\n if (\"production\" !== process.env.NODE_ENV) {\n Object.defineProperty(observerComponent, \"contextTypes\", {\n set: function () {\n var _a, _b;\n throw new Error(\"[mobx-react-lite] `\".concat(this.displayName || ((_a = this.type) === null || _a === void 0 ? void 0 : _a.displayName) || ((_b = this.type) === null || _b === void 0 ? void 0 : _b.name) || \"Component\", \".contextTypes` must be set before applying `observer`.\"));\n }\n });\n }\n return observerComponent;\n}\n// based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js\nvar hoistBlackList = {\n $$typeof: true,\n render: true,\n compare: true,\n type: true,\n // Don't redefine `displayName`,\n // it's defined as getter-setter pair on `memo` (see #3192).\n displayName: true\n};\nfunction copyStaticProperties(base, target) {\n Object.keys(base).forEach(function (key) {\n if (!hoistBlackList[key]) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(base, key));\n }\n });\n}\n//# sourceMappingURL=observer.js.map","import { useObserver } from \"./useObserver\";\nfunction ObserverComponent(_a) {\n var children = _a.children, render = _a.render;\n var component = children || render;\n if (typeof component !== \"function\") {\n return null;\n }\n return useObserver(component);\n}\nif (\"production\" !== process.env.NODE_ENV) {\n ObserverComponent.propTypes = {\n children: ObserverPropsCheck,\n render: ObserverPropsCheck\n };\n}\nObserverComponent.displayName = \"Observer\";\nexport { ObserverComponent as Observer };\nfunction ObserverPropsCheck(props, key, componentName, location, propFullName) {\n var extraKey = key === \"children\" ? \"render\" : \"children\";\n var hasProp = typeof props[key] === \"function\";\n var hasExtraProp = typeof props[extraKey] === \"function\";\n if (hasProp && hasExtraProp) {\n return new Error(\"MobX Observer: Do not use children and render in the same time in`\" + componentName);\n }\n if (hasProp || hasExtraProp) {\n return null;\n }\n return new Error(\"Invalid prop `\" +\n propFullName +\n \"` of type `\" +\n typeof props[key] +\n \"` supplied to\" +\n \" `\" +\n componentName +\n \"`, expected `function`.\");\n}\n//# sourceMappingURL=ObserverComponent.js.map","import { observable } from \"mobx\";\nimport { useState } from \"react\";\nexport function useLocalObservable(initializer, annotations) {\n return useState(function () { return observable(initializer(), annotations, { autoBind: true }); })[0];\n}\n//# sourceMappingURL=useLocalObservable.js.map","import { useDeprecated } from \"./utils/utils\";\nimport { observable, runInAction } from \"mobx\";\nimport { useState } from \"react\";\nexport function useAsObservableSource(current) {\n if (\"production\" !== process.env.NODE_ENV)\n useDeprecated(\"[mobx-react-lite] 'useAsObservableSource' is deprecated, please store the values directly in an observable, for example by using 'useLocalObservable', and sync future updates using 'useEffect' when needed. See the README for examples.\");\n // We're deliberately not using idiomatic destructuring for the hook here.\n // Accessing the state value as an array element prevents TypeScript from generating unnecessary helpers in the resulting code.\n // For further details, please refer to mobxjs/mobx#3842.\n var res = useState(function () { return observable(current, {}, { deep: false }); })[0];\n runInAction(function () {\n Object.assign(res, current);\n });\n return res;\n}\n//# sourceMappingURL=useAsObservableSource.js.map","import { observable } from \"mobx\";\nimport { useState } from \"react\";\nimport { useDeprecated } from \"./utils/utils\";\nimport { useAsObservableSource } from \"./useAsObservableSource\";\nexport function useLocalStore(initializer, current) {\n if (\"production\" !== process.env.NODE_ENV) {\n useDeprecated(\"[mobx-react-lite] 'useLocalStore' is deprecated, use 'useLocalObservable' instead.\");\n }\n var source = current && useAsObservableSource(current);\n return useState(function () { return observable(initializer(source), undefined, { autoBind: true }); })[0];\n}\n//# sourceMappingURL=useLocalStore.js.map","var _a;\nimport \"./utils/assertEnvironment\";\nimport { unstable_batchedUpdates as batch } from \"./utils/reactBatchedUpdates\";\nimport { observerBatching } from \"./utils/observerBatching\";\nimport { useDeprecated } from \"./utils/utils\";\nimport { useObserver as useObserverOriginal } from \"./useObserver\";\nimport { enableStaticRendering } from \"./staticRendering\";\nimport { observerFinalizationRegistry } from \"./utils/observerFinalizationRegistry\";\nobserverBatching(batch);\nexport { isUsingStaticRendering, enableStaticRendering } from \"./staticRendering\";\nexport { observer } from \"./observer\";\nexport { Observer } from \"./ObserverComponent\";\nexport { useLocalObservable } from \"./useLocalObservable\";\nexport { useLocalStore } from \"./useLocalStore\";\nexport { useAsObservableSource } from \"./useAsObservableSource\";\nexport { observerFinalizationRegistry as _observerFinalizationRegistry };\nexport var clearTimers = (_a = observerFinalizationRegistry[\"finalizeAllImmediately\"]) !== null && _a !== void 0 ? _a : (function () { });\nexport function useObserver(fn, baseComponentName) {\n if (baseComponentName === void 0) { baseComponentName = \"observed\"; }\n if (\"production\" !== process.env.NODE_ENV) {\n useDeprecated(\"[mobx-react-lite] 'useObserver(fn)' is deprecated. Use `{fn}` instead, or wrap the entire component in `observer`.\");\n }\n return useObserverOriginal(fn, baseComponentName);\n}\nexport { isObserverBatched, observerBatching } from \"./utils/observerBatching\";\nexport function useStaticRendering(enable) {\n if (\"production\" !== process.env.NODE_ENV) {\n console.warn(\"[mobx-react-lite] 'useStaticRendering' is deprecated, use 'enableStaticRendering' instead\");\n }\n enableStaticRendering(enable);\n}\n//# sourceMappingURL=index.js.map","import { _getGlobalState, Reaction, _allowStateChanges, untracked, isObservableMap, isObservableObject, isObservableArray, observable } from 'mobx';\nimport React__default, { PureComponent, Component } from 'react';\nimport { isUsingStaticRendering, _observerFinalizationRegistry, observer as observer$1 } from 'mobx-react-lite';\nexport { Observer, enableStaticRendering, isUsingStaticRendering, observerBatching, useAsObservableSource, useLocalObservable, useLocalStore, useObserver, useStaticRendering } from 'mobx-react-lite';\n\nfunction shallowEqual(objA, objB) {\n //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n if (is(objA, objB)) {\n return true;\n }\n if (typeof objA !== \"object\" || objA === null || typeof objB !== \"object\" || objB === null) {\n return false;\n }\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n if (keysA.length !== keysB.length) {\n return false;\n }\n for (var i = 0; i < keysA.length; i++) {\n if (!Object.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n return true;\n}\nfunction is(x, y) {\n // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\n// based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js\nvar hoistBlackList = {\n $$typeof: 1,\n render: 1,\n compare: 1,\n type: 1,\n childContextTypes: 1,\n contextType: 1,\n contextTypes: 1,\n defaultProps: 1,\n getDefaultProps: 1,\n getDerivedStateFromError: 1,\n getDerivedStateFromProps: 1,\n mixins: 1,\n displayName: 1,\n propTypes: 1\n};\nfunction copyStaticProperties(base, target) {\n var protoProps = Object.getOwnPropertyNames(Object.getPrototypeOf(base));\n Object.getOwnPropertyNames(base).forEach(function (key) {\n if (!hoistBlackList[key] && protoProps.indexOf(key) === -1) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(base, key));\n }\n });\n}\n/**\n * Utilities for patching componentWillUnmount, to make sure @disposeOnUnmount works correctly icm with user defined hooks\n * and the handler provided by mobx-react\n */\nvar mobxMixins = /*#__PURE__*/Symbol(\"patchMixins\");\nvar mobxPatchedDefinition = /*#__PURE__*/Symbol(\"patchedDefinition\");\nfunction getMixins(target, methodName) {\n var mixins = target[mobxMixins] = target[mobxMixins] || {};\n var methodMixins = mixins[methodName] = mixins[methodName] || {};\n methodMixins.locks = methodMixins.locks || 0;\n methodMixins.methods = methodMixins.methods || [];\n return methodMixins;\n}\nfunction wrapper(realMethod, mixins) {\n var _this = this;\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n // locks are used to ensure that mixins are invoked only once per invocation, even on recursive calls\n mixins.locks++;\n try {\n var retVal;\n if (realMethod !== undefined && realMethod !== null) {\n retVal = realMethod.apply(this, args);\n }\n return retVal;\n } finally {\n mixins.locks--;\n if (mixins.locks === 0) {\n mixins.methods.forEach(function (mx) {\n mx.apply(_this, args);\n });\n }\n }\n}\nfunction wrapFunction(realMethod, mixins) {\n var fn = function fn() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n wrapper.call.apply(wrapper, [this, realMethod, mixins].concat(args));\n };\n return fn;\n}\nfunction patch(target, methodName, mixinMethod) {\n var mixins = getMixins(target, methodName);\n if (mixins.methods.indexOf(mixinMethod) < 0) {\n mixins.methods.push(mixinMethod);\n }\n var oldDefinition = Object.getOwnPropertyDescriptor(target, methodName);\n if (oldDefinition && oldDefinition[mobxPatchedDefinition]) {\n // already patched definition, do not repatch\n return;\n }\n var originalMethod = target[methodName];\n var newDefinition = createDefinition(target, methodName, oldDefinition ? oldDefinition.enumerable : undefined, mixins, originalMethod);\n Object.defineProperty(target, methodName, newDefinition);\n}\nfunction createDefinition(target, methodName, enumerable, mixins, originalMethod) {\n var _ref;\n var wrappedFunc = wrapFunction(originalMethod, mixins);\n return _ref = {}, _ref[mobxPatchedDefinition] = true, _ref.get = function get() {\n return wrappedFunc;\n }, _ref.set = function set(value) {\n if (this === target) {\n wrappedFunc = wrapFunction(value, mixins);\n } else {\n // when it is an instance of the prototype/a child prototype patch that particular case again separately\n // since we need to store separate values depending on wether it is the actual instance, the prototype, etc\n // e.g. the method for super might not be the same as the method for the prototype which might be not the same\n // as the method for the instance\n var newDefinition = createDefinition(this, methodName, enumerable, mixins, value);\n Object.defineProperty(this, methodName, newDefinition);\n }\n }, _ref.configurable = true, _ref.enumerable = enumerable, _ref;\n}\n\nvar administrationSymbol = /*#__PURE__*/Symbol(\"ObserverAdministration\");\nvar isMobXReactObserverSymbol = /*#__PURE__*/Symbol(\"isMobXReactObserver\");\nvar observablePropDescriptors;\nif (process.env.NODE_ENV !== \"production\") {\n observablePropDescriptors = {\n props: /*#__PURE__*/createObservablePropDescriptor(\"props\"),\n state: /*#__PURE__*/createObservablePropDescriptor(\"state\"),\n context: /*#__PURE__*/createObservablePropDescriptor(\"context\")\n };\n}\nfunction getAdministration(component) {\n var _component$administra;\n // We create administration lazily, because we can't patch constructor\n // and the exact moment of initialization partially depends on React internals.\n // At the time of writing this, the first thing invoked is one of the observable getter/setter (state/props/context).\n return (_component$administra = component[administrationSymbol]) != null ? _component$administra : component[administrationSymbol] = {\n reaction: null,\n mounted: false,\n reactionInvalidatedBeforeMount: false,\n forceUpdate: null,\n name: getDisplayName(component.constructor),\n state: undefined,\n props: undefined,\n context: undefined\n };\n}\nfunction makeClassComponentObserver(componentClass) {\n var prototype = componentClass.prototype;\n if (componentClass[isMobXReactObserverSymbol]) {\n var displayName = getDisplayName(componentClass);\n throw new Error(\"The provided component class (\" + displayName + \") has already been declared as an observer component.\");\n } else {\n componentClass[isMobXReactObserverSymbol] = true;\n }\n if (prototype.componentWillReact) {\n throw new Error(\"The componentWillReact life-cycle event is no longer supported\");\n }\n if (componentClass[\"__proto__\"] !== PureComponent) {\n if (!prototype.shouldComponentUpdate) {\n prototype.shouldComponentUpdate = observerSCU;\n } else if (prototype.shouldComponentUpdate !== observerSCU) {\n // n.b. unequal check, instead of existence check, as @observer might be on superclass as well\n throw new Error(\"It is not allowed to use shouldComponentUpdate in observer based components.\");\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n Object.defineProperties(prototype, observablePropDescriptors);\n }\n var originalRender = prototype.render;\n if (typeof originalRender !== \"function\") {\n var _displayName = getDisplayName(componentClass);\n throw new Error(\"[mobx-react] class component (\" + _displayName + \") is missing `render` method.\" + \"\\n`observer` requires `render` being a function defined on prototype.\" + \"\\n`render = () => {}` or `render = function() {}` is not supported.\");\n }\n prototype.render = function () {\n Object.defineProperty(this, \"render\", {\n // There is no safe way to replace render, therefore it's forbidden.\n configurable: false,\n writable: false,\n value: isUsingStaticRendering() ? originalRender : createReactiveRender.call(this, originalRender)\n });\n return this.render();\n };\n var originalComponentDidMount = prototype.componentDidMount;\n prototype.componentDidMount = function () {\n var _this = this;\n if (process.env.NODE_ENV !== \"production\" && this.componentDidMount !== Object.getPrototypeOf(this).componentDidMount) {\n var _displayName2 = getDisplayName(componentClass);\n throw new Error(\"[mobx-react] `observer(\" + _displayName2 + \").componentDidMount` must be defined on prototype.\" + \"\\n`componentDidMount = () => {}` or `componentDidMount = function() {}` is not supported.\");\n }\n // `componentDidMount` may not be called at all. React can abandon the instance after `render`.\n // That's why we use finalization registry to dispose reaction created during render.\n // Happens with `` see #3492\n //\n // `componentDidMount` can be called immediately after `componentWillUnmount` without calling `render` in between.\n // Happens with ``see #3395.\n //\n // If `componentDidMount` is called, it's guaranteed to run synchronously with render (similary to `useLayoutEffect`).\n // Therefore we don't have to worry about external (observable) state being updated before mount (no state version checking).\n //\n // Things may change: \"In the future, React will provide a feature that lets components preserve state between unmounts\"\n var admin = getAdministration(this);\n admin.mounted = true;\n // Component instance committed, prevent reaction disposal.\n _observerFinalizationRegistry.unregister(this);\n // We don't set forceUpdate before mount because it requires a reference to `this`,\n // therefore `this` could NOT be garbage collected before mount,\n // preventing reaction disposal by FinalizationRegistry and leading to memory leak.\n // As an alternative we could have `admin.instanceRef = new WeakRef(this)`, but lets avoid it if possible.\n admin.forceUpdate = function () {\n return _this.forceUpdate();\n };\n if (!admin.reaction || admin.reactionInvalidatedBeforeMount) {\n // Missing reaction:\n // 1. Instance was unmounted (reaction disposed) and immediately remounted without running render #3395.\n // 2. Reaction was disposed by finalization registry before mount. Shouldn't ever happen for class components:\n // `componentDidMount` runs synchronously after render, but our registry are deferred (can't run in between).\n // In any case we lost subscriptions to observables, so we have to create new reaction and re-render to resubscribe.\n // The reaction will be created lazily by following render.\n // Reaction invalidated before mount:\n // 1. A descendant's `componenDidMount` invalidated it's parent #3730\n admin.forceUpdate();\n }\n return originalComponentDidMount == null ? void 0 : originalComponentDidMount.apply(this, arguments);\n };\n // TODO@major Overly complicated \"patch\" is only needed to support the deprecated @disposeOnUnmount\n patch(prototype, \"componentWillUnmount\", function () {\n var _admin$reaction;\n if (isUsingStaticRendering()) {\n return;\n }\n var admin = getAdministration(this);\n (_admin$reaction = admin.reaction) == null ? void 0 : _admin$reaction.dispose();\n admin.reaction = null;\n admin.forceUpdate = null;\n admin.mounted = false;\n admin.reactionInvalidatedBeforeMount = false;\n });\n return componentClass;\n}\n// Generates a friendly name for debugging\nfunction getDisplayName(componentClass) {\n return componentClass.displayName || componentClass.name || \"\";\n}\nfunction createReactiveRender(originalRender) {\n var boundOriginalRender = originalRender.bind(this);\n var admin = getAdministration(this);\n function reactiveRender() {\n if (!admin.reaction) {\n // Create reaction lazily to support re-mounting #3395\n admin.reaction = createReaction(admin);\n if (!admin.mounted) {\n // React can abandon this instance and never call `componentDidMount`/`componentWillUnmount`,\n // we have to make sure reaction will be disposed.\n _observerFinalizationRegistry.register(this, admin, this);\n }\n }\n var error = undefined;\n var renderResult = undefined;\n admin.reaction.track(function () {\n try {\n // TODO@major\n // Optimization: replace with _allowStateChangesStart/End (not available in mobx@6.0.0)\n renderResult = _allowStateChanges(false, boundOriginalRender);\n } catch (e) {\n error = e;\n }\n });\n if (error) {\n throw error;\n }\n return renderResult;\n }\n return reactiveRender;\n}\nfunction createReaction(admin) {\n return new Reaction(admin.name + \".render()\", function () {\n if (!admin.mounted) {\n // This is neccessary to avoid react warning about calling forceUpdate on component that isn't mounted yet.\n // This happens when component is abandoned after render - our reaction is already created and reacts to changes.\n // `componenDidMount` runs synchronously after `render`, so unlike functional component, there is no delay during which the reaction could be invalidated.\n // However `componentDidMount` runs AFTER it's descendants' `componentDidMount`, which CAN invalidate the reaction, see #3730. Therefore remember and forceUpdate on mount.\n admin.reactionInvalidatedBeforeMount = true;\n return;\n }\n try {\n admin.forceUpdate == null ? void 0 : admin.forceUpdate();\n } catch (error) {\n var _admin$reaction2;\n (_admin$reaction2 = admin.reaction) == null ? void 0 : _admin$reaction2.dispose();\n admin.reaction = null;\n }\n });\n}\nfunction observerSCU(nextProps, nextState) {\n if (isUsingStaticRendering()) {\n console.warn(\"[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side.\");\n }\n // update on any state changes (as is the default)\n if (this.state !== nextState) {\n return true;\n }\n // update if props are shallowly not equal, inspired by PureRenderMixin\n // we could return just 'false' here, and avoid the `skipRender` checks etc\n // however, it is nicer if lifecycle events are triggered like usually,\n // so we return true here if props are shallowly modified.\n return !shallowEqual(this.props, nextProps);\n}\nfunction createObservablePropDescriptor(key) {\n return {\n configurable: true,\n enumerable: true,\n get: function get() {\n var admin = getAdministration(this);\n var derivation = _getGlobalState().trackingDerivation;\n if (derivation && derivation !== admin.reaction) {\n throw new Error(\"[mobx-react] Cannot read \\\"\" + admin.name + \".\" + key + \"\\\" in a reactive context, as it isn't observable.\\n Please use component lifecycle method to copy the value into a local observable first.\\n See https://github.com/mobxjs/mobx/blob/main/packages/mobx-react/README.md#note-on-using-props-and-state-in-derivations\");\n }\n return admin[key];\n },\n set: function set(value) {\n getAdministration(this)[key] = value;\n }\n };\n}\n\nfunction observer(component, context) {\n if (context && context.kind !== \"class\") {\n throw new Error(\"The @observer decorator can be used on classes only\");\n }\n if (component[\"isMobxInjector\"] === true) {\n console.warn(\"Mobx observer: You are trying to use `observer` on a component that already has `inject`. Please apply `observer` before applying `inject`\");\n }\n if (Object.prototype.isPrototypeOf.call(Component, component) || Object.prototype.isPrototypeOf.call(PureComponent, component)) {\n // Class component\n return makeClassComponentObserver(component);\n } else {\n // Function component\n return observer$1(component);\n }\n}\n\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\n\nvar _excluded = [\"children\"];\nvar MobXProviderContext = /*#__PURE__*/React__default.createContext({});\nfunction Provider(props) {\n var children = props.children,\n stores = _objectWithoutPropertiesLoose(props, _excluded);\n var parentValue = React__default.useContext(MobXProviderContext);\n var mutableProviderRef = React__default.useRef(_extends({}, parentValue, stores));\n var value = mutableProviderRef.current;\n if (process.env.NODE_ENV !== \"production\") {\n var newValue = _extends({}, value, stores); // spread in previous state for the context based stores\n if (!shallowEqual(value, newValue)) {\n throw new Error(\"MobX Provider: The set of provided stores has changed. See: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error.\");\n }\n }\n return React__default.createElement(MobXProviderContext.Provider, {\n value: value\n }, children);\n}\nProvider.displayName = \"MobXProvider\";\n\n/**\n * Store Injection\n */\nfunction createStoreInjector(grabStoresFn, component, injectNames, makeReactive) {\n // Support forward refs\n var Injector = React__default.forwardRef(function (props, ref) {\n var newProps = _extends({}, props);\n var context = React__default.useContext(MobXProviderContext);\n Object.assign(newProps, grabStoresFn(context || {}, newProps) || {});\n if (ref) {\n newProps.ref = ref;\n }\n return React__default.createElement(component, newProps);\n });\n if (makeReactive) Injector = observer(Injector);\n Injector[\"isMobxInjector\"] = true; // assigned late to suppress observer warning\n // Static fields from component should be visible on the generated Injector\n copyStaticProperties(component, Injector);\n Injector[\"wrappedComponent\"] = component;\n Injector.displayName = getInjectName(component, injectNames);\n return Injector;\n}\nfunction getInjectName(component, injectNames) {\n var displayName;\n var componentName = component.displayName || component.name || component.constructor && component.constructor.name || \"Component\";\n if (injectNames) displayName = \"inject-with-\" + injectNames + \"(\" + componentName + \")\";else displayName = \"inject(\" + componentName + \")\";\n return displayName;\n}\nfunction grabStoresByName(storeNames) {\n return function (baseStores, nextProps) {\n storeNames.forEach(function (storeName) {\n if (storeName in nextProps // prefer props over stores\n ) return;\n if (!(storeName in baseStores)) throw new Error(\"MobX injector: Store '\" + storeName + \"' is not available! Make sure it is provided by some Provider\");\n nextProps[storeName] = baseStores[storeName];\n });\n return nextProps;\n };\n}\n/**\n * higher order component that injects stores to a child.\n * takes either a varargs list of strings, which are stores read from the context,\n * or a function that manually maps the available stores from the context to props:\n * storesToProps(mobxStores, props, context) => newProps\n */\nfunction inject() {\n for (var _len = arguments.length, storeNames = new Array(_len), _key = 0; _key < _len; _key++) {\n storeNames[_key] = arguments[_key];\n }\n if (typeof arguments[0] === \"function\") {\n var grabStoresFn = arguments[0];\n return function (componentClass) {\n return createStoreInjector(grabStoresFn, componentClass, grabStoresFn.name, true);\n };\n } else {\n return function (componentClass) {\n return createStoreInjector(grabStoresByName(storeNames), componentClass, storeNames.join(\"-\"), false);\n };\n }\n}\n\nvar reactMajorVersion = /*#__PURE__*/Number.parseInt( /*#__PURE__*/React__default.version.split(\".\")[0]);\nvar warnedAboutDisposeOnUnmountDeprecated = false;\nvar protoStoreKey = /*#__PURE__*/Symbol(\"disposeOnUnmountProto\");\nvar instStoreKey = /*#__PURE__*/Symbol(\"disposeOnUnmountInst\");\nfunction runDisposersOnWillUnmount() {\n var _this = this;\n [].concat(this[protoStoreKey] || [], this[instStoreKey] || []).forEach(function (propKeyOrFunction) {\n var prop = typeof propKeyOrFunction === \"string\" ? _this[propKeyOrFunction] : propKeyOrFunction;\n if (prop !== undefined && prop !== null) {\n if (Array.isArray(prop)) prop.map(function (f) {\n return f();\n });else prop();\n }\n });\n}\n/**\n * @deprecated `disposeOnUnmount` is not compatible with React 18 and higher.\n */\nfunction disposeOnUnmount(target, propertyKeyOrFunction) {\n if (Array.isArray(propertyKeyOrFunction)) {\n return propertyKeyOrFunction.map(function (fn) {\n return disposeOnUnmount(target, fn);\n });\n }\n if (!warnedAboutDisposeOnUnmountDeprecated) {\n if (reactMajorVersion >= 18) {\n console.error(\"[mobx-react] disposeOnUnmount is not compatible with React 18 and higher. Don't use it.\");\n } else {\n console.warn(\"[mobx-react] disposeOnUnmount is deprecated. It won't work correctly with React 18 and higher.\");\n }\n warnedAboutDisposeOnUnmountDeprecated = true;\n }\n var c = Object.getPrototypeOf(target).constructor;\n var c2 = Object.getPrototypeOf(target.constructor);\n // Special case for react-hot-loader\n var c3 = Object.getPrototypeOf(Object.getPrototypeOf(target));\n if (!(c === React__default.Component || c === React__default.PureComponent || c2 === React__default.Component || c2 === React__default.PureComponent || c3 === React__default.Component || c3 === React__default.PureComponent)) {\n throw new Error(\"[mobx-react] disposeOnUnmount only supports direct subclasses of React.Component or React.PureComponent.\");\n }\n if (typeof propertyKeyOrFunction !== \"string\" && typeof propertyKeyOrFunction !== \"function\" && !Array.isArray(propertyKeyOrFunction)) {\n throw new Error(\"[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function.\");\n }\n // decorator's target is the prototype, so it doesn't have any instance properties like props\n var isDecorator = typeof propertyKeyOrFunction === \"string\";\n // add property key / function we want run (disposed) to the store\n var componentWasAlreadyModified = !!target[protoStoreKey] || !!target[instStoreKey];\n var store = isDecorator ?\n // decorators are added to the prototype store\n target[protoStoreKey] || (target[protoStoreKey] = []) :\n // functions are added to the instance store\n target[instStoreKey] || (target[instStoreKey] = []);\n store.push(propertyKeyOrFunction);\n // tweak the component class componentWillUnmount if not done already\n if (!componentWasAlreadyModified) {\n patch(target, \"componentWillUnmount\", runDisposersOnWillUnmount);\n }\n // return the disposer as is if invoked as a non decorator\n if (typeof propertyKeyOrFunction !== \"string\") {\n return propertyKeyOrFunction;\n }\n}\n\n// Copied from React.PropTypes\nfunction createChainableTypeChecker(validator) {\n function checkType(isRequired, props, propName, componentName, location, propFullName) {\n for (var _len = arguments.length, rest = new Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {\n rest[_key - 6] = arguments[_key];\n }\n return untracked(function () {\n componentName = componentName || \"<>\";\n propFullName = propFullName || propName;\n if (props[propName] == null) {\n if (isRequired) {\n var actual = props[propName] === null ? \"null\" : \"undefined\";\n return new Error(\"The \" + location + \" `\" + propFullName + \"` is marked as required \" + \"in `\" + componentName + \"`, but its value is `\" + actual + \"`.\");\n }\n return null;\n } else {\n // @ts-ignore rest arg is necessary for some React internals - fails tests otherwise\n return validator.apply(void 0, [props, propName, componentName, location, propFullName].concat(rest));\n }\n });\n }\n var chainedCheckType = checkType.bind(null, false);\n // Add isRequired to satisfy Requirable\n chainedCheckType.isRequired = checkType.bind(null, true);\n return chainedCheckType;\n}\n// Copied from React.PropTypes\nfunction isSymbol(propType, propValue) {\n // Native Symbol.\n if (propType === \"symbol\") {\n return true;\n }\n // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'\n if (propValue[\"@@toStringTag\"] === \"Symbol\") {\n return true;\n }\n // Fallback for non-spec compliant Symbols which are polyfilled.\n if (typeof Symbol === \"function\" && propValue instanceof Symbol) {\n return true;\n }\n return false;\n}\n// Copied from React.PropTypes\nfunction getPropType(propValue) {\n var propType = typeof propValue;\n if (Array.isArray(propValue)) {\n return \"array\";\n }\n if (propValue instanceof RegExp) {\n // Old webkits (at least until Android 4.0) return 'function' rather than\n // 'object' for typeof a RegExp. We'll normalize this here so that /bla/\n // passes PropTypes.object.\n return \"object\";\n }\n if (isSymbol(propType, propValue)) {\n return \"symbol\";\n }\n return propType;\n}\n// This handles more types than `getPropType`. Only used for error messages.\n// Copied from React.PropTypes\nfunction getPreciseType(propValue) {\n var propType = getPropType(propValue);\n if (propType === \"object\") {\n if (propValue instanceof Date) {\n return \"date\";\n } else if (propValue instanceof RegExp) {\n return \"regexp\";\n }\n }\n return propType;\n}\nfunction createObservableTypeCheckerCreator(allowNativeType, mobxType) {\n return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {\n return untracked(function () {\n if (allowNativeType) {\n if (getPropType(props[propName]) === mobxType.toLowerCase()) return null;\n }\n var mobxChecker;\n switch (mobxType) {\n case \"Array\":\n mobxChecker = isObservableArray;\n break;\n case \"Object\":\n mobxChecker = isObservableObject;\n break;\n case \"Map\":\n mobxChecker = isObservableMap;\n break;\n default:\n throw new Error(\"Unexpected mobxType: \" + mobxType);\n }\n var propValue = props[propName];\n if (!mobxChecker(propValue)) {\n var preciseType = getPreciseType(propValue);\n var nativeTypeExpectationMessage = allowNativeType ? \" or javascript `\" + mobxType.toLowerCase() + \"`\" : \"\";\n return new Error(\"Invalid prop `\" + propFullName + \"` of type `\" + preciseType + \"` supplied to\" + \" `\" + componentName + \"`, expected `mobx.Observable\" + mobxType + \"`\" + nativeTypeExpectationMessage + \".\");\n }\n return null;\n });\n });\n}\nfunction createObservableArrayOfTypeChecker(allowNativeType, typeChecker) {\n return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {\n for (var _len2 = arguments.length, rest = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {\n rest[_key2 - 5] = arguments[_key2];\n }\n return untracked(function () {\n if (typeof typeChecker !== \"function\") {\n return new Error(\"Property `\" + propFullName + \"` of component `\" + componentName + \"` has \" + \"invalid PropType notation.\");\n } else {\n var error = createObservableTypeCheckerCreator(allowNativeType, \"Array\")(props, propName, componentName, location, propFullName);\n if (error instanceof Error) return error;\n var propValue = props[propName];\n for (var i = 0; i < propValue.length; i++) {\n error = typeChecker.apply(void 0, [propValue, i, componentName, location, propFullName + \"[\" + i + \"]\"].concat(rest));\n if (error instanceof Error) return error;\n }\n return null;\n }\n });\n });\n}\nvar observableArray = /*#__PURE__*/createObservableTypeCheckerCreator(false, \"Array\");\nvar observableArrayOf = /*#__PURE__*/createObservableArrayOfTypeChecker.bind(null, false);\nvar observableMap = /*#__PURE__*/createObservableTypeCheckerCreator(false, \"Map\");\nvar observableObject = /*#__PURE__*/createObservableTypeCheckerCreator(false, \"Object\");\nvar arrayOrObservableArray = /*#__PURE__*/createObservableTypeCheckerCreator(true, \"Array\");\nvar arrayOrObservableArrayOf = /*#__PURE__*/createObservableArrayOfTypeChecker.bind(null, true);\nvar objectOrObservableObject = /*#__PURE__*/createObservableTypeCheckerCreator(true, \"Object\");\nvar PropTypes = {\n observableArray: observableArray,\n observableArrayOf: observableArrayOf,\n observableMap: observableMap,\n observableObject: observableObject,\n arrayOrObservableArray: arrayOrObservableArray,\n arrayOrObservableArrayOf: arrayOrObservableArrayOf,\n objectOrObservableObject: objectOrObservableObject\n};\n\nif (!Component) {\n throw new Error(\"mobx-react requires React to be available\");\n}\nif (!observable) {\n throw new Error(\"mobx-react requires mobx to be available\");\n}\n\nexport { MobXProviderContext, PropTypes, Provider, disposeOnUnmount, inject, observer };\n//# sourceMappingURL=mobxreact.esm.js.map\n","import { isComputedProp, isObservableProp, createAtom, action, computed, _allowStateChangesInsideComputed, reaction, runInAction, observable, values, entries, _getGlobalState, isObservableArray, isObservableObject, defineProperty as defineProperty$1, ObservableMap, _interceptReads, intercept, observe, _getAdministration, set, makeObservable, getAtom, when } from 'mobx';\n\nvar livelinessChecking = \"warn\";\n/**\n * Defines what MST should do when running into reads / writes to objects that have died.\n * By default it will print a warning.\n * Use the `\"error\"` option to easy debugging to see where the error was thrown and when the offending read / write took place\n *\n * @param mode `\"warn\"`, `\"error\"` or `\"ignore\"`\n */\nfunction setLivelinessChecking(mode) {\n livelinessChecking = mode;\n}\n/**\n * Returns the current liveliness checking mode.\n *\n * @returns `\"warn\"`, `\"error\"` or `\"ignore\"`\n */\nfunction getLivelinessChecking() {\n return livelinessChecking;\n}\n/**\n * @deprecated use setLivelinessChecking instead\n * @hidden\n *\n * Defines what MST should do when running into reads / writes to objects that have died.\n * By default it will print a warning.\n * Use the `\"error\"` option to easy debugging to see where the error was thrown and when the offending read / write took place\n *\n * @param mode `\"warn\"`, `\"error\"` or `\"ignore\"`\n */\nfunction setLivelynessChecking(mode) {\n setLivelinessChecking(mode);\n}\n\n/**\n * @hidden\n */\nvar Hook;\n(function (Hook) {\n Hook[\"afterCreate\"] = \"afterCreate\";\n Hook[\"afterAttach\"] = \"afterAttach\";\n Hook[\"afterCreationFinalization\"] = \"afterCreationFinalization\";\n Hook[\"beforeDetach\"] = \"beforeDetach\";\n Hook[\"beforeDestroy\"] = \"beforeDestroy\";\n})(Hook || (Hook = {}));\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nfunction __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nfunction __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\n\n/**\n * Returns the _actual_ type of the given tree node. (Or throws)\n *\n * @param object\n * @returns\n */\nfunction getType(object) {\n assertIsStateTreeNode(object, 1);\n return getStateTreeNode(object).type;\n}\n/**\n * Returns the _declared_ type of the given sub property of an object, array or map.\n * In the case of arrays and maps the property name is optional and will be ignored.\n *\n * Example:\n * ```ts\n * const Box = types.model({ x: 0, y: 0 })\n * const box = Box.create()\n *\n * console.log(getChildType(box, \"x\").name) // 'number'\n * ```\n *\n * @param object\n * @param propertyName\n * @returns\n */\nfunction getChildType(object, propertyName) {\n assertIsStateTreeNode(object, 1);\n return getStateTreeNode(object).getChildType(propertyName);\n}\n/**\n * Registers a function that will be invoked for each mutation that is applied to the provided model instance, or to any of its children.\n * See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details. onPatch events are emitted immediately and will not await the end of a transaction.\n * Patches can be used to deeply observe a model tree.\n *\n * @param target the model instance from which to receive patches\n * @param callback the callback that is invoked for each patch. The reversePatch is a patch that would actually undo the emitted patch\n * @returns function to remove the listener\n */\nfunction onPatch(target, callback) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsFunction(callback, 2);\n return getStateTreeNode(target).onPatch(callback);\n}\n/**\n * Registers a function that is invoked whenever a new snapshot for the given model instance is available.\n * The listener will only be fire at the end of the current MobX (trans)action.\n * See [snapshots](https://github.com/mobxjs/mobx-state-tree#snapshots) for more details.\n *\n * @param target\n * @param callback\n * @returns\n */\nfunction onSnapshot(target, callback) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsFunction(callback, 2);\n return getStateTreeNode(target).onSnapshot(callback);\n}\n/**\n * Applies a JSON-patch to the given model instance or bails out if the patch couldn't be applied\n * See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details.\n *\n * Can apply a single past, or an array of patches.\n *\n * @param target\n * @param patch\n * @returns\n */\nfunction applyPatch(target, patch) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertArg(patch, function (p) { return typeof p === \"object\"; }, \"object or array\", 2);\n getStateTreeNode(target).applyPatches(asArray(patch));\n}\n/**\n * Small abstraction around `onPatch` and `applyPatch`, attaches a patch listener to a tree and records all the patches.\n * Returns a recorder object with the following signature:\n *\n * Example:\n * ```ts\n * export interface IPatchRecorder {\n * // the recorded patches\n * patches: IJsonPatch[]\n * // the inverse of the recorded patches\n * inversePatches: IJsonPatch[]\n * // true if currently recording\n * recording: boolean\n * // stop recording patches\n * stop(): void\n * // resume recording patches\n * resume(): void\n * // apply all the recorded patches on the given target (the original subject if omitted)\n * replay(target?: IAnyStateTreeNode): void\n * // reverse apply the recorded patches on the given target (the original subject if omitted)\n * // stops the recorder if not already stopped\n * undo(): void\n * }\n * ```\n *\n * The optional filter function allows to skip recording certain patches.\n *\n * @param subject\n * @param filter\n * @returns\n */\nfunction recordPatches(subject, filter) {\n // check all arguments\n assertIsStateTreeNode(subject, 1);\n var data = {\n patches: [],\n inversePatches: []\n };\n // we will generate the immutable copy of patches on demand for public consumption\n var publicData = {};\n var disposer;\n var recorder = {\n get recording() {\n return !!disposer;\n },\n get patches() {\n if (!publicData.patches) {\n publicData.patches = data.patches.slice();\n }\n return publicData.patches;\n },\n get reversedInversePatches() {\n if (!publicData.reversedInversePatches) {\n publicData.reversedInversePatches = data.inversePatches.slice().reverse();\n }\n return publicData.reversedInversePatches;\n },\n get inversePatches() {\n if (!publicData.inversePatches) {\n publicData.inversePatches = data.inversePatches.slice();\n }\n return publicData.inversePatches;\n },\n stop: function () {\n if (disposer) {\n disposer();\n disposer = undefined;\n }\n },\n resume: function () {\n if (disposer)\n return;\n disposer = onPatch(subject, function (patch, inversePatch) {\n // skip patches that are asked to be filtered if there's a filter in place\n if (filter && !filter(patch, inversePatch, getRunningActionContext())) {\n return;\n }\n data.patches.push(patch);\n data.inversePatches.push(inversePatch);\n // mark immutable public patches as dirty\n publicData.patches = undefined;\n publicData.inversePatches = undefined;\n publicData.reversedInversePatches = undefined;\n });\n },\n replay: function (target) {\n applyPatch(target || subject, data.patches);\n },\n undo: function (target) {\n applyPatch(target || subject, data.inversePatches.slice().reverse());\n }\n };\n recorder.resume();\n return recorder;\n}\n/**\n * The inverse of `unprotect`.\n *\n * @param target\n */\nfunction protect(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (!node.isRoot)\n throw fail(\"`protect` can only be invoked on root nodes\");\n node.isProtectionEnabled = true;\n}\n/**\n * By default it is not allowed to directly modify a model. Models can only be modified through actions.\n * However, in some cases you don't care about the advantages (like replayability, traceability, etc) this yields.\n * For example because you are building a PoC or don't have any middleware attached to your tree.\n *\n * In that case you can disable this protection by calling `unprotect` on the root of your tree.\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * done: false\n * }).actions(self => ({\n * toggle() {\n * self.done = !self.done\n * }\n * }))\n *\n * const todo = Todo.create()\n * todo.done = true // throws!\n * todo.toggle() // OK\n * unprotect(todo)\n * todo.done = false // OK\n * ```\n */\nfunction unprotect(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (!node.isRoot)\n throw fail(\"`unprotect` can only be invoked on root nodes\");\n node.isProtectionEnabled = false;\n}\n/**\n * Returns true if the object is in protected mode, @see protect\n */\nfunction isProtected(target) {\n return getStateTreeNode(target).isProtected;\n}\n/**\n * Applies a snapshot to a given model instances. Patch and snapshot listeners will be invoked as usual.\n *\n * @param target\n * @param snapshot\n * @returns\n */\nfunction applySnapshot(target, snapshot) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).applySnapshot(snapshot);\n}\n/**\n * Calculates a snapshot from the given model instance. The snapshot will always reflect the latest state but use\n * structural sharing where possible. Doesn't require MobX transactions to be completed.\n *\n * @param target\n * @param applyPostProcess If true (the default) then postProcessSnapshot gets applied.\n * @returns\n */\nfunction getSnapshot(target, applyPostProcess) {\n if (applyPostProcess === void 0) { applyPostProcess = true; }\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (applyPostProcess)\n return node.snapshot;\n return freeze(node.type.getSnapshot(node, false));\n}\n/**\n * Given a model instance, returns `true` if the object has a parent, that is, is part of another object, map or array.\n *\n * @param target\n * @param depth How far should we look upward? 1 by default.\n * @returns\n */\nfunction hasParent(target, depth) {\n if (depth === void 0) { depth = 1; }\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsNumber(depth, 2, 0);\n var parent = getStateTreeNode(target).parent;\n while (parent) {\n if (--depth === 0)\n return true;\n parent = parent.parent;\n }\n return false;\n}\n/**\n * Returns the immediate parent of this object, or throws.\n *\n * Note that the immediate parent can be either an object, map or array, and\n * doesn't necessarily refer to the parent model.\n *\n * Please note that in child nodes access to the root is only possible\n * once the `afterAttach` hook has fired.\n *\n * @param target\n * @param depth How far should we look upward? 1 by default.\n * @returns\n */\nfunction getParent(target, depth) {\n if (depth === void 0) { depth = 1; }\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsNumber(depth, 2, 0);\n var d = depth;\n var parent = getStateTreeNode(target).parent;\n while (parent) {\n if (--d === 0)\n return parent.storedValue;\n parent = parent.parent;\n }\n throw fail(\"Failed to find the parent of \" + getStateTreeNode(target) + \" at depth \" + depth);\n}\n/**\n * Given a model instance, returns `true` if the object has a parent of given type, that is, is part of another object, map or array\n *\n * @param target\n * @param type\n * @returns\n */\nfunction hasParentOfType(target, type) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsType(type, 2);\n var parent = getStateTreeNode(target).parent;\n while (parent) {\n if (type.is(parent.storedValue))\n return true;\n parent = parent.parent;\n }\n return false;\n}\n/**\n * Returns the target's parent of a given type, or throws.\n *\n * @param target\n * @param type\n * @returns\n */\nfunction getParentOfType(target, type) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsType(type, 2);\n var parent = getStateTreeNode(target).parent;\n while (parent) {\n if (type.is(parent.storedValue))\n return parent.storedValue;\n parent = parent.parent;\n }\n throw fail(\"Failed to find the parent of \" + getStateTreeNode(target) + \" of a given type\");\n}\n/**\n * Given an object in a model tree, returns the root object of that tree.\n *\n * Please note that in child nodes access to the root is only possible\n * once the `afterAttach` hook has fired.\n *\n * @param target\n * @returns\n */\nfunction getRoot(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).root.storedValue;\n}\n/**\n * Returns the path of the given object in the model tree\n *\n * @param target\n * @returns\n */\nfunction getPath(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).path;\n}\n/**\n * Returns the path of the given object as unescaped string array.\n *\n * @param target\n * @returns\n */\nfunction getPathParts(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return splitJsonPath(getStateTreeNode(target).path);\n}\n/**\n * Returns true if the given object is the root of a model tree.\n *\n * @param target\n * @returns\n */\nfunction isRoot(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).isRoot;\n}\n/**\n * Resolves a path relatively to a given object.\n * Returns undefined if no value can be found.\n *\n * @param target\n * @param path escaped json path\n * @returns\n */\nfunction resolvePath(target, path) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsString(path, 2);\n var node = resolveNodeByPath(getStateTreeNode(target), path);\n return node ? node.value : undefined;\n}\n/**\n * Resolves a model instance given a root target, the type and the identifier you are searching for.\n * Returns undefined if no value can be found.\n *\n * @param type\n * @param target\n * @param identifier\n * @returns\n */\nfunction resolveIdentifier(type, target, identifier) {\n // check all arguments\n assertIsType(type, 1);\n assertIsStateTreeNode(target, 2);\n assertIsValidIdentifier(identifier, 3);\n var node = getStateTreeNode(target).root.identifierCache.resolve(type, normalizeIdentifier(identifier));\n return node === null || node === void 0 ? void 0 : node.value;\n}\n/**\n * Returns the identifier of the target node.\n * This is the *string normalized* identifier, which might not match the type of the identifier attribute\n *\n * @param target\n * @returns\n */\nfunction getIdentifier(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).identifier;\n}\n/**\n * Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns such reference if the check passes,\n * else it returns undefined.\n *\n * @param getter Function to access the reference.\n * @param checkIfAlive true to also make sure the referenced node is alive (default), false to skip this check.\n * @returns\n */\nfunction tryReference(getter, checkIfAlive) {\n if (checkIfAlive === void 0) { checkIfAlive = true; }\n try {\n var node = getter();\n if (node === undefined || node === null) {\n return undefined;\n }\n else if (isStateTreeNode(node)) {\n if (!checkIfAlive) {\n return node;\n }\n else {\n return isAlive(node) ? node : undefined;\n }\n }\n else {\n throw fail(\"The reference to be checked is not one of node, null or undefined\");\n }\n }\n catch (e) {\n if (e instanceof InvalidReferenceError) {\n return undefined;\n }\n throw e;\n }\n}\n/**\n * Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns if the check passes or not.\n *\n * @param getter Function to access the reference.\n * @param checkIfAlive true to also make sure the referenced node is alive (default), false to skip this check.\n * @returns\n */\nfunction isValidReference(getter, checkIfAlive) {\n if (checkIfAlive === void 0) { checkIfAlive = true; }\n try {\n var node = getter();\n if (node === undefined || node === null) {\n return false;\n }\n else if (isStateTreeNode(node)) {\n return checkIfAlive ? isAlive(node) : true;\n }\n else {\n throw fail(\"The reference to be checked is not one of node, null or undefined\");\n }\n }\n catch (e) {\n if (e instanceof InvalidReferenceError) {\n return false;\n }\n throw e;\n }\n}\n/**\n * Try to resolve a given path relative to a given node.\n *\n * @param target\n * @param path\n * @returns\n */\nfunction tryResolve(target, path) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsString(path, 2);\n var node = resolveNodeByPath(getStateTreeNode(target), path, false);\n if (node === undefined)\n return undefined;\n try {\n return node.value;\n }\n catch (e) {\n // For what ever reason not resolvable (e.g. totally not existing path, or value that cannot be fetched)\n // see test / issue: 'try resolve doesn't work #686'\n return undefined;\n }\n}\n/**\n * Given two state tree nodes that are part of the same tree,\n * returns the shortest jsonpath needed to navigate from the one to the other\n *\n * @param base\n * @param target\n * @returns\n */\nfunction getRelativePath(base, target) {\n // check all arguments\n assertIsStateTreeNode(base, 1);\n assertIsStateTreeNode(target, 2);\n return getRelativePathBetweenNodes(getStateTreeNode(base), getStateTreeNode(target));\n}\n/**\n * Returns a deep copy of the given state tree node as new tree.\n * Shorthand for `snapshot(x) = getType(x).create(getSnapshot(x))`\n *\n * _Tip: clone will create a literal copy, including the same identifiers. To modify identifiers etc. during cloning, don't use clone but take a snapshot of the tree, modify it, and create new instance_\n *\n * @param source\n * @param keepEnvironment indicates whether the clone should inherit the same environment (`true`, the default), or not have an environment (`false`). If an object is passed in as second argument, that will act as the environment for the cloned tree.\n * @returns\n */\nfunction clone(source, keepEnvironment) {\n if (keepEnvironment === void 0) { keepEnvironment = true; }\n // check all arguments\n assertIsStateTreeNode(source, 1);\n var node = getStateTreeNode(source);\n return node.type.create(node.snapshot, keepEnvironment === true\n ? node.root.environment\n : keepEnvironment === false\n ? undefined\n : keepEnvironment); // it's an object or something else\n}\n/**\n * Removes a model element from the state tree, and let it live on as a new state tree\n */\nfunction detach(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n getStateTreeNode(target).detach();\n return target;\n}\n/**\n * Removes a model element from the state tree, and mark it as end-of-life; the element should not be used anymore\n */\nfunction destroy(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (node.isRoot)\n node.die();\n else\n node.parent.removeChild(node.subpath);\n}\n/**\n * Returns true if the given state tree node is not killed yet.\n * This means that the node is still a part of a tree, and that `destroy`\n * has not been called. If a node is not alive anymore, the only thing one can do with it\n * is requesting it's last path and snapshot\n *\n * @param target\n * @returns\n */\nfunction isAlive(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).observableIsAlive;\n}\n/**\n * Use this utility to register a function that should be called whenever the\n * targeted state tree node is destroyed. This is a useful alternative to managing\n * cleanup methods yourself using the `beforeDestroy` hook.\n *\n * This methods returns the same disposer that was passed as argument.\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * title: types.string\n * }).actions(self => ({\n * afterCreate() {\n * const autoSaveDisposer = reaction(\n * () => getSnapshot(self),\n * snapshot => sendSnapshotToServerSomehow(snapshot)\n * )\n * // stop sending updates to server if this\n * // instance is destroyed\n * addDisposer(self, autoSaveDisposer)\n * }\n * }))\n * ```\n *\n * @param target\n * @param disposer\n * @returns The same disposer that was passed as argument\n */\nfunction addDisposer(target, disposer) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsFunction(disposer, 2);\n var node = getStateTreeNode(target);\n node.addDisposer(disposer);\n return disposer;\n}\n/**\n * Returns the environment of the current state tree. For more info on environments,\n * see [Dependency injection](https://github.com/mobxjs/mobx-state-tree#dependency-injection)\n *\n * Please note that in child nodes access to the root is only possible\n * once the `afterAttach` hook has fired\n *\n * Returns an empty environment if the tree wasn't initialized with an environment\n *\n * @param target\n * @returns\n */\nfunction getEnv(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n var env = node.root.environment;\n if (!env)\n return EMPTY_OBJECT;\n return env;\n}\n/**\n * Performs a depth first walk through a tree.\n */\nfunction walk(target, processor) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsFunction(processor, 2);\n var node = getStateTreeNode(target);\n // tslint:disable-next-line:no_unused-variable\n node.getChildren().forEach(function (child) {\n if (isStateTreeNode(child.storedValue))\n walk(child.storedValue, processor);\n });\n processor(node.storedValue);\n}\n/**\n * Returns a reflection of the model type properties and name for either a model type or model node.\n *\n * @param typeOrNode\n * @returns\n */\nfunction getPropertyMembers(typeOrNode) {\n var type;\n if (isStateTreeNode(typeOrNode)) {\n type = getType(typeOrNode);\n }\n else {\n type = typeOrNode;\n }\n assertArg(type, function (t) { return isModelType(t); }, \"model type or model instance\", 1);\n return {\n name: type.name,\n properties: __assign({}, type.properties)\n };\n}\n/**\n * Returns a reflection of the model node, including name, properties, views, volatile state,\n * and actions. `flowActions` is also provided as a separate array of names for any action that\n * came from a flow generator as well.\n *\n * In the case where a model has two actions: `doSomething` and `doSomethingWithFlow`, where\n * `doSomethingWithFlow` is a flow generator, the `actions` array will contain both actions,\n * i.e. [\"doSomething\", \"doSomethingWithFlow\"], and the `flowActions` array will contain only\n * the flow action, i.e. [\"doSomethingWithFlow\"].\n *\n * @param target\n * @returns\n */\nfunction getMembers(target) {\n var type = getStateTreeNode(target).type;\n var reflected = __assign(__assign({}, getPropertyMembers(type)), { actions: [], volatile: [], views: [], flowActions: [] });\n var props = Object.getOwnPropertyNames(target);\n props.forEach(function (key) {\n if (key in reflected.properties)\n return;\n var descriptor = Object.getOwnPropertyDescriptor(target, key);\n if (descriptor.get) {\n if (isComputedProp(target, key))\n reflected.views.push(key);\n else\n reflected.volatile.push(key);\n return;\n }\n if (descriptor.value._isFlowAction === true) {\n reflected.flowActions.push(key);\n }\n if (descriptor.value._isMSTAction === true) {\n reflected.actions.push(key);\n }\n else if (isObservableProp(target, key)) {\n reflected.volatile.push(key);\n }\n else {\n reflected.views.push(key);\n }\n });\n return reflected;\n}\n/**\n * Casts a node snapshot or instance type to an instance type so it can be assigned to a type instance.\n * Note that this is just a cast for the type system, this is, it won't actually convert a snapshot to an instance,\n * but just fool typescript into thinking so.\n * Either way, casting when outside an assignation operation won't compile.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * }).actions(self => ({\n * someAction() {\n * // this will allow the compiler to assign a snapshot to the property\n * self.innerModel = cast({ a: 5 })\n * }\n * }))\n * ```\n *\n * @param snapshotOrInstance Snapshot or instance\n * @returns The same object cast as an instance\n */\nfunction cast(snapshotOrInstance) {\n return snapshotOrInstance;\n}\n/**\n * Casts a node instance type to a snapshot type so it can be assigned to a type snapshot (e.g. to be used inside a create call).\n * Note that this is just a cast for the type system, this is, it won't actually convert an instance to a snapshot,\n * but just fool typescript into thinking so.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * })\n *\n * const a = ModelA.create({ n: 5 });\n * // this will allow the compiler to use a model as if it were a snapshot\n * const b = ModelB.create({ innerModel: castToSnapshot(a)})\n * ```\n *\n * @param snapshotOrInstance Snapshot or instance\n * @returns The same object cast as an input (creation) snapshot\n */\nfunction castToSnapshot(snapshotOrInstance) {\n return snapshotOrInstance;\n}\n/**\n * Casts a node instance type to a reference snapshot type so it can be assigned to a reference snapshot (e.g. to be used inside a create call).\n * Note that this is just a cast for the type system, this is, it won't actually convert an instance to a reference snapshot,\n * but just fool typescript into thinking so.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * id: types.identifier,\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * refA: types.reference(ModelA)\n * })\n *\n * const a = ModelA.create({ id: 'someId', n: 5 });\n * // this will allow the compiler to use a model as if it were a reference snapshot\n * const b = ModelB.create({ refA: castToReferenceSnapshot(a)})\n * ```\n *\n * @param instance Instance\n * @returns The same object cast as a reference snapshot (string or number)\n */\nfunction castToReferenceSnapshot(instance) {\n return instance;\n}\n/**\n * Returns the unique node id (not to be confused with the instance identifier) for a\n * given instance.\n * This id is a number that is unique for each instance.\n *\n * @export\n * @param target\n * @returns\n */\nfunction getNodeId(target) {\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).nodeId;\n}\n\n/**\n * @internal\n * @hidden\n */\nvar BaseNode = /** @class */ (function () {\n function BaseNode(type, parent, subpath, environment) {\n Object.defineProperty(this, \"type\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: type\n });\n Object.defineProperty(this, \"environment\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: environment\n });\n Object.defineProperty(this, \"_escapedSubpath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_subpath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_subpathUponDeath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pathUponDeath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"storedValue\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n }); // usually the same type as the value, but not always (such as with references)\n Object.defineProperty(this, \"aliveAtom\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_state\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: NodeLifeCycle.INITIALIZING\n });\n Object.defineProperty(this, \"_hookSubscribers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_parent\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"pathAtom\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.environment = environment;\n this.baseSetParent(parent, subpath);\n }\n Object.defineProperty(BaseNode.prototype, \"subpath\", {\n get: function () {\n return this._subpath;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"subpathUponDeath\", {\n get: function () {\n return this._subpathUponDeath;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"pathUponDeath\", {\n get: function () {\n return this._pathUponDeath;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"value\", {\n get: function () {\n return this.type.getValue(this);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"state\", {\n get: function () {\n return this._state;\n },\n set: function (val) {\n var wasAlive = this.isAlive;\n this._state = val;\n var isAlive = this.isAlive;\n if (this.aliveAtom && wasAlive !== isAlive) {\n this.aliveAtom.reportChanged();\n }\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"fireInternalHook\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (name) {\n if (this._hookSubscribers) {\n this._hookSubscribers.emit(name, this, name);\n }\n }\n });\n Object.defineProperty(BaseNode.prototype, \"registerHook\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (hook, hookHandler) {\n if (!this._hookSubscribers) {\n this._hookSubscribers = new EventHandlers();\n }\n return this._hookSubscribers.register(hook, hookHandler);\n }\n });\n Object.defineProperty(BaseNode.prototype, \"parent\", {\n get: function () {\n return this._parent;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"getReconciliationType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.type;\n }\n });\n Object.defineProperty(BaseNode.prototype, \"baseSetParent\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath) {\n this._parent = parent;\n this._subpath = subpath;\n this._escapedSubpath = undefined; // regenerate when needed\n if (this.pathAtom) {\n this.pathAtom.reportChanged();\n }\n }\n });\n Object.defineProperty(BaseNode.prototype, \"path\", {\n /*\n * Returns (escaped) path representation as string\n */\n get: function () {\n return this.getEscapedPath(true);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"getEscapedPath\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (reportObserved) {\n if (reportObserved) {\n if (!this.pathAtom) {\n this.pathAtom = createAtom(\"path\");\n }\n this.pathAtom.reportObserved();\n }\n if (!this.parent)\n return \"\";\n // regenerate escaped subpath if needed\n if (this._escapedSubpath === undefined) {\n this._escapedSubpath = !this._subpath ? \"\" : escapeJsonPath(this._subpath);\n }\n return this.parent.getEscapedPath(reportObserved) + \"/\" + this._escapedSubpath;\n }\n });\n Object.defineProperty(BaseNode.prototype, \"isRoot\", {\n get: function () {\n return this.parent === null;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"isAlive\", {\n get: function () {\n return this.state !== NodeLifeCycle.DEAD;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"isDetaching\", {\n get: function () {\n return this.state === NodeLifeCycle.DETACHING;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"observableIsAlive\", {\n get: function () {\n if (!this.aliveAtom) {\n this.aliveAtom = createAtom(\"alive\");\n }\n this.aliveAtom.reportObserved();\n return this.isAlive;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseNode.prototype, \"baseFinalizeCreation\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (whenFinalized) {\n if (devMode()) {\n if (!this.isAlive) {\n // istanbul ignore next\n throw fail(\"assertion failed: cannot finalize the creation of a node that is already dead\");\n }\n }\n // goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already\n if (this.state === NodeLifeCycle.CREATED) {\n if (this.parent) {\n if (this.parent.state !== NodeLifeCycle.FINALIZED) {\n // parent not ready yet, postpone\n return;\n }\n this.fireHook(Hook.afterAttach);\n }\n this.state = NodeLifeCycle.FINALIZED;\n if (whenFinalized) {\n whenFinalized();\n }\n }\n }\n });\n Object.defineProperty(BaseNode.prototype, \"baseFinalizeDeath\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this._hookSubscribers) {\n this._hookSubscribers.clearAll();\n }\n this._subpathUponDeath = this._subpath;\n this._pathUponDeath = this.getEscapedPath(false);\n this.baseSetParent(null, \"\");\n this.state = NodeLifeCycle.DEAD;\n }\n });\n Object.defineProperty(BaseNode.prototype, \"baseAboutToDie\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.fireHook(Hook.beforeDestroy);\n }\n });\n return BaseNode;\n}());\n\n/**\n * @internal\n * @hidden\n */\nvar ScalarNode = /** @class */ (function (_super) {\n __extends(ScalarNode, _super);\n function ScalarNode(simpleType, parent, subpath, environment, initialSnapshot) {\n var _this = _super.call(this, simpleType, parent, subpath, environment) || this;\n try {\n _this.storedValue = simpleType.createNewInstance(initialSnapshot);\n }\n catch (e) {\n // short-cut to die the instance, to avoid the snapshot computed starting to throw...\n _this.state = NodeLifeCycle.DEAD;\n throw e;\n }\n _this.state = NodeLifeCycle.CREATED;\n // for scalar nodes there's no point in firing this event since it would fire on the constructor, before\n // anybody can actually register for/listen to it\n // this.fireHook(Hook.AfterCreate)\n _this.finalizeCreation();\n return _this;\n }\n Object.defineProperty(ScalarNode.prototype, \"root\", {\n get: function () {\n // future optimization: store root ref in the node and maintain it\n if (!this.parent)\n throw fail(\"This scalar node is not part of a tree\");\n return this.parent.root;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(ScalarNode.prototype, \"setParent\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (newParent, subpath) {\n var parentChanged = this.parent !== newParent;\n var subpathChanged = this.subpath !== subpath;\n if (!parentChanged && !subpathChanged) {\n return;\n }\n if (devMode()) {\n if (!subpath) {\n // istanbul ignore next\n throw fail(\"assertion failed: subpath expected\");\n }\n if (!newParent) {\n // istanbul ignore next\n throw fail(\"assertion failed: parent expected\");\n }\n if (parentChanged) {\n // istanbul ignore next\n throw fail(\"assertion failed: scalar nodes cannot change their parent\");\n }\n }\n this.environment = undefined; // use parent's\n this.baseSetParent(this.parent, subpath);\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"snapshot\", {\n get: function () {\n return freeze(this.getSnapshot());\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(ScalarNode.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.type.getSnapshot(this);\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"toString\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var path = (this.isAlive ? this.path : this.pathUponDeath) || \"\";\n return this.type.name + \"@\" + path + (this.isAlive ? \"\" : \" [dead]\");\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"die\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (!this.isAlive || this.state === NodeLifeCycle.DETACHING)\n return;\n this.aboutToDie();\n this.finalizeDeath();\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"finalizeCreation\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.baseFinalizeCreation();\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"aboutToDie\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.baseAboutToDie();\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"finalizeDeath\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.baseFinalizeDeath();\n }\n });\n Object.defineProperty(ScalarNode.prototype, \"fireHook\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (name) {\n this.fireInternalHook(name);\n }\n });\n return ScalarNode;\n}(BaseNode));\nScalarNode.prototype.die = action(ScalarNode.prototype.die);\n\nvar nextNodeId = 1;\nvar snapshotReactionOptions = {\n onError: function (e) {\n throw e;\n }\n};\n/**\n * @internal\n * @hidden\n */\nvar ObjectNode = /** @class */ (function (_super) {\n __extends(ObjectNode, _super);\n function ObjectNode(complexType, parent, subpath, environment, initialValue) {\n var _this = _super.call(this, complexType, parent, subpath, environment) || this;\n Object.defineProperty(_this, \"nodeId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ++nextNodeId\n });\n Object.defineProperty(_this, \"identifierAttribute\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"identifier\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n }); // Identifier is always normalized to string, even if the identifier property isn't\n Object.defineProperty(_this, \"unnormalizedIdentifier\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"identifierCache\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"isProtectionEnabled\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(_this, \"middlewares\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"hasSnapshotPostProcessor\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(_this, \"_applyPatches\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_applySnapshot\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_autoUnbox\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n }); // unboxing is disabled when reading child nodes\n Object.defineProperty(_this, \"_isRunningAction\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n }); // only relevant for root\n Object.defineProperty(_this, \"_hasSnapshotReaction\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(_this, \"_observableInstanceState\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0 /* UNINITIALIZED */\n });\n Object.defineProperty(_this, \"_childNodes\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_initialSnapshot\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_cachedInitialSnapshot\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_cachedInitialSnapshotCreated\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(_this, \"_snapshotComputed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_snapshotUponDeath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // #region internal event handling\n Object.defineProperty(_this, \"_internalEvents\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _this._snapshotComputed = computed(function () { return freeze(_this.getSnapshot()); });\n _this.unbox = _this.unbox.bind(_this);\n _this._initialSnapshot = freeze(initialValue);\n _this.identifierAttribute = complexType.identifierAttribute;\n if (!parent) {\n _this.identifierCache = new IdentifierCache();\n }\n _this._childNodes = complexType.initializeChildNodes(_this, _this._initialSnapshot);\n // identifier can not be changed during lifecycle of a node\n // so we safely can read it from initial snapshot\n _this.identifier = null;\n _this.unnormalizedIdentifier = null;\n if (_this.identifierAttribute && _this._initialSnapshot) {\n var id = _this._initialSnapshot[_this.identifierAttribute];\n if (id === undefined) {\n // try with the actual node if not (for optional identifiers)\n var childNode = _this._childNodes[_this.identifierAttribute];\n if (childNode) {\n id = childNode.value;\n }\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw fail(\"Instance identifier '\" + _this.identifierAttribute + \"' for type '\" + _this.type.name + \"' must be a string or a number\");\n }\n // normalize internal identifier to string\n _this.identifier = normalizeIdentifier(id);\n _this.unnormalizedIdentifier = id;\n }\n if (!parent) {\n _this.identifierCache.addNodeToCache(_this);\n }\n else {\n parent.root.identifierCache.addNodeToCache(_this);\n }\n return _this;\n }\n Object.defineProperty(ObjectNode.prototype, \"applyPatches\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (patches) {\n this.createObservableInstanceIfNeeded();\n this._applyPatches(patches);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"applySnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot) {\n this.createObservableInstanceIfNeeded();\n this._applySnapshot(snapshot);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"createObservableInstanceIfNeeded\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fireHooks) {\n if (fireHooks === void 0) { fireHooks = true; }\n if (this._observableInstanceState === 0 /* UNINITIALIZED */) {\n this.createObservableInstance(fireHooks);\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"createObservableInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fireHooks) {\n var e_1, _a, e_2, _b;\n if (fireHooks === void 0) { fireHooks = true; }\n if (devMode()) {\n if (this.state !== NodeLifeCycle.INITIALIZING) {\n // istanbul ignore next\n throw fail(\"assertion failed: the creation of the observable instance must be done on the initializing phase\");\n }\n }\n this._observableInstanceState = 1 /* CREATING */;\n // make sure the parent chain is created as well\n // array with parent chain from parent to child\n var parentChain = [];\n var parent = this.parent;\n // for performance reasons we never go back further than the most direct\n // uninitialized parent\n // this is done to avoid traversing the whole tree to the root when using\n // the same reference again\n while (parent &&\n parent._observableInstanceState === 0 /* UNINITIALIZED */) {\n parentChain.unshift(parent);\n parent = parent.parent;\n }\n try {\n // initialize the uninitialized parent chain from parent to child\n for (var parentChain_1 = __values(parentChain), parentChain_1_1 = parentChain_1.next(); !parentChain_1_1.done; parentChain_1_1 = parentChain_1.next()) {\n var p = parentChain_1_1.value;\n // delay firing hooks until after all parents have been created\n p.createObservableInstanceIfNeeded(false);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (parentChain_1_1 && !parentChain_1_1.done && (_a = parentChain_1.return)) _a.call(parentChain_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var type = this.type;\n try {\n this.storedValue = type.createNewInstance(this._childNodes);\n this.preboot();\n this._isRunningAction = true;\n type.finalizeNewInstance(this, this.storedValue);\n }\n catch (e) {\n // short-cut to die the instance, to avoid the snapshot computed starting to throw...\n this.state = NodeLifeCycle.DEAD;\n throw e;\n }\n finally {\n this._isRunningAction = false;\n }\n this._observableInstanceState = 2 /* CREATED */;\n this._snapshotComputed.trackAndCompute();\n if (this.isRoot)\n this._addSnapshotReaction();\n this._childNodes = EMPTY_OBJECT;\n this.state = NodeLifeCycle.CREATED;\n if (fireHooks) {\n this.fireHook(Hook.afterCreate);\n // Note that the parent might not be finalized at this point\n // so afterAttach won't be called until later in that case\n this.finalizeCreation();\n try {\n // fire the hooks of the parents that we created\n for (var _c = __values(parentChain.reverse()), _d = _c.next(); !_d.done; _d = _c.next()) {\n var p = _d.value;\n p.fireHook(Hook.afterCreate);\n // This will call afterAttach on the child if necessary\n p.finalizeCreation();\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_b = _c.return)) _b.call(_c);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"root\", {\n get: function () {\n var parent = this.parent;\n return parent ? parent.root : this;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(ObjectNode.prototype, \"clearParent\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (!this.parent)\n return;\n // detach if attached\n this.fireHook(Hook.beforeDetach);\n var previousState = this.state;\n this.state = NodeLifeCycle.DETACHING;\n var root = this.root;\n var newEnv = root.environment;\n var newIdCache = root.identifierCache.splitCache(this);\n try {\n this.parent.removeChild(this.subpath);\n this.baseSetParent(null, \"\");\n this.environment = newEnv;\n this.identifierCache = newIdCache;\n }\n finally {\n this.state = previousState;\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"setParent\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (newParent, subpath) {\n var parentChanged = newParent !== this.parent;\n var subpathChanged = subpath !== this.subpath;\n if (!parentChanged && !subpathChanged) {\n return;\n }\n if (devMode()) {\n if (!subpath) {\n // istanbul ignore next\n throw fail(\"assertion failed: subpath expected\");\n }\n if (!newParent) {\n // istanbul ignore next\n throw fail(\"assertion failed: new parent expected\");\n }\n if (this.parent && parentChanged) {\n throw fail(\"A node cannot exists twice in the state tree. Failed to add \" + this + \" to path '\" + newParent.path + \"/\" + subpath + \"'.\");\n }\n if (!this.parent && newParent.root === this) {\n throw fail(\"A state tree is not allowed to contain itself. Cannot assign \" + this + \" to path '\" + newParent.path + \"/\" + subpath + \"'\");\n }\n if (!this.parent && !!this.environment && this.environment !== newParent.root.environment) {\n throw fail(\"A state tree cannot be made part of another state tree as long as their environments are different.\");\n }\n }\n if (parentChanged) {\n // attach to new parent\n this.environment = undefined; // will use root's\n newParent.root.identifierCache.mergeCache(this);\n this.baseSetParent(newParent, subpath);\n this.fireHook(Hook.afterAttach);\n }\n else if (subpathChanged) {\n // moving to a new subpath on the same parent\n this.baseSetParent(this.parent, subpath);\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"fireHook\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (name) {\n var _this = this;\n this.fireInternalHook(name);\n var fn = this.storedValue && typeof this.storedValue === \"object\" && this.storedValue[name];\n if (typeof fn === \"function\") {\n // we check for it to allow old mobx peer dependencies that don't have the method to work (even when still bugged)\n if (_allowStateChangesInsideComputed) {\n _allowStateChangesInsideComputed(function () {\n fn.apply(_this.storedValue);\n });\n }\n else {\n fn.apply(this.storedValue);\n }\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"snapshot\", {\n // advantage of using computed for a snapshot is that nicely respects transactions etc.\n get: function () {\n if (this.hasSnapshotPostProcessor) {\n this.createObservableInstanceIfNeeded();\n }\n return this._snapshotComputed.get();\n },\n enumerable: false,\n configurable: true\n });\n // NOTE: we use this method to get snapshot without creating @computed overhead\n Object.defineProperty(ObjectNode.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (!this.isAlive)\n return this._snapshotUponDeath;\n return this._observableInstanceState === 2 /* CREATED */\n ? this._getActualSnapshot()\n : this._getCachedInitialSnapshot();\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_getActualSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.type.getSnapshot(this);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_getCachedInitialSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (!this._cachedInitialSnapshotCreated) {\n var type = this.type;\n var childNodes = this._childNodes;\n var snapshot = this._initialSnapshot;\n this._cachedInitialSnapshot = type.processInitialSnapshot(childNodes, snapshot);\n this._cachedInitialSnapshotCreated = true;\n }\n return this._cachedInitialSnapshot;\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"isRunningAction\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this._isRunningAction)\n return true;\n if (this.isRoot)\n return false;\n return this.parent.isRunningAction();\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"assertAlive\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (context) {\n var livelinessChecking = getLivelinessChecking();\n if (!this.isAlive && livelinessChecking !== \"ignore\") {\n var error = this._getAssertAliveError(context);\n switch (livelinessChecking) {\n case \"error\":\n throw fail(error);\n case \"warn\":\n warnError(error);\n }\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_getAssertAliveError\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (context) {\n var escapedPath = this.getEscapedPath(false) || this.pathUponDeath || \"\";\n var subpath = (context.subpath && escapeJsonPath(context.subpath)) || \"\";\n var actionContext = context.actionContext || getCurrentActionContext();\n // try to use a real action context if possible since it includes the action name\n if (actionContext && actionContext.type !== \"action\" && actionContext.parentActionEvent) {\n actionContext = actionContext.parentActionEvent;\n }\n var actionFullPath = \"\";\n if (actionContext && actionContext.name != null) {\n // try to use the context, and if it not available use the node one\n var actionPath = (actionContext && actionContext.context && getPath(actionContext.context)) || escapedPath;\n actionFullPath = actionPath + \".\" + actionContext.name + \"()\";\n }\n 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: '\" + escapedPath + \"', Subpath: '\" + subpath + \"', Action: '\" + actionFullPath + \"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree.\";\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"getChildNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (subpath) {\n this.assertAlive({\n subpath: subpath\n });\n this._autoUnbox = false;\n try {\n return this._observableInstanceState === 2 /* CREATED */\n ? this.type.getChildNode(this, subpath)\n : this._childNodes[subpath];\n }\n finally {\n this._autoUnbox = true;\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"getChildren\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.assertAlive(EMPTY_OBJECT);\n this._autoUnbox = false;\n try {\n return this._observableInstanceState === 2 /* CREATED */\n ? this.type.getChildren(this)\n : convertChildNodesToArray(this._childNodes);\n }\n finally {\n this._autoUnbox = true;\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"getChildType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (propertyName) {\n return this.type.getChildType(propertyName);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"isProtected\", {\n get: function () {\n return this.root.isProtectionEnabled;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(ObjectNode.prototype, \"assertWritable\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (context) {\n this.assertAlive(context);\n if (!this.isRunningAction() && this.isProtected) {\n throw fail(\"Cannot modify '\" + this + \"', the object is protected and can only be modified by using an action.\");\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"removeChild\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (subpath) {\n this.type.removeChild(this, subpath);\n }\n });\n // bound on the constructor\n Object.defineProperty(ObjectNode.prototype, \"unbox\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNode) {\n if (!childNode)\n return childNode;\n this.assertAlive({\n subpath: childNode.subpath || childNode.subpathUponDeath\n });\n return this._autoUnbox ? childNode.value : childNode;\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"toString\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var path = (this.isAlive ? this.path : this.pathUponDeath) || \"\";\n var identifier = this.identifier ? \"(id: \" + this.identifier + \")\" : \"\";\n return this.type.name + \"@\" + path + identifier + (this.isAlive ? \"\" : \" [dead]\");\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"finalizeCreation\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var _this = this;\n this.baseFinalizeCreation(function () {\n var e_3, _a;\n try {\n for (var _b = __values(_this.getChildren()), _c = _b.next(); !_c.done; _c = _b.next()) {\n var child = _c.value;\n child.finalizeCreation();\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_3) throw e_3.error; }\n }\n _this.fireInternalHook(Hook.afterCreationFinalization);\n });\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"detach\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (!this.isAlive)\n throw fail(\"Error while detaching, node is not alive.\");\n this.clearParent();\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"preboot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var self = this;\n this._applyPatches = createActionInvoker(this.storedValue, \"@APPLY_PATCHES\", function (patches) {\n patches.forEach(function (patch) {\n if (!patch.path) {\n self.type.applySnapshot(self, patch.value);\n return;\n }\n var parts = splitJsonPath(patch.path);\n var node = resolveNodeByPathParts(self, parts.slice(0, -1));\n node.applyPatchLocally(parts[parts.length - 1], patch);\n });\n });\n this._applySnapshot = createActionInvoker(this.storedValue, \"@APPLY_SNAPSHOT\", function (snapshot) {\n // if the snapshot is the same as the current one, avoid performing a reconcile\n if (snapshot === self.snapshot)\n return;\n // else, apply it by calling the type logic\n return self.type.applySnapshot(self, snapshot);\n });\n addHiddenFinalProp(this.storedValue, \"$treenode\", this);\n addHiddenFinalProp(this.storedValue, \"toJSON\", toJSON);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"die\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (!this.isAlive || this.state === NodeLifeCycle.DETACHING)\n return;\n this.aboutToDie();\n this.finalizeDeath();\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"aboutToDie\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this._observableInstanceState === 0 /* UNINITIALIZED */) {\n return;\n }\n this.getChildren().forEach(function (node) {\n node.aboutToDie();\n });\n // beforeDestroy should run before the disposers since else we could end up in a situation where\n // a disposer added with addDisposer at this stage (beforeDestroy) is actually never released\n this.baseAboutToDie();\n this._internalEventsEmit(\"dispose\" /* Dispose */);\n this._internalEventsClear(\"dispose\" /* Dispose */);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"finalizeDeath\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n // invariant: not called directly but from \"die\"\n this.getChildren().forEach(function (node) {\n node.finalizeDeath();\n });\n this.root.identifierCache.notifyDied(this);\n // \"kill\" the computed prop and just store the last snapshot\n var snapshot = this.snapshot;\n this._snapshotUponDeath = snapshot;\n this._internalEventsClearAll();\n this.baseFinalizeDeath();\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"onSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (onChange) {\n this._addSnapshotReaction();\n return this._internalEventsRegister(\"snapshot\" /* Snapshot */, onChange);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"emitSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot) {\n this._internalEventsEmit(\"snapshot\" /* Snapshot */, snapshot);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"onPatch\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (handler) {\n return this._internalEventsRegister(\"patch\" /* Patch */, handler);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"emitPatch\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (basePatch, source) {\n if (this._internalEventsHasSubscribers(\"patch\" /* Patch */)) {\n var localizedPatch = extend({}, basePatch, {\n path: source.path.substr(this.path.length) + \"/\" + basePatch.path // calculate the relative path of the patch\n });\n var _a = __read(splitPatch(localizedPatch), 2), patch = _a[0], reversePatch = _a[1];\n this._internalEventsEmit(\"patch\" /* Patch */, patch, reversePatch);\n }\n if (this.parent)\n this.parent.emitPatch(basePatch, source);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"hasDisposer\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (disposer) {\n return this._internalEventsHas(\"dispose\" /* Dispose */, disposer);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"addDisposer\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (disposer) {\n if (!this.hasDisposer(disposer)) {\n this._internalEventsRegister(\"dispose\" /* Dispose */, disposer, true);\n return;\n }\n throw fail(\"cannot add a disposer when it is already registered for execution\");\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"removeDisposer\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (disposer) {\n if (!this._internalEventsHas(\"dispose\" /* Dispose */, disposer)) {\n throw fail(\"cannot remove a disposer which was never registered for execution\");\n }\n this._internalEventsUnregister(\"dispose\" /* Dispose */, disposer);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"removeMiddleware\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (middleware) {\n if (this.middlewares) {\n var index = this.middlewares.indexOf(middleware);\n if (index >= 0) {\n this.middlewares.splice(index, 1);\n }\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"addMiddleWare\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (handler, includeHooks) {\n var _this = this;\n if (includeHooks === void 0) { includeHooks = true; }\n var middleware = { handler: handler, includeHooks: includeHooks };\n if (!this.middlewares)\n this.middlewares = [middleware];\n else\n this.middlewares.push(middleware);\n return function () {\n _this.removeMiddleware(middleware);\n };\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"applyPatchLocally\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (subpath, patch) {\n this.assertWritable({\n subpath: subpath\n });\n this.createObservableInstanceIfNeeded();\n this.type.applyPatchLocally(this, subpath, patch);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_addSnapshotReaction\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var _this = this;\n if (!this._hasSnapshotReaction) {\n var snapshotDisposer = reaction(function () { return _this.snapshot; }, function (snapshot) { return _this.emitSnapshot(snapshot); }, snapshotReactionOptions);\n this.addDisposer(snapshotDisposer);\n this._hasSnapshotReaction = true;\n }\n }\n });\n // we proxy the methods to avoid creating an EventHandlers instance when it is not needed\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsHasSubscribers\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event) {\n return !!this._internalEvents && this._internalEvents.hasSubscribers(event);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsRegister\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event, eventHandler, atTheBeginning) {\n if (atTheBeginning === void 0) { atTheBeginning = false; }\n if (!this._internalEvents) {\n this._internalEvents = new EventHandlers();\n }\n return this._internalEvents.register(event, eventHandler, atTheBeginning);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsHas\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event, eventHandler) {\n return !!this._internalEvents && this._internalEvents.has(event, eventHandler);\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsUnregister\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event, eventHandler) {\n if (this._internalEvents) {\n this._internalEvents.unregister(event, eventHandler);\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsEmit\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event) {\n var _a;\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (this._internalEvents) {\n (_a = this._internalEvents).emit.apply(_a, __spread([event], args));\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsClear\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event) {\n if (this._internalEvents) {\n this._internalEvents.clear(event);\n }\n }\n });\n Object.defineProperty(ObjectNode.prototype, \"_internalEventsClearAll\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this._internalEvents) {\n this._internalEvents.clearAll();\n }\n }\n });\n return ObjectNode;\n}(BaseNode));\nObjectNode.prototype.createObservableInstance = action(ObjectNode.prototype.createObservableInstance);\nObjectNode.prototype.detach = action(ObjectNode.prototype.detach);\nObjectNode.prototype.die = action(ObjectNode.prototype.die);\n\nvar _a;\n/**\n * @internal\n * @hidden\n */\nvar TypeFlags;\n(function (TypeFlags) {\n TypeFlags[TypeFlags[\"String\"] = 1] = \"String\";\n TypeFlags[TypeFlags[\"Number\"] = 2] = \"Number\";\n TypeFlags[TypeFlags[\"Boolean\"] = 4] = \"Boolean\";\n TypeFlags[TypeFlags[\"Date\"] = 8] = \"Date\";\n TypeFlags[TypeFlags[\"Literal\"] = 16] = \"Literal\";\n TypeFlags[TypeFlags[\"Array\"] = 32] = \"Array\";\n TypeFlags[TypeFlags[\"Map\"] = 64] = \"Map\";\n TypeFlags[TypeFlags[\"Object\"] = 128] = \"Object\";\n TypeFlags[TypeFlags[\"Frozen\"] = 256] = \"Frozen\";\n TypeFlags[TypeFlags[\"Optional\"] = 512] = \"Optional\";\n TypeFlags[TypeFlags[\"Reference\"] = 1024] = \"Reference\";\n TypeFlags[TypeFlags[\"Identifier\"] = 2048] = \"Identifier\";\n TypeFlags[TypeFlags[\"Late\"] = 4096] = \"Late\";\n TypeFlags[TypeFlags[\"Refinement\"] = 8192] = \"Refinement\";\n TypeFlags[TypeFlags[\"Union\"] = 16384] = \"Union\";\n TypeFlags[TypeFlags[\"Null\"] = 32768] = \"Null\";\n TypeFlags[TypeFlags[\"Undefined\"] = 65536] = \"Undefined\";\n TypeFlags[TypeFlags[\"Integer\"] = 131072] = \"Integer\";\n TypeFlags[TypeFlags[\"Custom\"] = 262144] = \"Custom\";\n TypeFlags[TypeFlags[\"SnapshotProcessor\"] = 524288] = \"SnapshotProcessor\";\n TypeFlags[TypeFlags[\"Lazy\"] = 1048576] = \"Lazy\";\n TypeFlags[TypeFlags[\"Finite\"] = 2097152] = \"Finite\";\n TypeFlags[TypeFlags[\"Float\"] = 4194304] = \"Float\";\n})(TypeFlags || (TypeFlags = {}));\n/**\n * @internal\n * @hidden\n */\nvar cannotDetermineSubtype = \"cannotDetermine\";\n/** @hidden */\nvar $type = Symbol(\"$type\");\n/**\n * A base type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\nvar BaseType = /** @class */ (function () {\n function BaseType(name) {\n Object.defineProperty(this, _a, {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // these are just to make inner types avaialable to inherited classes\n Object.defineProperty(this, \"C\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"S\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"T\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"N\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"isType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = name;\n }\n Object.defineProperty(BaseType.prototype, \"create\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot, environment) {\n typecheckInternal(this, snapshot);\n return this.instantiate(null, \"\", environment, snapshot).value;\n }\n });\n Object.defineProperty(BaseType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, applyPostProcess) {\n // istanbul ignore next\n throw fail(\"unimplemented method\");\n }\n });\n Object.defineProperty(BaseType.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n return type === this;\n }\n });\n Object.defineProperty(BaseType.prototype, \"validate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var node = getStateTreeNodeSafe(value);\n if (node) {\n var valueType = getType(value);\n return this.isAssignableFrom(valueType)\n ? typeCheckSuccess()\n : typeCheckFailure(context, value);\n // it is tempting to compare snapshots, but in that case we should always clone on assignments...\n }\n return this.isValidSnapshot(value, context);\n }\n });\n Object.defineProperty(BaseType.prototype, \"is\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (thing) {\n return this.validate(thing, [{ path: \"\", type: this }]).length === 0;\n }\n });\n Object.defineProperty(BaseType.prototype, \"Type\", {\n get: function () {\n // istanbul ignore next\n 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`\");\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseType.prototype, \"TypeWithoutSTN\", {\n get: function () {\n // istanbul ignore next\n 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`\");\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseType.prototype, \"SnapshotType\", {\n get: function () {\n // istanbul ignore next\n 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`\");\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseType.prototype, \"CreationType\", {\n get: function () {\n // istanbul ignore next\n 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`\");\n },\n enumerable: false,\n configurable: true\n });\n return BaseType;\n}());\n_a = $type;\nBaseType.prototype.create = action(BaseType.prototype.create);\n/**\n * A complex type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\nvar ComplexType = /** @class */ (function (_super) {\n __extends(ComplexType, _super);\n function ComplexType(name) {\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"identifierAttribute\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n return _this;\n }\n Object.defineProperty(ComplexType.prototype, \"create\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot, environment) {\n if (snapshot === void 0) { snapshot = this.getDefaultSnapshot(); }\n return _super.prototype.create.call(this, snapshot, environment);\n }\n });\n Object.defineProperty(ComplexType.prototype, \"getValue\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n node.createObservableInstanceIfNeeded();\n return node.storedValue;\n }\n });\n Object.defineProperty(ComplexType.prototype, \"isMatchingSnapshotId\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, snapshot) {\n return (!current.identifierAttribute ||\n current.identifier === normalizeIdentifier(snapshot[current.identifierAttribute]));\n }\n });\n Object.defineProperty(ComplexType.prototype, \"tryToReconcileNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue) {\n if (current.isDetaching)\n return false;\n if (current.snapshot === newValue) {\n // newValue is the current snapshot of the node, noop\n return true;\n }\n if (isStateTreeNode(newValue) && getStateTreeNode(newValue) === current) {\n // the current node is the same as the new one\n return true;\n }\n if (current.type === this &&\n isMutable(newValue) &&\n !isStateTreeNode(newValue) &&\n this.isMatchingSnapshotId(current, newValue)) {\n // the newValue has no node, so can be treated like a snapshot\n // we can reconcile\n current.applySnapshot(newValue);\n return true;\n }\n return false;\n }\n });\n Object.defineProperty(ComplexType.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n var nodeReconciled = this.tryToReconcileNode(current, newValue);\n if (nodeReconciled) {\n current.setParent(parent, subpath);\n return current;\n }\n // current node cannot be recycled in any way\n current.die(); // noop if detaching\n // attempt to reuse the new one\n if (isStateTreeNode(newValue) && this.isAssignableFrom(getType(newValue))) {\n // newValue is a Node as well, move it here..\n var newNode = getStateTreeNode(newValue);\n newNode.setParent(parent, subpath);\n return newNode;\n }\n // nothing to do, we have to create a new node\n return this.instantiate(parent, subpath, undefined, newValue);\n }\n });\n Object.defineProperty(ComplexType.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return null;\n }\n });\n return ComplexType;\n}(BaseType));\nComplexType.prototype.create = action(ComplexType.prototype.create);\n/**\n * @internal\n * @hidden\n */\nvar SimpleType = /** @class */ (function (_super) {\n __extends(SimpleType, _super);\n function SimpleType() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(SimpleType.prototype, \"createNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot) {\n return snapshot;\n }\n });\n Object.defineProperty(SimpleType.prototype, \"getValue\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n // if we ever find a case where scalar nodes can be accessed without iterating through its parent\n // uncomment this to make sure the parent chain is created when this is accessed\n // if (node.parent) {\n // node.parent.createObservableInstanceIfNeeded()\n // }\n return node.storedValue;\n }\n });\n Object.defineProperty(SimpleType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n return node.storedValue;\n }\n });\n Object.defineProperty(SimpleType.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n // reconcile only if type and value are still the same, and only if the node is not detaching\n if (!current.isDetaching && current.type === this && current.storedValue === newValue) {\n return current;\n }\n var res = this.instantiate(parent, subpath, undefined, newValue);\n current.die(); // noop if detaching\n return res;\n }\n });\n Object.defineProperty(SimpleType.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return null;\n }\n });\n return SimpleType;\n}(BaseType));\n/**\n * Returns if a given value represents a type.\n *\n * @param value Value to check.\n * @returns `true` if the value is a type.\n */\nfunction isType(value) {\n return typeof value === \"object\" && value && value.isType === true;\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertIsType(type, argNumber) {\n assertArg(type, isType, \"mobx-state-tree type\", argNumber);\n}\n\nvar runningActions = new Map();\n/**\n * Note: Consider migrating to `createActionTrackingMiddleware2`, it is easier to use.\n *\n * Convenience utility to create action based middleware that supports async processes more easily.\n * All hooks are called for both synchronous and asynchronous actions. Except that either `onSuccess` or `onFail` is called\n *\n * The create middleware tracks the process of an action (assuming it passes the `filter`).\n * `onResume` can return any value, which will be passed as second argument to any other hook. This makes it possible to keep state during a process.\n *\n * See the `atomic` middleware for an example\n *\n * @param hooks\n * @returns\n */\nfunction createActionTrackingMiddleware(hooks) {\n return function actionTrackingMiddleware(call, next, abort) {\n switch (call.type) {\n case \"action\": {\n if (!hooks.filter || hooks.filter(call) === true) {\n var context = hooks.onStart(call);\n hooks.onResume(call, context);\n runningActions.set(call.id, {\n call: call,\n context: context,\n async: false\n });\n try {\n var res = next(call);\n hooks.onSuspend(call, context);\n if (runningActions.get(call.id).async === false) {\n runningActions.delete(call.id);\n hooks.onSuccess(call, context, res);\n }\n return res;\n }\n catch (e) {\n runningActions.delete(call.id);\n hooks.onFail(call, context, e);\n throw e;\n }\n }\n else {\n return next(call);\n }\n }\n case \"flow_spawn\": {\n var root = runningActions.get(call.rootId);\n root.async = true;\n return next(call);\n }\n case \"flow_resume\":\n case \"flow_resume_error\": {\n var root = runningActions.get(call.rootId);\n hooks.onResume(call, root.context);\n try {\n return next(call);\n }\n finally {\n hooks.onSuspend(call, root.context);\n }\n }\n case \"flow_throw\": {\n var root = runningActions.get(call.rootId);\n runningActions.delete(call.rootId);\n hooks.onFail(call, root.context, call.args[0]);\n return next(call);\n }\n case \"flow_return\": {\n var root = runningActions.get(call.rootId);\n runningActions.delete(call.rootId);\n hooks.onSuccess(call, root.context, call.args[0]);\n return next(call);\n }\n }\n };\n}\n\nvar RunningAction = /** @class */ (function () {\n function RunningAction(hooks, call) {\n Object.defineProperty(this, \"hooks\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: hooks\n });\n Object.defineProperty(this, \"call\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: call\n });\n Object.defineProperty(this, \"flowsPending\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"running\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n if (hooks) {\n hooks.onStart(call);\n }\n }\n Object.defineProperty(RunningAction.prototype, \"finish\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (error) {\n if (this.running) {\n this.running = false;\n if (this.hooks) {\n this.hooks.onFinish(this.call, error);\n }\n }\n }\n });\n Object.defineProperty(RunningAction.prototype, \"incFlowsPending\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.flowsPending++;\n }\n });\n Object.defineProperty(RunningAction.prototype, \"decFlowsPending\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.flowsPending--;\n }\n });\n Object.defineProperty(RunningAction.prototype, \"hasFlowsPending\", {\n get: function () {\n return this.flowsPending > 0;\n },\n enumerable: false,\n configurable: true\n });\n return RunningAction;\n}());\n/**\n * Convenience utility to create action based middleware that supports async processes more easily.\n * The flow is like this:\n * - for each action: if filter passes -> `onStart` -> (inner actions recursively) -> `onFinish`\n *\n * Example: if we had an action `a` that called inside an action `b1`, then `b2` the flow would be:\n * - `filter(a)`\n * - `onStart(a)`\n * - `filter(b1)`\n * - `onStart(b1)`\n * - `onFinish(b1)`\n * - `filter(b2)`\n * - `onStart(b2)`\n * - `onFinish(b2)`\n * - `onFinish(a)`\n *\n * The flow is the same no matter if the actions are sync or async.\n *\n * See the `atomic` middleware for an example\n *\n * @param hooks\n * @returns\n */\nfunction createActionTrackingMiddleware2(middlewareHooks) {\n var runningActions = new Map();\n return function actionTrackingMiddleware(call, next) {\n // find parentRunningAction\n var parentRunningAction = call.parentActionEvent\n ? runningActions.get(call.parentActionEvent.id)\n : undefined;\n if (call.type === \"action\") {\n var newCall = __assign(__assign({}, call), { \n // make a shallow copy of the parent action env\n env: parentRunningAction && parentRunningAction.call.env, parentCall: parentRunningAction && parentRunningAction.call });\n var passesFilter = !middlewareHooks.filter || middlewareHooks.filter(newCall);\n var hooks = passesFilter ? middlewareHooks : undefined;\n var runningAction = new RunningAction(hooks, newCall);\n runningActions.set(call.id, runningAction);\n var res = void 0;\n try {\n res = next(call);\n }\n catch (e) {\n runningActions.delete(call.id);\n runningAction.finish(e);\n throw e;\n }\n // sync action finished\n if (!runningAction.hasFlowsPending) {\n runningActions.delete(call.id);\n runningAction.finish();\n }\n return res;\n }\n else {\n if (!parentRunningAction) {\n return next(call);\n }\n switch (call.type) {\n case \"flow_spawn\": {\n parentRunningAction.incFlowsPending();\n return next(call);\n }\n case \"flow_resume\":\n case \"flow_resume_error\": {\n return next(call);\n }\n case \"flow_throw\": {\n var error = call.args[0];\n try {\n return next(call);\n }\n finally {\n parentRunningAction.decFlowsPending();\n if (!parentRunningAction.hasFlowsPending) {\n runningActions.delete(call.parentActionEvent.id);\n parentRunningAction.finish(error);\n }\n }\n }\n case \"flow_return\": {\n try {\n return next(call);\n }\n finally {\n parentRunningAction.decFlowsPending();\n if (!parentRunningAction.hasFlowsPending) {\n runningActions.delete(call.parentActionEvent.id);\n parentRunningAction.finish();\n }\n }\n }\n }\n }\n };\n}\n\nfunction serializeArgument(node, actionName, index, arg) {\n if (arg instanceof Date)\n return { $MST_DATE: arg.getTime() };\n if (isPrimitive(arg))\n return arg;\n // We should not serialize MST nodes, even if we can, because we don't know if the receiving party can handle a raw snapshot instead of an\n // MST type instance. So if one wants to serialize a MST node that was pass in, either explitly pass: 1: an id, 2: a (relative) path, 3: a snapshot\n if (isStateTreeNode(arg))\n return serializeTheUnserializable(\"[MSTNode: \" + getType(arg).name + \"]\");\n if (typeof arg === \"function\")\n return serializeTheUnserializable(\"[function]\");\n if (typeof arg === \"object\" && !isPlainObject(arg) && !isArray(arg))\n return serializeTheUnserializable(\"[object \" + ((arg && arg.constructor && arg.constructor.name) || \"Complex Object\") + \"]\");\n try {\n // Check if serializable, cycle free etc...\n // MWE: there must be a better way....\n JSON.stringify(arg); // or throws\n return arg;\n }\n catch (e) {\n return serializeTheUnserializable(\"\" + e);\n }\n}\nfunction deserializeArgument(adm, value) {\n if (value && typeof value === \"object\" && \"$MST_DATE\" in value)\n return new Date(value[\"$MST_DATE\"]);\n return value;\n}\nfunction serializeTheUnserializable(baseType) {\n return {\n $MST_UNSERIALIZABLE: true,\n type: baseType\n };\n}\n/**\n * Applies an action or a series of actions in a single MobX transaction.\n * Does not return any value\n * Takes an action description as produced by the `onAction` middleware.\n *\n * @param target\n * @param actions\n */\nfunction applyAction(target, actions) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertArg(actions, function (a) { return typeof a === \"object\"; }, \"object or array\", 2);\n runInAction(function () {\n asArray(actions).forEach(function (action) { return baseApplyAction(target, action); });\n });\n}\nfunction baseApplyAction(target, action) {\n var resolvedTarget = tryResolve(target, action.path || \"\");\n if (!resolvedTarget)\n throw fail(\"Invalid action path: \" + (action.path || \"\"));\n var node = getStateTreeNode(resolvedTarget);\n // Reserved functions\n if (action.name === \"@APPLY_PATCHES\") {\n return applyPatch.call(null, resolvedTarget, action.args[0]);\n }\n if (action.name === \"@APPLY_SNAPSHOT\") {\n return applySnapshot.call(null, resolvedTarget, action.args[0]);\n }\n if (!(typeof resolvedTarget[action.name] === \"function\"))\n throw fail(\"Action '\" + action.name + \"' does not exist in '\" + node.path + \"'\");\n return resolvedTarget[action.name].apply(resolvedTarget, action.args ? action.args.map(function (v) { return deserializeArgument(node, v); }) : []);\n}\n/**\n * Small abstraction around `onAction` and `applyAction`, attaches an action listener to a tree and records all the actions emitted.\n * Returns an recorder object with the following signature:\n *\n * Example:\n * ```ts\n * export interface IActionRecorder {\n * // the recorded actions\n * actions: ISerializedActionCall[]\n * // true if currently recording\n * recording: boolean\n * // stop recording actions\n * stop(): void\n * // resume recording actions\n * resume(): void\n * // apply all the recorded actions on the given object\n * replay(target: IAnyStateTreeNode): void\n * }\n * ```\n *\n * The optional filter function allows to skip recording certain actions.\n *\n * @param subject\n * @returns\n */\nfunction recordActions(subject, filter) {\n // check all arguments\n assertIsStateTreeNode(subject, 1);\n var actions = [];\n var listener = function (call) {\n var recordThis = filter ? filter(call, getRunningActionContext()) : true;\n if (recordThis) {\n actions.push(call);\n }\n };\n var disposer;\n var recorder = {\n actions: actions,\n get recording() {\n return !!disposer;\n },\n stop: function () {\n if (disposer) {\n disposer();\n disposer = undefined;\n }\n },\n resume: function () {\n if (disposer)\n return;\n disposer = onAction(subject, listener);\n },\n replay: function (target) {\n applyAction(target, actions);\n }\n };\n recorder.resume();\n return recorder;\n}\n/**\n * Registers a function that will be invoked for each action that is called on the provided model instance, or to any of its children.\n * See [actions](https://github.com/mobxjs/mobx-state-tree#actions) for more details. onAction events are emitted only for the outermost called action in the stack.\n * Action can also be intercepted by middleware using addMiddleware to change the function call before it will be run.\n *\n * Not all action arguments might be serializable. For unserializable arguments, a struct like `{ $MST_UNSERIALIZABLE: true, type: \"someType\" }` will be generated.\n * MST Nodes are considered non-serializable as well (they could be serialized as there snapshot, but it is uncertain whether an replaying party will be able to handle such a non-instantiated snapshot).\n * Rather, when using `onAction` middleware, one should consider in passing arguments which are 1: an id, 2: a (relative) path, or 3: a snapshot. Instead of a real MST node.\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.array(Todo)\n * }).actions(self => ({\n * add(todo) {\n * self.todos.push(todo);\n * }\n * }))\n *\n * const s = TodoStore.create({ todos: [] })\n *\n * let disposer = onAction(s, (call) => {\n * console.log(call);\n * })\n *\n * s.add({ task: \"Grab a coffee\" })\n * // Logs: { name: \"add\", path: \"\", args: [{ task: \"Grab a coffee\" }] }\n * ```\n *\n * @param target\n * @param listener\n * @param attachAfter (default false) fires the listener *after* the action has executed instead of before.\n * @returns\n */\nfunction onAction(target, listener, attachAfter) {\n if (attachAfter === void 0) { attachAfter = false; }\n // check all arguments\n assertIsStateTreeNode(target, 1);\n if (devMode()) {\n if (!isRoot(target))\n warnError(\"Warning: Attaching onAction listeners to non root nodes is dangerous: No events will be emitted for actions initiated higher up in the tree.\");\n if (!isProtected(target))\n warnError(\"Warning: Attaching onAction listeners to non protected nodes is dangerous: No events will be emitted for direct modifications without action.\");\n }\n return addMiddleware(target, function handler(rawCall, next) {\n if (rawCall.type === \"action\" && rawCall.id === rawCall.rootId) {\n var sourceNode_1 = getStateTreeNode(rawCall.context);\n var info = {\n name: rawCall.name,\n path: getRelativePathBetweenNodes(getStateTreeNode(target), sourceNode_1),\n args: rawCall.args.map(function (arg, index) {\n return serializeArgument(sourceNode_1, rawCall.name, index, arg);\n })\n };\n if (attachAfter) {\n var res = next(rawCall);\n listener(info);\n return res;\n }\n else {\n listener(info);\n return next(rawCall);\n }\n }\n else {\n return next(rawCall);\n }\n });\n}\n\nvar nextActionId = 1;\nvar currentActionContext;\n/**\n * @internal\n * @hidden\n */\nfunction getCurrentActionContext() {\n return currentActionContext;\n}\n/**\n * @internal\n * @hidden\n */\nfunction getNextActionId() {\n return nextActionId++;\n}\n// TODO: optimize away entire action context if there is no middleware in tree?\n/**\n * @internal\n * @hidden\n */\nfunction runWithActionContext(context, fn) {\n var node = getStateTreeNode(context.context);\n if (context.type === \"action\") {\n node.assertAlive({\n actionContext: context\n });\n }\n var baseIsRunningAction = node._isRunningAction;\n node._isRunningAction = true;\n var previousContext = currentActionContext;\n currentActionContext = context;\n try {\n return runMiddleWares(node, context, fn);\n }\n finally {\n currentActionContext = previousContext;\n node._isRunningAction = baseIsRunningAction;\n }\n}\n/**\n * @internal\n * @hidden\n */\nfunction getParentActionContext(parentContext) {\n if (!parentContext)\n return undefined;\n if (parentContext.type === \"action\")\n return parentContext;\n return parentContext.parentActionEvent;\n}\n/**\n * @internal\n * @hidden\n */\nfunction createActionInvoker(target, name, fn) {\n var res = function () {\n var id = getNextActionId();\n var parentContext = currentActionContext;\n var parentActionContext = getParentActionContext(parentContext);\n return runWithActionContext({\n type: \"action\",\n name: name,\n id: id,\n args: argsToArray(arguments),\n context: target,\n tree: getRoot(target),\n rootId: parentContext ? parentContext.rootId : id,\n parentId: parentContext ? parentContext.id : 0,\n allParentIds: parentContext ? __spread(parentContext.allParentIds, [parentContext.id]) : [],\n parentEvent: parentContext,\n parentActionEvent: parentActionContext\n }, fn);\n };\n res._isMSTAction = true;\n res._isFlowAction = fn._isFlowAction;\n return res;\n}\n/**\n * Middleware can be used to intercept any action is invoked on the subtree where it is attached.\n * If a tree is protected (by default), this means that any mutation of the tree will pass through your middleware.\n *\n * For more details, see the [middleware docs](concepts/middleware.md)\n *\n * @param target Node to apply the middleware to.\n * @param middleware Middleware to apply.\n * @returns A callable function to dispose the middleware.\n */\nfunction addMiddleware(target, handler, includeHooks) {\n if (includeHooks === void 0) { includeHooks = true; }\n var node = getStateTreeNode(target);\n if (devMode()) {\n if (!node.isProtectionEnabled) {\n 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`\");\n }\n }\n return node.addMiddleWare(handler, includeHooks);\n}\n/**\n * Binds middleware to a specific action.\n *\n * Example:\n * ```ts\n * type.actions(self => {\n * function takeA____() {\n * self.toilet.donate()\n * self.wipe()\n * self.wipe()\n * self.toilet.flush()\n * }\n * return {\n * takeA____: decorate(atomic, takeA____)\n * }\n * })\n * ```\n *\n * @param handler\n * @param fn\n * @param includeHooks\n * @returns The original function\n */\nfunction decorate(handler, fn, includeHooks) {\n if (includeHooks === void 0) { includeHooks = true; }\n var middleware = { handler: handler, includeHooks: includeHooks };\n fn.$mst_middleware = fn.$mst_middleware || [];\n fn.$mst_middleware.push(middleware);\n return fn;\n}\nvar CollectedMiddlewares = /** @class */ (function () {\n function CollectedMiddlewares(node, fn) {\n Object.defineProperty(this, \"arrayIndex\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"inArrayIndex\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"middlewares\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n // we just push middleware arrays into an array of arrays to avoid making copies\n if (fn.$mst_middleware) {\n this.middlewares.push(fn.$mst_middleware);\n }\n var n = node;\n // Find all middlewares. Optimization: cache this?\n while (n) {\n if (n.middlewares)\n this.middlewares.push(n.middlewares);\n n = n.parent;\n }\n }\n Object.defineProperty(CollectedMiddlewares.prototype, \"isEmpty\", {\n get: function () {\n return this.middlewares.length <= 0;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(CollectedMiddlewares.prototype, \"getNextMiddleware\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var array = this.middlewares[this.arrayIndex];\n if (!array)\n return undefined;\n var item = array[this.inArrayIndex++];\n if (!item) {\n this.arrayIndex++;\n this.inArrayIndex = 0;\n return this.getNextMiddleware();\n }\n return item;\n }\n });\n return CollectedMiddlewares;\n}());\nfunction runMiddleWares(node, baseCall, originalFn) {\n var middlewares = new CollectedMiddlewares(node, originalFn);\n // Short circuit\n if (middlewares.isEmpty)\n return action(originalFn).apply(null, baseCall.args);\n var result = null;\n function runNextMiddleware(call) {\n var middleware = middlewares.getNextMiddleware();\n var handler = middleware && middleware.handler;\n if (!handler) {\n return action(originalFn).apply(null, call.args);\n }\n // skip hooks if asked to\n if (!middleware.includeHooks && Hook[call.name]) {\n return runNextMiddleware(call);\n }\n var nextInvoked = false;\n function next(call2, callback) {\n nextInvoked = true;\n // the result can contain\n // - the non manipulated return value from an action\n // - the non manipulated abort value\n // - one of the above but manipulated through the callback function\n result = runNextMiddleware(call2);\n if (callback) {\n result = callback(result);\n }\n }\n var abortInvoked = false;\n function abort(value) {\n abortInvoked = true;\n // overwrite the result\n // can be manipulated through middlewares earlier in the queue using the callback fn\n result = value;\n }\n handler(call, next, abort);\n if (devMode()) {\n if (!nextInvoked && !abortInvoked) {\n var node2 = getStateTreeNode(call.tree);\n throw fail(\"Neither the next() nor the abort() callback within the middleware \" + handler.name + \" for the action: \\\"\" + call.name + \"\\\" on the node: \" + node2.type.name + \" was invoked.\");\n }\n else if (nextInvoked && abortInvoked) {\n var node2 = getStateTreeNode(call.tree);\n throw fail(\"The next() and abort() callback within the middleware \" + handler.name + \" for the action: \\\"\" + call.name + \"\\\" on the node: \" + node2.type.name + \" were invoked.\");\n }\n }\n return result;\n }\n return runNextMiddleware(baseCall);\n}\n\n/**\n * Returns the currently executing MST action context, or undefined if none.\n */\nfunction getRunningActionContext() {\n var current = getCurrentActionContext();\n while (current && current.type !== \"action\") {\n current = current.parentActionEvent;\n }\n return current;\n}\nfunction _isActionContextThisOrChildOf(actionContext, sameOrParent, includeSame) {\n var parentId = typeof sameOrParent === \"number\" ? sameOrParent : sameOrParent.id;\n var current = includeSame\n ? actionContext\n : actionContext.parentActionEvent;\n while (current) {\n if (current.id === parentId) {\n return true;\n }\n current = current.parentActionEvent;\n }\n return false;\n}\n/**\n * Returns if the given action context is a parent of this action context.\n */\nfunction isActionContextChildOf(actionContext, parent) {\n return _isActionContextThisOrChildOf(actionContext, parent, false);\n}\n/**\n * Returns if the given action context is this or a parent of this action context.\n */\nfunction isActionContextThisOrChildOf(actionContext, parentOrThis) {\n return _isActionContextThisOrChildOf(actionContext, parentOrThis, true);\n}\n\nfunction safeStringify(value) {\n try {\n return JSON.stringify(value);\n }\n catch (e) {\n // istanbul ignore next\n return \"\";\n }\n}\n/**\n * @internal\n * @hidden\n */\nfunction prettyPrintValue(value) {\n return typeof value === \"function\"\n ? \"\"\n : isStateTreeNode(value)\n ? \"<\" + value + \">\"\n : \"`\" + safeStringify(value) + \"`\";\n}\nfunction shortenPrintValue(valueInString) {\n return valueInString.length < 280\n ? valueInString\n : valueInString.substring(0, 272) + \"......\" + valueInString.substring(valueInString.length - 8);\n}\nfunction toErrorString(error) {\n var value = error.value;\n var type = error.context[error.context.length - 1].type;\n var fullPath = error.context\n .map(function (_a) {\n var path = _a.path;\n return path;\n })\n .filter(function (path) { return path.length > 0; })\n .join(\"/\");\n var pathPrefix = fullPath.length > 0 ? \"at path \\\"/\" + fullPath + \"\\\" \" : \"\";\n var currentTypename = isStateTreeNode(value)\n ? \"value of type \" + getStateTreeNode(value).type.name + \":\"\n : isPrimitive(value)\n ? \"value\"\n : \"snapshot\";\n var isSnapshotCompatible = type && isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot);\n return (\"\" + pathPrefix + currentTypename + \" \" + prettyPrintValue(value) + \" is not assignable \" + (type ? \"to type: `\" + type.name + \"`\" : \"\") +\n (error.message ? \" (\" + error.message + \")\" : \"\") +\n (type\n ? isPrimitiveType(type) || isPrimitive(value)\n ? \".\"\n : \", expected an instance of `\" + type.name + \"` or a snapshot like `\" + type.describe() + \"` instead.\" +\n (isSnapshotCompatible\n ? \" (Note that a snapshot of the provided value is compatible with the targeted type)\"\n : \"\")\n : \".\"));\n}\n/**\n * @internal\n * @hidden\n */\nfunction getContextForPath(context, path, type) {\n return context.concat([{ path: path, type: type }]);\n}\n/**\n * @internal\n * @hidden\n */\nfunction typeCheckSuccess() {\n return EMPTY_ARRAY;\n}\n/**\n * @internal\n * @hidden\n */\nfunction typeCheckFailure(context, value, message) {\n return [{ context: context, value: value, message: message }];\n}\n/**\n * @internal\n * @hidden\n */\nfunction flattenTypeErrors(errors) {\n return errors.reduce(function (a, i) { return a.concat(i); }, []);\n}\n// TODO; doublecheck: typecheck should only needed to be invoked from: type.create and array / map / value.property will change\n/**\n * @internal\n * @hidden\n */\nfunction typecheckInternal(type, value) {\n // runs typeChecking if it is in dev-mode or through a process.env.ENABLE_TYPE_CHECK flag\n if (isTypeCheckingEnabled()) {\n typecheck(type, value);\n }\n}\n/**\n * Run's the typechecker for the given type on the given value, which can be a snapshot or an instance.\n * Throws if the given value is not according the provided type specification.\n * Use this if you need typechecks even in a production build (by default all automatic runtime type checks will be skipped in production builds)\n *\n * @param type Type to check against.\n * @param value Value to be checked, either a snapshot or an instance.\n */\nfunction typecheck(type, value) {\n var errors = type.validate(value, [{ path: \"\", type: type }]);\n if (errors.length > 0) {\n throw fail(validationErrorsToString(type, value, errors));\n }\n}\nfunction validationErrorsToString(type, value, errors) {\n if (errors.length === 0) {\n return undefined;\n }\n return (\"Error while converting \" + shortenPrintValue(prettyPrintValue(value)) + \" to `\" + type.name + \"`:\\n\\n \" + errors.map(toErrorString).join(\"\\n \"));\n}\n\nvar identifierCacheId = 0;\n/**\n * @internal\n * @hidden\n */\nvar IdentifierCache = /** @class */ (function () {\n function IdentifierCache() {\n Object.defineProperty(this, \"cacheId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: identifierCacheId++\n });\n // n.b. in cache all identifiers are normalized to strings\n Object.defineProperty(this, \"cache\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: observable.map()\n });\n // last time the cache (array) for a given time changed\n // n.b. it is not really the time, but just an integer that gets increased after each modification to the array\n Object.defineProperty(this, \"lastCacheModificationPerId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: observable.map()\n });\n }\n Object.defineProperty(IdentifierCache.prototype, \"updateLastCacheModificationPerId\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (identifier) {\n var lcm = this.lastCacheModificationPerId.get(identifier);\n // we start at 1 since 0 means no update since cache creation\n this.lastCacheModificationPerId.set(identifier, lcm === undefined ? 1 : lcm + 1);\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"getLastCacheModificationPerId\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (identifier) {\n var modificationId = this.lastCacheModificationPerId.get(identifier) || 0;\n return this.cacheId + \"-\" + modificationId;\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"addNodeToCache\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, lastCacheUpdate) {\n if (lastCacheUpdate === void 0) { lastCacheUpdate = true; }\n if (node.identifierAttribute) {\n var identifier = node.identifier;\n if (!this.cache.has(identifier)) {\n this.cache.set(identifier, observable.array([], mobxShallow));\n }\n var set = this.cache.get(identifier);\n if (set.indexOf(node) !== -1)\n throw fail(\"Already registered\");\n set.push(node);\n if (lastCacheUpdate) {\n this.updateLastCacheModificationPerId(identifier);\n }\n }\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"mergeCache\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n var _this = this;\n values(node.identifierCache.cache).forEach(function (nodes) {\n return nodes.forEach(function (child) {\n _this.addNodeToCache(child);\n });\n });\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"notifyDied\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n if (node.identifierAttribute) {\n var id = node.identifier;\n var set = this.cache.get(id);\n if (set) {\n set.remove(node);\n // remove empty sets from cache\n if (!set.length) {\n this.cache.delete(id);\n }\n this.updateLastCacheModificationPerId(node.identifier);\n }\n }\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"splitCache\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (splitNode) {\n var _this = this;\n var newCache = new IdentifierCache();\n // The slash is added here so we only match children of the splitNode. In version 5.1.8 and\n // earlier there was no trailing slash, so non children that started with the same path string\n // were being matched incorrectly.\n var basePath = splitNode.path + \"/\";\n entries(this.cache).forEach(function (_a) {\n var _b = __read(_a, 2), id = _b[0], nodes = _b[1];\n var modified = false;\n for (var i = nodes.length - 1; i >= 0; i--) {\n var node = nodes[i];\n if (node === splitNode || node.path.indexOf(basePath) === 0) {\n newCache.addNodeToCache(node, false); // no need to update lastUpdated since it is a whole new cache\n nodes.splice(i, 1);\n // remove empty sets from cache\n if (!nodes.length) {\n _this.cache.delete(id);\n }\n modified = true;\n }\n }\n if (modified) {\n _this.updateLastCacheModificationPerId(id);\n }\n });\n return newCache;\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"has\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type, identifier) {\n var set = this.cache.get(identifier);\n if (!set)\n return false;\n return set.some(function (candidate) { return type.isAssignableFrom(candidate.type); });\n }\n });\n Object.defineProperty(IdentifierCache.prototype, \"resolve\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type, identifier) {\n var set = this.cache.get(identifier);\n if (!set)\n return null;\n var matches = set.filter(function (candidate) { return type.isAssignableFrom(candidate.type); });\n switch (matches.length) {\n case 0:\n return null;\n case 1:\n return matches[0];\n default:\n throw fail(\"Cannot resolve a reference to type '\" + type.name + \"' with id: '\" + identifier + \"' unambigously, there are multiple candidates: \" + matches\n .map(function (n) { return n.path; })\n .join(\", \"));\n }\n }\n });\n return IdentifierCache;\n}());\n\n/**\n * @internal\n * @hidden\n */\nfunction createObjectNode(type, parent, subpath, environment, initialValue) {\n var existingNode = getStateTreeNodeSafe(initialValue);\n if (existingNode) {\n if (existingNode.parent) {\n // istanbul ignore next\n 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 '\" + (parent ? parent.path : \"\") + \"/\" + subpath + \"', but it lives already at '\" + existingNode.path + \"'\");\n }\n if (parent) {\n existingNode.setParent(parent, subpath);\n }\n // else it already has no parent since it is a pre-requisite\n return existingNode;\n }\n // not a node, a snapshot\n return new ObjectNode(type, parent, subpath, environment, initialValue);\n}\n/**\n * @internal\n * @hidden\n */\nfunction createScalarNode(type, parent, subpath, environment, initialValue) {\n return new ScalarNode(type, parent, subpath, environment, initialValue);\n}\n/**\n * @internal\n * @hidden\n */\nfunction isNode(value) {\n return value instanceof ScalarNode || value instanceof ObjectNode;\n}\n\n/**\n * @internal\n * @hidden\n */\nvar NodeLifeCycle;\n(function (NodeLifeCycle) {\n NodeLifeCycle[NodeLifeCycle[\"INITIALIZING\"] = 0] = \"INITIALIZING\";\n NodeLifeCycle[NodeLifeCycle[\"CREATED\"] = 1] = \"CREATED\";\n NodeLifeCycle[NodeLifeCycle[\"FINALIZED\"] = 2] = \"FINALIZED\";\n NodeLifeCycle[NodeLifeCycle[\"DETACHING\"] = 3] = \"DETACHING\";\n NodeLifeCycle[NodeLifeCycle[\"DEAD\"] = 4] = \"DEAD\"; // no coming back from this one\n})(NodeLifeCycle || (NodeLifeCycle = {}));\n/**\n * Returns true if the given value is a node in a state tree.\n * More precisely, that is, if the value is an instance of a\n * `types.model`, `types.array` or `types.map`.\n *\n * @param value\n * @returns true if the value is a state tree node.\n */\nfunction isStateTreeNode(value) {\n return !!(value && value.$treenode);\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertIsStateTreeNode(value, argNumber) {\n assertArg(value, isStateTreeNode, \"mobx-state-tree node\", argNumber);\n}\n/**\n * @internal\n * @hidden\n */\nfunction getStateTreeNode(value) {\n if (!isStateTreeNode(value)) {\n // istanbul ignore next\n throw fail(\"Value \" + value + \" is no MST Node\");\n }\n return value.$treenode;\n}\n/**\n * @internal\n * @hidden\n */\nfunction getStateTreeNodeSafe(value) {\n return (value && value.$treenode) || null;\n}\n/**\n * @internal\n * @hidden\n */\nfunction toJSON() {\n return getStateTreeNode(this).snapshot;\n}\nvar doubleDot = function (_) { return \"..\"; };\n/**\n * @internal\n * @hidden\n */\nfunction getRelativePathBetweenNodes(base, target) {\n // PRE condition target is (a child of) base!\n if (base.root !== target.root) {\n throw fail(\"Cannot calculate relative path: objects '\" + base + \"' and '\" + target + \"' are not part of the same object tree\");\n }\n var baseParts = splitJsonPath(base.path);\n var targetParts = splitJsonPath(target.path);\n var common = 0;\n for (; common < baseParts.length; common++) {\n if (baseParts[common] !== targetParts[common])\n break;\n }\n // TODO: assert that no targetParts paths are \"..\", \".\" or \"\"!\n return baseParts.slice(common).map(doubleDot).join(\"/\") + joinJsonPath(targetParts.slice(common));\n}\n/**\n * @internal\n * @hidden\n */\nfunction resolveNodeByPath(base, path, failIfResolveFails) {\n if (failIfResolveFails === void 0) { failIfResolveFails = true; }\n return resolveNodeByPathParts(base, splitJsonPath(path), failIfResolveFails);\n}\n/**\n * @internal\n * @hidden\n */\nfunction resolveNodeByPathParts(base, pathParts, failIfResolveFails) {\n if (failIfResolveFails === void 0) { failIfResolveFails = true; }\n var current = base;\n try {\n for (var i = 0; i < pathParts.length; i++) {\n var part = pathParts[i];\n if (part === \"..\") {\n current = current.parent;\n if (current)\n continue; // not everything has a parent\n }\n else if (part === \".\") {\n continue;\n }\n else if (current) {\n if (current instanceof ScalarNode) {\n // check if the value of a scalar resolves to a state tree node (e.g. references)\n // then we can continue resolving...\n var value = current.value;\n if (isStateTreeNode(value)) {\n current = getStateTreeNode(value);\n // fall through\n }\n }\n if (current instanceof ObjectNode) {\n var subType = current.getChildType(part);\n if (subType) {\n current = current.getChildNode(part);\n if (current)\n continue;\n }\n }\n }\n throw fail(\"Could not resolve '\" + part + \"' in path '\" + (joinJsonPath(pathParts.slice(0, i)) || \"/\") + \"' while resolving '\" + joinJsonPath(pathParts) + \"'\");\n }\n }\n catch (e) {\n if (!failIfResolveFails) {\n return undefined;\n }\n throw e;\n }\n return current;\n}\n/**\n * @internal\n * @hidden\n */\nfunction convertChildNodesToArray(childNodes) {\n if (!childNodes)\n return EMPTY_ARRAY;\n var keys = Object.keys(childNodes);\n if (!keys.length)\n return EMPTY_ARRAY;\n var result = new Array(keys.length);\n keys.forEach(function (key, index) {\n result[index] = childNodes[key];\n });\n return result;\n}\n\n// based on: https://github.com/mobxjs/mobx-utils/blob/master/src/async-action.ts\n/*\n All contents of this file are deprecated.\n\n The term `process` has been replaced with `flow` to avoid conflicts with the\n global `process` object.\n\n Refer to `flow.ts` for any further changes to this implementation.\n*/\nvar DEPRECATION_MESSAGE = \"See https://github.com/mobxjs/mobx-state-tree/issues/399 for more information. \" +\n \"Note that the middleware event types starting with `process` now start with `flow`.\";\n/**\n * @hidden\n *\n * @deprecated has been renamed to `flow()`.\n * See https://github.com/mobxjs/mobx-state-tree/issues/399 for more information.\n * Note that the middleware event types starting with `process` now start with `flow`.\n *\n * @returns {Promise}\n */\nfunction process$1(asyncAction) {\n deprecated(\"process\", \"`process()` has been renamed to `flow()`. \" + DEPRECATION_MESSAGE);\n return flow(asyncAction);\n}\n\nvar plainObjectString = Object.toString();\n/**\n * @internal\n * @hidden\n */\nvar EMPTY_ARRAY = Object.freeze([]);\n/**\n * @internal\n * @hidden\n */\nvar EMPTY_OBJECT = Object.freeze({});\n/**\n * @internal\n * @hidden\n */\nvar mobxShallow = _getGlobalState().useProxies\n ? { deep: false }\n : { deep: false, proxy: false };\nObject.freeze(mobxShallow);\n/**\n * @internal\n * @hidden\n */\nfunction fail(message) {\n if (message === void 0) { message = \"Illegal state\"; }\n return new Error(\"[mobx-state-tree] \" + message);\n}\n/**\n * @internal\n * @hidden\n */\nfunction identity(_) {\n return _;\n}\n/**\n * @internal\n * @hidden\n */\nvar isInteger = Number.isInteger;\n/**\n * @internal\n * @hidden\n */\nfunction isFloat(val) {\n return Number(val) === val && val % 1 !== 0;\n}\n/**\n * @internal\n * @hidden\n */\nfunction isFinite(val) {\n return Number.isFinite(val);\n}\n/**\n * @internal\n * @hidden\n */\nfunction isArray(val) {\n return Array.isArray(val) || isObservableArray(val);\n}\n/**\n * @internal\n * @hidden\n */\nfunction asArray(val) {\n if (!val)\n return EMPTY_ARRAY;\n if (isArray(val))\n return val;\n return [val];\n}\n/**\n * @internal\n * @hidden\n */\nfunction extend(a) {\n var b = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n b[_i - 1] = arguments[_i];\n }\n for (var i = 0; i < b.length; i++) {\n var current = b[i];\n for (var key in current)\n a[key] = current[key];\n }\n return a;\n}\n/**\n * @internal\n * @hidden\n */\nfunction isPlainObject(value) {\n var _a;\n if (value === null || typeof value !== \"object\")\n return false;\n var proto = Object.getPrototypeOf(value);\n if (proto == null)\n return true;\n return ((_a = proto.constructor) === null || _a === void 0 ? void 0 : _a.toString()) === plainObjectString;\n}\n/**\n * @internal\n * @hidden\n */\nfunction isMutable(value) {\n return (value !== null &&\n typeof value === \"object\" &&\n !(value instanceof Date) &&\n !(value instanceof RegExp));\n}\n/**\n * @internal\n * @hidden\n */\nfunction isPrimitive(value, includeDate) {\n if (includeDate === void 0) { includeDate = true; }\n return (value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n (includeDate && value instanceof Date));\n}\n/**\n * @internal\n * @hidden\n * Freeze a value and return it (if not in production)\n */\nfunction freeze(value) {\n if (!devMode())\n return value;\n return isPrimitive(value) || isObservableArray(value) ? value : Object.freeze(value);\n}\n/**\n * @internal\n * @hidden\n * Recursively freeze a value (if not in production)\n */\nfunction deepFreeze(value) {\n if (!devMode())\n return value;\n freeze(value);\n if (isPlainObject(value)) {\n Object.keys(value).forEach(function (propKey) {\n if (!isPrimitive(value[propKey]) && !Object.isFrozen(value[propKey])) {\n deepFreeze(value[propKey]);\n }\n });\n }\n return value;\n}\n/**\n * @internal\n * @hidden\n */\nfunction isSerializable(value) {\n return typeof value !== \"function\";\n}\n/**\n * @internal\n * @hidden\n */\nfunction defineProperty(object, key, descriptor) {\n isObservableObject(object)\n ? defineProperty$1(object, key, descriptor)\n : Object.defineProperty(object, key, descriptor);\n}\n/**\n * @internal\n * @hidden\n */\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\n/**\n * @internal\n * @hidden\n */\nfunction addHiddenWritableProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\n/**\n * @internal\n * @hidden\n */\nvar EventHandler = /** @class */ (function () {\n function EventHandler() {\n Object.defineProperty(this, \"handlers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n }\n Object.defineProperty(EventHandler.prototype, \"hasSubscribers\", {\n get: function () {\n return this.handlers.length > 0;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(EventHandler.prototype, \"register\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn, atTheBeginning) {\n var _this = this;\n if (atTheBeginning === void 0) { atTheBeginning = false; }\n if (atTheBeginning) {\n this.handlers.unshift(fn);\n }\n else {\n this.handlers.push(fn);\n }\n return function () {\n _this.unregister(fn);\n };\n }\n });\n Object.defineProperty(EventHandler.prototype, \"has\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n return this.handlers.indexOf(fn) >= 0;\n }\n });\n Object.defineProperty(EventHandler.prototype, \"unregister\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n var index = this.handlers.indexOf(fn);\n if (index >= 0) {\n this.handlers.splice(index, 1);\n }\n }\n });\n Object.defineProperty(EventHandler.prototype, \"clear\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.handlers.length = 0;\n }\n });\n Object.defineProperty(EventHandler.prototype, \"emit\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n // make a copy just in case it changes\n var handlers = this.handlers.slice();\n handlers.forEach(function (f) { return f.apply(void 0, __spread(args)); });\n }\n });\n return EventHandler;\n}());\n/**\n * @internal\n * @hidden\n */\nvar EventHandlers = /** @class */ (function () {\n function EventHandlers() {\n Object.defineProperty(this, \"eventHandlers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n Object.defineProperty(EventHandlers.prototype, \"hasSubscribers\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event) {\n var handler = this.eventHandlers && this.eventHandlers[event];\n return !!handler && handler.hasSubscribers;\n }\n });\n Object.defineProperty(EventHandlers.prototype, \"register\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event, fn, atTheBeginning) {\n if (atTheBeginning === void 0) { atTheBeginning = false; }\n if (!this.eventHandlers) {\n this.eventHandlers = {};\n }\n var handler = this.eventHandlers[event];\n if (!handler) {\n handler = this.eventHandlers[event] = new EventHandler();\n }\n return handler.register(fn, atTheBeginning);\n }\n });\n Object.defineProperty(EventHandlers.prototype, \"has\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event, fn) {\n var handler = this.eventHandlers && this.eventHandlers[event];\n return !!handler && handler.has(fn);\n }\n });\n Object.defineProperty(EventHandlers.prototype, \"unregister\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event, fn) {\n var handler = this.eventHandlers && this.eventHandlers[event];\n if (handler) {\n handler.unregister(fn);\n }\n }\n });\n Object.defineProperty(EventHandlers.prototype, \"clear\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event) {\n if (this.eventHandlers) {\n delete this.eventHandlers[event];\n }\n }\n });\n Object.defineProperty(EventHandlers.prototype, \"clearAll\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.eventHandlers = undefined;\n }\n });\n Object.defineProperty(EventHandlers.prototype, \"emit\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (event) {\n var _a;\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var handler = this.eventHandlers && this.eventHandlers[event];\n if (handler) {\n (_a = handler).emit.apply(_a, __spread(args));\n }\n }\n });\n return EventHandlers;\n}());\n/**\n * @internal\n * @hidden\n */\nfunction argsToArray(args) {\n var res = new Array(args.length);\n for (var i = 0; i < args.length; i++)\n res[i] = args[i];\n return res;\n}\n/**\n * @internal\n * @hidden\n */\nfunction stringStartsWith(str, beginning) {\n return str.indexOf(beginning) === 0;\n}\n/**\n * @internal\n * @hidden\n */\nvar deprecated = function (id, message) {\n // skip if running production\n if (!devMode())\n return;\n // warn if hasn't been warned before\n if (deprecated.ids && !deprecated.ids.hasOwnProperty(id)) {\n warnError(\"Deprecation warning: \" + message);\n }\n // mark as warned to avoid duplicate warn message\n if (deprecated.ids)\n deprecated.ids[id] = true;\n};\ndeprecated.ids = {};\n/**\n * @internal\n * @hidden\n */\nfunction warnError(msg) {\n console.warn(new Error(\"[mobx-state-tree] \" + msg));\n}\n/**\n * @internal\n * @hidden\n */\nfunction isTypeCheckingEnabled() {\n return (devMode() ||\n (typeof process !== \"undefined\" && process.env && process.env.ENABLE_TYPE_CHECK === \"true\"));\n}\n/**\n * @internal\n * @hidden\n */\nfunction devMode() {\n return process.env.NODE_ENV !== \"production\";\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertArg(value, fn, typeName, argNumber) {\n if (devMode()) {\n if (!fn(value)) {\n // istanbul ignore next\n throw fail(\"expected \" + typeName + \" as argument \" + asArray(argNumber).join(\" or \") + \", got \" + value + \" instead\");\n }\n }\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertIsFunction(value, argNumber) {\n assertArg(value, function (fn) { return typeof fn === \"function\"; }, \"function\", argNumber);\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertIsNumber(value, argNumber, min, max) {\n assertArg(value, function (n) { return typeof n === \"number\"; }, \"number\", argNumber);\n if (min !== undefined) {\n assertArg(value, function (n) { return n >= min; }, \"number greater than \" + min, argNumber);\n }\n if (max !== undefined) {\n assertArg(value, function (n) { return n <= max; }, \"number lesser than \" + max, argNumber);\n }\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertIsString(value, argNumber, canBeEmpty) {\n if (canBeEmpty === void 0) { canBeEmpty = true; }\n assertArg(value, function (s) { return typeof s === \"string\"; }, \"string\", argNumber);\n if (!canBeEmpty) {\n assertArg(value, function (s) { return s !== \"\"; }, \"not empty string\", argNumber);\n }\n}\n/**\n * @internal\n * @hidden\n */\nfunction setImmediateWithFallback(fn) {\n if (typeof queueMicrotask === \"function\") {\n queueMicrotask(fn);\n }\n else if (typeof setImmediate === \"function\") {\n setImmediate(fn);\n }\n else {\n setTimeout(fn, 1);\n }\n}\n\n/**\n * See [asynchronous actions](concepts/async-actions.md).\n *\n * @returns The flow as a promise.\n */\nfunction flow(generator) {\n return createFlowSpawner(generator.name, generator);\n}\n/**\n * @deprecated Not needed since TS3.6.\n * Used for TypeScript to make flows that return a promise return the actual promise result.\n *\n * @param val\n * @returns\n */\nfunction castFlowReturn(val) {\n return val;\n}\n/**\n * @experimental\n * experimental api - might change on minor/patch releases\n *\n * Convert a promise-returning function to a generator-returning one.\n * This is intended to allow for usage of `yield*` in async actions to\n * retain the promise return type.\n *\n * Example:\n * ```ts\n * function getDataAsync(input: string): Promise { ... }\n * const getDataGen = toGeneratorFunction(getDataAsync);\n *\n * const someModel.actions(self => ({\n * someAction: flow(function*() {\n * // value is typed as number\n * const value = yield* getDataGen(\"input value\");\n * ...\n * })\n * }))\n * ```\n */\nfunction toGeneratorFunction(p) {\n return function () {\n var _i;\n var args = [];\n for (_i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, p.apply(void 0, __spread(args))];\n case 1: return [2 /*return*/, (_a.sent())];\n }\n });\n };\n}\n/**\n * @experimental\n * experimental api - might change on minor/patch releases\n *\n * Convert a promise to a generator yielding that promise\n * This is intended to allow for usage of `yield*` in async actions to\n * retain the promise return type.\n *\n * Example:\n * ```ts\n * function getDataAsync(input: string): Promise { ... }\n *\n * const someModel.actions(self => ({\n * someAction: flow(function*() {\n * // value is typed as number\n * const value = yield* toGenerator(getDataAsync(\"input value\"));\n * ...\n * })\n * }))\n * ```\n */\nfunction toGenerator(p) {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, p];\n case 1: return [2 /*return*/, (_a.sent())];\n }\n });\n}\n/**\n * @internal\n * @hidden\n */\nfunction createFlowSpawner(name, generator) {\n var spawner = function flowSpawner() {\n // Implementation based on https://github.com/tj/co/blob/master/index.js\n var runId = getNextActionId();\n var parentContext = getCurrentActionContext();\n if (!parentContext) {\n throw fail(\"a mst flow must always have a parent context\");\n }\n var parentActionContext = getParentActionContext(parentContext);\n if (!parentActionContext) {\n throw fail(\"a mst flow must always have a parent action context\");\n }\n var contextBase = {\n name: name,\n id: runId,\n tree: parentContext.tree,\n context: parentContext.context,\n parentId: parentContext.id,\n allParentIds: __spread(parentContext.allParentIds, [parentContext.id]),\n rootId: parentContext.rootId,\n parentEvent: parentContext,\n parentActionEvent: parentActionContext\n };\n var args = arguments;\n function wrap(fn, type, arg) {\n fn.$mst_middleware = spawner.$mst_middleware; // pick up any middleware attached to the flow\n return runWithActionContext(__assign(__assign({}, contextBase), { type: type, args: [arg] }), fn);\n }\n return new Promise(function (resolve, reject) {\n var gen;\n var init = function asyncActionInit() {\n gen = generator.apply(null, arguments);\n onFulfilled(undefined); // kick off the flow\n };\n init.$mst_middleware = spawner.$mst_middleware;\n runWithActionContext(__assign(__assign({}, contextBase), { type: \"flow_spawn\", args: argsToArray(args) }), init);\n function onFulfilled(res) {\n var ret;\n try {\n // prettier-ignore\n var cancelError = wrap(function (r) { ret = gen.next(r); }, \"flow_resume\", res);\n if (cancelError instanceof Error) {\n ret = gen.throw(cancelError);\n }\n }\n catch (e) {\n // prettier-ignore\n setImmediateWithFallback(function () {\n wrap(function (r) { reject(e); }, \"flow_throw\", e);\n });\n return;\n }\n next(ret);\n return;\n }\n function onRejected(err) {\n var ret;\n try {\n // prettier-ignore\n wrap(function (r) { ret = gen.throw(r); }, \"flow_resume_error\", err); // or yieldError?\n }\n catch (e) {\n // prettier-ignore\n setImmediateWithFallback(function () {\n wrap(function (r) { reject(e); }, \"flow_throw\", e);\n });\n return;\n }\n next(ret);\n }\n function next(ret) {\n if (ret.done) {\n // prettier-ignore\n setImmediateWithFallback(function () {\n wrap(function (r) { resolve(r); }, \"flow_return\", ret.value);\n });\n return;\n }\n // TODO: support more type of values? See https://github.com/tj/co/blob/249bbdc72da24ae44076afd716349d2089b31c4c/index.js#L100\n if (!ret.value || typeof ret.value.then !== \"function\") {\n // istanbul ignore next\n throw fail(\"Only promises can be yielded to `async`, got: \" + ret);\n }\n return ret.value.then(onFulfilled, onRejected);\n }\n });\n };\n spawner._isFlowAction = true;\n return spawner;\n}\n\n/**\n * @internal\n * @hidden\n */\nfunction splitPatch(patch) {\n if (!(\"oldValue\" in patch))\n throw fail(\"Patches without `oldValue` field cannot be inversed\");\n return [stripPatch(patch), invertPatch(patch)];\n}\n/**\n * @internal\n * @hidden\n */\nfunction stripPatch(patch) {\n // strips `oldvalue` information from the patch, so that it becomes a patch conform the json-patch spec\n // this removes the ability to undo the patch\n switch (patch.op) {\n case \"add\":\n return { op: \"add\", path: patch.path, value: patch.value };\n case \"remove\":\n return { op: \"remove\", path: patch.path };\n case \"replace\":\n return { op: \"replace\", path: patch.path, value: patch.value };\n }\n}\nfunction invertPatch(patch) {\n switch (patch.op) {\n case \"add\":\n return {\n op: \"remove\",\n path: patch.path\n };\n case \"remove\":\n return {\n op: \"add\",\n path: patch.path,\n value: patch.oldValue\n };\n case \"replace\":\n return {\n op: \"replace\",\n path: patch.path,\n value: patch.oldValue\n };\n }\n}\n/**\n * Simple simple check to check it is a number.\n */\nfunction isNumber(x) {\n return typeof x === \"number\";\n}\n/**\n * Escape slashes and backslashes.\n *\n * http://tools.ietf.org/html/rfc6901\n */\nfunction escapeJsonPath(path) {\n if (isNumber(path) === true) {\n return \"\" + path;\n }\n if (path.indexOf(\"/\") === -1 && path.indexOf(\"~\") === -1)\n return path;\n return path.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n/**\n * Unescape slashes and backslashes.\n */\nfunction unescapeJsonPath(path) {\n return path.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n/**\n * Generates a json-path compliant json path from path parts.\n *\n * @param path\n * @returns\n */\nfunction joinJsonPath(path) {\n // `/` refers to property with an empty name, while `` refers to root itself!\n if (path.length === 0)\n return \"\";\n var getPathStr = function (p) { return p.map(escapeJsonPath).join(\"/\"); };\n if (path[0] === \".\" || path[0] === \"..\") {\n // relative\n return getPathStr(path);\n }\n else {\n // absolute\n return \"/\" + getPathStr(path);\n }\n}\n/**\n * Splits and decodes a json path into several parts.\n *\n * @param path\n * @returns\n */\nfunction splitJsonPath(path) {\n // `/` refers to property with an empty name, while `` refers to root itself!\n var parts = path.split(\"/\").map(unescapeJsonPath);\n var valid = path === \"\" ||\n path === \".\" ||\n path === \"..\" ||\n stringStartsWith(path, \"/\") ||\n stringStartsWith(path, \"./\") ||\n stringStartsWith(path, \"../\");\n if (!valid) {\n throw fail(\"a json path must be either rooted, empty or relative, but got '\" + path + \"'\");\n }\n // '/a/b/c' -> [\"a\", \"b\", \"c\"]\n // '../../b/c' -> [\"..\", \"..\", \"b\", \"c\"]\n // '' -> []\n // '/' -> ['']\n // './a' -> [\".\", \"a\"]\n // /./a' -> [\".\", \"a\"] equivalent to './a'\n if (parts[0] === \"\") {\n parts.shift();\n }\n return parts;\n}\n\n/** @hidden */\nvar $preProcessorFailed = Symbol(\"$preProcessorFailed\");\nvar SnapshotProcessor = /** @class */ (function (_super) {\n __extends(SnapshotProcessor, _super);\n function SnapshotProcessor(_subtype, _processors, name) {\n var _this = _super.call(this, name || _subtype.name) || this;\n Object.defineProperty(_this, \"_subtype\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _subtype\n });\n Object.defineProperty(_this, \"_processors\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _processors\n });\n return _this;\n }\n Object.defineProperty(SnapshotProcessor.prototype, \"flags\", {\n get: function () {\n return this._subtype.flags | TypeFlags.SnapshotProcessor;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return \"snapshotProcessor(\" + this._subtype.describe() + \")\";\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"preProcessSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (sn) {\n if (this._processors.preProcessor) {\n return this._processors.preProcessor.call(null, sn);\n }\n return sn;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"preProcessSnapshotSafe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (sn) {\n try {\n return this.preProcessSnapshot(sn);\n }\n catch (e) {\n return $preProcessorFailed;\n }\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"postProcessSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (sn, node) {\n if (this._processors.postProcessor) {\n return this._processors.postProcessor.call(null, sn, node.storedValue);\n }\n return sn;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"_fixNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n var _this = this;\n // the node has to use these methods rather than the original type ones\n proxyNodeTypeMethods(node.type, this, \"create\");\n if (node instanceof ObjectNode) {\n node.hasSnapshotPostProcessor = !!this._processors.postProcessor;\n }\n var oldGetSnapshot = node.getSnapshot;\n node.getSnapshot = function () { return _this.postProcessSnapshot(oldGetSnapshot.call(node), node); };\n if (!isUnionType(this._subtype)) {\n node.getReconciliationType = function () {\n return _this;\n };\n }\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n var processedInitialValue = isStateTreeNode(initialValue)\n ? initialValue\n : this.preProcessSnapshot(initialValue);\n var node = this._subtype.instantiate(parent, subpath, environment, processedInitialValue);\n this._fixNode(node);\n return node;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n var node = this._subtype.reconcile(current, isStateTreeNode(newValue) ? newValue : this.preProcessSnapshot(newValue), parent, subpath);\n if (node !== current) {\n this._fixNode(node);\n }\n return node;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, applyPostProcess) {\n if (applyPostProcess === void 0) { applyPostProcess = true; }\n var sn = this._subtype.getSnapshot(node);\n return applyPostProcess ? this.postProcessSnapshot(sn, node) : sn;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var processedSn = this.preProcessSnapshotSafe(value);\n if (processedSn === $preProcessorFailed) {\n return typeCheckFailure(context, value, \"Failed to preprocess value\");\n }\n return this._subtype.validate(processedSn, context);\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._subtype;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"is\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (thing) {\n var value = isType(thing)\n ? this._subtype\n : isStateTreeNode(thing)\n ? getSnapshot(thing, false)\n : this.preProcessSnapshotSafe(thing);\n if (value === $preProcessorFailed) {\n return false;\n }\n return this._subtype.validate(value, [{ path: \"\", type: this._subtype }]).length === 0;\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n return this._subtype.isAssignableFrom(type);\n }\n });\n Object.defineProperty(SnapshotProcessor.prototype, \"isMatchingSnapshotId\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, snapshot) {\n if (!(this._subtype instanceof ComplexType)) {\n return false;\n }\n var processedSn = this.preProcessSnapshot(snapshot);\n return this._subtype.isMatchingSnapshotId(current, processedSn);\n }\n });\n return SnapshotProcessor;\n}(BaseType));\nfunction proxyNodeTypeMethods(nodeType, snapshotProcessorType) {\n var e_1, _a;\n var methods = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n methods[_i - 2] = arguments[_i];\n }\n try {\n for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) {\n var method = methods_1_1.value;\n nodeType[method] = snapshotProcessorType[method].bind(snapshotProcessorType);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (methods_1_1 && !methods_1_1.done && (_a = methods_1.return)) _a.call(methods_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n}\n/**\n * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type.\n *\n * Example:\n * ```ts\n * const Todo1 = types.model({ text: types.string })\n * // in the backend the text type must be null when empty\n * interface BackendTodo {\n * text: string | null\n * }\n *\n * const Todo2 = types.snapshotProcessor(Todo1, {\n * // from snapshot to instance\n * preProcessor(snapshot: BackendTodo) {\n * return {\n * text: sn.text || \"\";\n * }\n * },\n *\n * // from instance to snapshot\n * postProcessor(snapshot, node): BackendTodo {\n * return {\n * text: !sn.text ? null : sn.text\n * }\n * }\n * })\n * ```\n *\n * @param type Type to run the processors over.\n * @param processors Processors to run.\n * @param name Type name, or undefined to inherit the inner type one.\n * @returns\n */\nfunction snapshotProcessor(type, processors, name) {\n assertIsType(type, 1);\n if (devMode()) {\n if (processors.postProcessor && typeof processors.postProcessor !== \"function\") {\n // istanbul ignore next\n throw fail(\"postSnapshotProcessor must be a function\");\n }\n if (processors.preProcessor && typeof processors.preProcessor !== \"function\") {\n // istanbul ignore next\n throw fail(\"preSnapshotProcessor must be a function\");\n }\n }\n return new SnapshotProcessor(type, processors, name);\n}\n\nvar needsIdentifierError = \"Map.put can only be used to store complex values that have an identifier type attribute\";\nfunction tryCollectModelTypes(type, modelTypes) {\n var e_1, _a;\n var subtypes = type.getSubTypes();\n if (subtypes === cannotDetermineSubtype) {\n return false;\n }\n if (subtypes) {\n var subtypesArray = asArray(subtypes);\n try {\n for (var subtypesArray_1 = __values(subtypesArray), subtypesArray_1_1 = subtypesArray_1.next(); !subtypesArray_1_1.done; subtypesArray_1_1 = subtypesArray_1.next()) {\n var subtype = subtypesArray_1_1.value;\n if (!tryCollectModelTypes(subtype, modelTypes))\n return false;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (subtypesArray_1_1 && !subtypesArray_1_1.done && (_a = subtypesArray_1.return)) _a.call(subtypesArray_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n if (type instanceof ModelType) {\n modelTypes.push(type);\n }\n return true;\n}\n/**\n * @internal\n * @hidden\n */\nvar MapIdentifierMode;\n(function (MapIdentifierMode) {\n MapIdentifierMode[MapIdentifierMode[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n MapIdentifierMode[MapIdentifierMode[\"YES\"] = 1] = \"YES\";\n MapIdentifierMode[MapIdentifierMode[\"NO\"] = 2] = \"NO\";\n})(MapIdentifierMode || (MapIdentifierMode = {}));\nvar MSTMap = /** @class */ (function (_super) {\n __extends(MSTMap, _super);\n function MSTMap(initialData, name) {\n return _super.call(this, initialData, observable.ref.enhancer, name) || this;\n }\n Object.defineProperty(MSTMap.prototype, \"get\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (key) {\n // maybe this is over-enthousiastic? normalize numeric keys to strings\n return _super.prototype.get.call(this, \"\" + key);\n }\n });\n Object.defineProperty(MSTMap.prototype, \"has\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (key) {\n return _super.prototype.has.call(this, \"\" + key);\n }\n });\n Object.defineProperty(MSTMap.prototype, \"delete\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (key) {\n return _super.prototype.delete.call(this, \"\" + key);\n }\n });\n Object.defineProperty(MSTMap.prototype, \"set\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (key, value) {\n return _super.prototype.set.call(this, \"\" + key, value);\n }\n });\n Object.defineProperty(MSTMap.prototype, \"put\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value) {\n if (!value)\n throw fail(\"Map.put cannot be used to set empty values\");\n if (isStateTreeNode(value)) {\n var node = getStateTreeNode(value);\n if (devMode()) {\n if (!node.identifierAttribute) {\n throw fail(needsIdentifierError);\n }\n }\n if (node.identifier === null) {\n throw fail(needsIdentifierError);\n }\n this.set(node.identifier, value);\n return value;\n }\n else if (!isMutable(value)) {\n throw fail(\"Map.put can only be used to store complex values\");\n }\n else {\n var mapNode = getStateTreeNode(this);\n var mapType = mapNode.type;\n if (mapType.identifierMode !== MapIdentifierMode.YES) {\n throw fail(needsIdentifierError);\n }\n var idAttr = mapType.mapIdentifierAttribute;\n var id = value[idAttr];\n if (!isValidIdentifier(id)) {\n // try again but this time after creating a node for the value\n // since it might be an optional identifier\n var newNode = this.put(mapType.getChildType().create(value, mapNode.environment));\n return this.put(getSnapshot(newNode));\n }\n var key = normalizeIdentifier(id);\n this.set(key, value);\n return this.get(key);\n }\n }\n });\n return MSTMap;\n}(ObservableMap));\n/**\n * @internal\n * @hidden\n */\nvar MapType = /** @class */ (function (_super) {\n __extends(MapType, _super);\n function MapType(name, _subType, hookInitializers) {\n if (hookInitializers === void 0) { hookInitializers = []; }\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"_subType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _subType\n });\n Object.defineProperty(_this, \"identifierMode\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: MapIdentifierMode.UNKNOWN\n });\n Object.defineProperty(_this, \"mapIdentifierAttribute\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Map\n });\n Object.defineProperty(_this, \"hookInitializers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n _this._determineIdentifierMode();\n _this.hookInitializers = hookInitializers;\n return _this;\n }\n Object.defineProperty(MapType.prototype, \"hooks\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (hooks) {\n var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks];\n return new MapType(this.name, this._subType, hookInitializers);\n }\n });\n Object.defineProperty(MapType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n this._determineIdentifierMode();\n return createObjectNode(this, parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(MapType.prototype, \"_determineIdentifierMode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this.identifierMode !== MapIdentifierMode.UNKNOWN) {\n return;\n }\n var modelTypes = [];\n if (tryCollectModelTypes(this._subType, modelTypes)) {\n var identifierAttribute = modelTypes.reduce(function (current, type) {\n if (!type.identifierAttribute)\n return current;\n if (current && current !== type.identifierAttribute) {\n throw fail(\"The objects in a map should all have the same identifier attribute, expected '\" + current + \"', but child of type '\" + type.name + \"' declared attribute '\" + type.identifierAttribute + \"' as identifier\");\n }\n return type.identifierAttribute;\n }, undefined);\n if (identifierAttribute) {\n this.identifierMode = MapIdentifierMode.YES;\n this.mapIdentifierAttribute = identifierAttribute;\n }\n else {\n this.identifierMode = MapIdentifierMode.NO;\n }\n }\n }\n });\n Object.defineProperty(MapType.prototype, \"initializeChildNodes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (objNode, initialSnapshot) {\n if (initialSnapshot === void 0) { initialSnapshot = {}; }\n var subType = objNode.type._subType;\n var result = {};\n Object.keys(initialSnapshot).forEach(function (name) {\n result[name] = subType.instantiate(objNode, name, undefined, initialSnapshot[name]);\n });\n return result;\n }\n });\n Object.defineProperty(MapType.prototype, \"createNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNodes) {\n return new MSTMap(childNodes, this.name);\n }\n });\n Object.defineProperty(MapType.prototype, \"finalizeNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, instance) {\n _interceptReads(instance, node.unbox);\n var type = node.type;\n type.hookInitializers.forEach(function (initializer) {\n var hooks = initializer(instance);\n Object.keys(hooks).forEach(function (name) {\n var hook = hooks[name];\n var actionInvoker = createActionInvoker(instance, name, hook);\n (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(instance, name, actionInvoker);\n });\n });\n intercept(instance, this.willChange);\n observe(instance, this.didChange);\n }\n });\n Object.defineProperty(MapType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.name;\n }\n });\n Object.defineProperty(MapType.prototype, \"getChildren\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n // return (node.storedValue as ObservableMap).values()\n return values(node.storedValue);\n }\n });\n Object.defineProperty(MapType.prototype, \"getChildNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, key) {\n var childNode = node.storedValue.get(\"\" + key);\n if (!childNode)\n throw fail(\"Not a child \" + key);\n return childNode;\n }\n });\n Object.defineProperty(MapType.prototype, \"willChange\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (change) {\n var node = getStateTreeNode(change.object);\n var key = change.name;\n node.assertWritable({ subpath: key });\n var mapType = node.type;\n var subType = mapType._subType;\n switch (change.type) {\n case \"update\":\n {\n var newValue = change.newValue;\n var oldValue = change.object.get(key);\n if (newValue === oldValue)\n return null;\n typecheckInternal(subType, newValue);\n change.newValue = subType.reconcile(node.getChildNode(key), change.newValue, node, key);\n mapType.processIdentifier(key, change.newValue);\n }\n break;\n case \"add\":\n {\n typecheckInternal(subType, change.newValue);\n change.newValue = subType.instantiate(node, key, undefined, change.newValue);\n mapType.processIdentifier(key, change.newValue);\n }\n break;\n }\n return change;\n }\n });\n Object.defineProperty(MapType.prototype, \"processIdentifier\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (expected, node) {\n if (this.identifierMode === MapIdentifierMode.YES && node instanceof ObjectNode) {\n var identifier = node.identifier;\n if (identifier !== expected)\n throw fail(\"A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '\" + identifier + \"', but expected: '\" + expected + \"'\");\n }\n }\n });\n Object.defineProperty(MapType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n var res = {};\n node.getChildren().forEach(function (childNode) {\n res[childNode.subpath] = childNode.snapshot;\n });\n return res;\n }\n });\n Object.defineProperty(MapType.prototype, \"processInitialSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNodes) {\n var processed = {};\n Object.keys(childNodes).forEach(function (key) {\n processed[key] = childNodes[key].getSnapshot();\n });\n return processed;\n }\n });\n Object.defineProperty(MapType.prototype, \"didChange\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (change) {\n var node = getStateTreeNode(change.object);\n switch (change.type) {\n case \"update\":\n return void node.emitPatch({\n op: \"replace\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: change.oldValue ? change.oldValue.snapshot : undefined\n }, node);\n case \"add\":\n return void node.emitPatch({\n op: \"add\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: undefined\n }, node);\n case \"delete\":\n // a node got deleted, get the old snapshot and make the node die\n var oldSnapshot = change.oldValue.snapshot;\n change.oldValue.die();\n // emit the patch\n return void node.emitPatch({\n op: \"remove\",\n path: escapeJsonPath(change.name),\n oldValue: oldSnapshot\n }, node);\n }\n }\n });\n Object.defineProperty(MapType.prototype, \"applyPatchLocally\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, subpath, patch) {\n var target = node.storedValue;\n switch (patch.op) {\n case \"add\":\n case \"replace\":\n target.set(subpath, patch.value);\n break;\n case \"remove\":\n target.delete(subpath);\n break;\n }\n }\n });\n Object.defineProperty(MapType.prototype, \"applySnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, snapshot) {\n typecheckInternal(this, snapshot);\n var target = node.storedValue;\n var currentKeys = {};\n Array.from(target.keys()).forEach(function (key) {\n currentKeys[key] = false;\n });\n if (snapshot) {\n // Don't use target.replace, as it will throw away all existing items first\n for (var key in snapshot) {\n target.set(key, snapshot[key]);\n currentKeys[\"\" + key] = true;\n }\n }\n Object.keys(currentKeys).forEach(function (key) {\n if (currentKeys[key] === false)\n target.delete(key);\n });\n }\n });\n Object.defineProperty(MapType.prototype, \"getChildType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._subType;\n }\n });\n Object.defineProperty(MapType.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var _this = this;\n if (!isPlainObject(value)) {\n return typeCheckFailure(context, value, \"Value is not a plain object\");\n }\n return flattenTypeErrors(Object.keys(value).map(function (path) {\n return _this._subType.validate(value[path], getContextForPath(context, path, _this._subType));\n }));\n }\n });\n Object.defineProperty(MapType.prototype, \"getDefaultSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return EMPTY_OBJECT;\n }\n });\n Object.defineProperty(MapType.prototype, \"removeChild\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, subpath) {\n node.storedValue.delete(subpath);\n }\n });\n return MapType;\n}(ComplexType));\nMapType.prototype.applySnapshot = action(MapType.prototype.applySnapshot);\n/**\n * `types.map` - Creates a key based collection type who's children are all of a uniform declared type.\n * If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map.\n *\n * This type will always produce [observable maps](https://mobx.js.org/api.html#observablemap)\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * id: types.identifier,\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.map(Todo)\n * })\n *\n * const s = TodoStore.create({ todos: {} })\n * unprotect(s)\n * s.todos.set(17, { task: \"Grab coffee\", id: 17 })\n * s.todos.put({ task: \"Grab cookie\", id: 18 }) // put will infer key from the identifier\n * console.log(s.todos.get(17).task) // prints: \"Grab coffee\"\n * ```\n *\n * @param subtype\n * @returns\n */\nfunction map(subtype) {\n return new MapType(\"Map\", subtype);\n}\n/**\n * Returns if a given value represents a map type.\n *\n * @param type\n * @returns `true` if it is a map type.\n */\nfunction isMapType(type) {\n return isType(type) && (type.flags & TypeFlags.Map) > 0;\n}\n\n/**\n * @internal\n * @hidden\n */\nvar ArrayType = /** @class */ (function (_super) {\n __extends(ArrayType, _super);\n function ArrayType(name, _subType, hookInitializers) {\n if (hookInitializers === void 0) { hookInitializers = []; }\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"_subType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _subType\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Array\n });\n Object.defineProperty(_this, \"hookInitializers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n _this.hookInitializers = hookInitializers;\n return _this;\n }\n Object.defineProperty(ArrayType.prototype, \"hooks\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (hooks) {\n var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks];\n return new ArrayType(this.name, this._subType, hookInitializers);\n }\n });\n Object.defineProperty(ArrayType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n return createObjectNode(this, parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(ArrayType.prototype, \"initializeChildNodes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (objNode, snapshot) {\n if (snapshot === void 0) { snapshot = []; }\n var subType = objNode.type._subType;\n var result = {};\n snapshot.forEach(function (item, index) {\n var subpath = \"\" + index;\n result[subpath] = subType.instantiate(objNode, subpath, undefined, item);\n });\n return result;\n }\n });\n Object.defineProperty(ArrayType.prototype, \"createNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNodes) {\n var options = __assign(__assign({}, mobxShallow), { name: this.name });\n return observable.array(convertChildNodesToArray(childNodes), options);\n }\n });\n Object.defineProperty(ArrayType.prototype, \"finalizeNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, instance) {\n _getAdministration(instance).dehancer = node.unbox;\n var type = node.type;\n type.hookInitializers.forEach(function (initializer) {\n var hooks = initializer(instance);\n Object.keys(hooks).forEach(function (name) {\n var hook = hooks[name];\n var actionInvoker = createActionInvoker(instance, name, hook);\n (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(instance, name, actionInvoker);\n });\n });\n intercept(instance, this.willChange);\n observe(instance, this.didChange);\n }\n });\n Object.defineProperty(ArrayType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.name;\n }\n });\n Object.defineProperty(ArrayType.prototype, \"getChildren\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n return node.storedValue.slice();\n }\n });\n Object.defineProperty(ArrayType.prototype, \"getChildNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, key) {\n var index = Number(key);\n if (index < node.storedValue.length)\n return node.storedValue[index];\n throw fail(\"Not a child: \" + key);\n }\n });\n Object.defineProperty(ArrayType.prototype, \"willChange\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (change) {\n var node = getStateTreeNode(change.object);\n node.assertWritable({ subpath: \"\" + change.index });\n var subType = node.type._subType;\n var childNodes = node.getChildren();\n switch (change.type) {\n case \"update\":\n {\n if (change.newValue === change.object[change.index])\n return null;\n var updatedNodes = reconcileArrayChildren(node, subType, [childNodes[change.index]], [change.newValue], [change.index]);\n if (!updatedNodes) {\n return null;\n }\n change.newValue = updatedNodes[0];\n }\n break;\n case \"splice\":\n {\n var index_1 = change.index, removedCount = change.removedCount, added = change.added;\n var addedNodes = reconcileArrayChildren(node, subType, childNodes.slice(index_1, index_1 + removedCount), added, added.map(function (_, i) { return index_1 + i; }));\n if (!addedNodes) {\n return null;\n }\n change.added = addedNodes;\n // update paths of remaining items\n for (var i = index_1 + removedCount; i < childNodes.length; i++) {\n childNodes[i].setParent(node, \"\" + (i + added.length - removedCount));\n }\n }\n break;\n }\n return change;\n }\n });\n Object.defineProperty(ArrayType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n return node.getChildren().map(function (childNode) { return childNode.snapshot; });\n }\n });\n Object.defineProperty(ArrayType.prototype, \"processInitialSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNodes) {\n var processed = [];\n Object.keys(childNodes).forEach(function (key) {\n processed.push(childNodes[key].getSnapshot());\n });\n return processed;\n }\n });\n Object.defineProperty(ArrayType.prototype, \"didChange\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (change) {\n var node = getStateTreeNode(change.object);\n switch (change.type) {\n case \"update\":\n return void node.emitPatch({\n op: \"replace\",\n path: \"\" + change.index,\n value: change.newValue.snapshot,\n oldValue: change.oldValue ? change.oldValue.snapshot : undefined\n }, node);\n case \"splice\":\n for (var i = change.removedCount - 1; i >= 0; i--)\n node.emitPatch({\n op: \"remove\",\n path: \"\" + (change.index + i),\n oldValue: change.removed[i].snapshot\n }, node);\n for (var i = 0; i < change.addedCount; i++)\n node.emitPatch({\n op: \"add\",\n path: \"\" + (change.index + i),\n value: node.getChildNode(\"\" + (change.index + i)).snapshot,\n oldValue: undefined\n }, node);\n return;\n }\n }\n });\n Object.defineProperty(ArrayType.prototype, \"applyPatchLocally\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, subpath, patch) {\n var target = node.storedValue;\n var index = subpath === \"-\" ? target.length : Number(subpath);\n switch (patch.op) {\n case \"replace\":\n target[index] = patch.value;\n break;\n case \"add\":\n target.splice(index, 0, patch.value);\n break;\n case \"remove\":\n target.splice(index, 1);\n break;\n }\n }\n });\n Object.defineProperty(ArrayType.prototype, \"applySnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, snapshot) {\n typecheckInternal(this, snapshot);\n var target = node.storedValue;\n target.replace(snapshot);\n }\n });\n Object.defineProperty(ArrayType.prototype, \"getChildType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._subType;\n }\n });\n Object.defineProperty(ArrayType.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var _this = this;\n if (!isArray(value)) {\n return typeCheckFailure(context, value, \"Value is not an array\");\n }\n return flattenTypeErrors(value.map(function (item, index) {\n return _this._subType.validate(item, getContextForPath(context, \"\" + index, _this._subType));\n }));\n }\n });\n Object.defineProperty(ArrayType.prototype, \"getDefaultSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return EMPTY_ARRAY;\n }\n });\n Object.defineProperty(ArrayType.prototype, \"removeChild\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, subpath) {\n node.storedValue.splice(Number(subpath), 1);\n }\n });\n return ArrayType;\n}(ComplexType));\nArrayType.prototype.applySnapshot = action(ArrayType.prototype.applySnapshot);\n/**\n * `types.array` - Creates an index based collection type who's children are all of a uniform declared type.\n *\n * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray)\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.array(Todo)\n * })\n *\n * const s = TodoStore.create({ todos: [] })\n * unprotect(s) // needed to allow modifying outside of an action\n * s.todos.push({ task: \"Grab coffee\" })\n * console.log(s.todos[0]) // prints: \"Grab coffee\"\n * ```\n *\n * @param subtype\n * @returns\n */\nfunction array(subtype) {\n assertIsType(subtype, 1);\n return new ArrayType(subtype.name + \"[]\", subtype);\n}\nfunction reconcileArrayChildren(parent, childType, oldNodes, newValues, newPaths) {\n var nothingChanged = true;\n for (var i = 0;; i++) {\n var hasNewNode = i <= newValues.length - 1;\n var oldNode = oldNodes[i];\n var newValue = hasNewNode ? newValues[i] : undefined;\n var newPath = \"\" + newPaths[i];\n // for some reason, instead of newValue we got a node, fallback to the storedValue\n // TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681\n if (isNode(newValue))\n newValue = newValue.storedValue;\n if (!oldNode && !hasNewNode) {\n // both are empty, end\n break;\n }\n else if (!hasNewNode) {\n // new one does not exists\n nothingChanged = false;\n oldNodes.splice(i, 1);\n if (oldNode instanceof ObjectNode) {\n // since it is going to be returned by pop/splice/shift better create it before killing it\n // so it doesn't end up in an undead state\n oldNode.createObservableInstanceIfNeeded();\n }\n oldNode.die();\n i--;\n }\n else if (!oldNode) {\n // there is no old node, create it\n // check if already belongs to the same parent. if so, avoid pushing item in. only swapping can occur.\n if (isStateTreeNode(newValue) && getStateTreeNode(newValue).parent === parent) {\n // this node is owned by this parent, but not in the reconcilable set, so it must be double\n 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 '\" + parent.path + \"/\" + newPath + \"', but it lives already at '\" + getStateTreeNode(newValue).path + \"'\");\n }\n nothingChanged = false;\n var newNode = valueAsNode(childType, parent, newPath, newValue);\n oldNodes.splice(i, 0, newNode);\n }\n else if (areSame(oldNode, newValue)) {\n // both are the same, reconcile\n oldNodes[i] = valueAsNode(childType, parent, newPath, newValue, oldNode);\n }\n else {\n // nothing to do, try to reorder\n var oldMatch = undefined;\n // find a possible candidate to reuse\n for (var j = i; j < oldNodes.length; j++) {\n if (areSame(oldNodes[j], newValue)) {\n oldMatch = oldNodes.splice(j, 1)[0];\n break;\n }\n }\n nothingChanged = false;\n var newNode = valueAsNode(childType, parent, newPath, newValue, oldMatch);\n oldNodes.splice(i, 0, newNode);\n }\n }\n return nothingChanged ? null : oldNodes;\n}\n/**\n * Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given.\n */\nfunction valueAsNode(childType, parent, subpath, newValue, oldNode) {\n // ensure the value is valid-ish\n typecheckInternal(childType, newValue);\n function getNewNode() {\n // the new value has a MST node\n if (isStateTreeNode(newValue)) {\n var childNode = getStateTreeNode(newValue);\n childNode.assertAlive(EMPTY_OBJECT);\n // the node lives here\n if (childNode.parent !== null && childNode.parent === parent) {\n childNode.setParent(parent, subpath);\n return childNode;\n }\n }\n // there is old node and new one is a value/snapshot\n if (oldNode) {\n return childType.reconcile(oldNode, newValue, parent, subpath);\n }\n // nothing to do, create from scratch\n return childType.instantiate(parent, subpath, undefined, newValue);\n }\n var newNode = getNewNode();\n if (oldNode && oldNode !== newNode) {\n if (oldNode instanceof ObjectNode) {\n // since it is going to be returned by pop/splice/shift better create it before killing it\n // so it doesn't end up in an undead state\n oldNode.createObservableInstanceIfNeeded();\n }\n oldNode.die();\n }\n return newNode;\n}\n/**\n * Check if a node holds a value.\n */\nfunction areSame(oldNode, newValue) {\n // never consider dead old nodes for reconciliation\n if (!oldNode.isAlive) {\n return false;\n }\n // the new value has the same node\n if (isStateTreeNode(newValue)) {\n var newNode = getStateTreeNode(newValue);\n return newNode.isAlive && newNode === oldNode;\n }\n // the provided value is the snapshot of the old node\n if (oldNode.snapshot === newValue) {\n return true;\n }\n // Non object nodes don't get reconciled\n if (!(oldNode instanceof ObjectNode)) {\n return false;\n }\n var oldNodeType = oldNode.getReconciliationType();\n // new value is a snapshot with the correct identifier\n return (oldNode.identifier !== null &&\n oldNode.identifierAttribute &&\n isPlainObject(newValue) &&\n oldNodeType.is(newValue) &&\n oldNodeType.isMatchingSnapshotId(oldNode, newValue));\n}\n/**\n * Returns if a given value represents an array type.\n *\n * @param type\n * @returns `true` if the type is an array type.\n */\nfunction isArrayType(type) {\n return isType(type) && (type.flags & TypeFlags.Array) > 0;\n}\n\nvar PRE_PROCESS_SNAPSHOT = \"preProcessSnapshot\";\nvar POST_PROCESS_SNAPSHOT = \"postProcessSnapshot\";\nfunction objectTypeToString() {\n return getStateTreeNode(this).toString();\n}\nvar defaultObjectOptions = {\n name: \"AnonymousModel\",\n properties: {},\n initializers: EMPTY_ARRAY\n};\nfunction toPropertiesObject(declaredProps) {\n var keysList = Object.keys(declaredProps);\n var alreadySeenKeys = new Set();\n keysList.forEach(function (key) {\n if (alreadySeenKeys.has(key)) {\n throw fail(key + \" is declared twice in the model. Model should not contain the same keys\");\n }\n alreadySeenKeys.add(key);\n });\n // loop through properties and ensures that all items are types\n return keysList.reduce(function (props, key) {\n // warn if user intended a HOOK\n if (key in Hook) {\n throw fail(\"Hook '\" + key + \"' was defined as property. Hooks should be defined as part of the actions\");\n }\n // the user intended to use a view\n var descriptor = Object.getOwnPropertyDescriptor(declaredProps, key);\n if (\"get\" in descriptor) {\n throw fail(\"Getters are not supported as properties. Please use views instead\");\n }\n // undefined and null are not valid\n var value = descriptor.value;\n if (value === null || value === undefined) {\n 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)`?\");\n }\n // its a primitive, convert to its type\n else if (isPrimitive(value)) {\n props[key] = optional(getPrimitiveFactoryFromValue(value), value);\n }\n // map defaults to empty object automatically for models\n else if (value instanceof MapType) {\n props[key] = optional(value, {});\n }\n else if (value instanceof ArrayType) {\n props[key] = optional(value, []);\n }\n // its already a type\n else if (isType(value)) ;\n // its a function, maybe the user wanted a view?\n else if (devMode() && typeof value === \"function\") {\n throw fail(\"Invalid type definition for property '\" + key + \"', it looks like you passed a function. Did you forget to invoke it, or did you intend to declare a view / action?\");\n }\n // no other complex values\n else if (devMode() && typeof value === \"object\") {\n throw fail(\"Invalid type definition for property '\" + key + \"', it looks like you passed an object. Try passing another model type or a types.frozen.\");\n }\n else {\n throw fail(\"Invalid type definition for property '\" + key + \"', cannot infer a type from a value like '\" + value + \"' (\" + typeof value + \")\");\n }\n return props;\n }, __assign({}, declaredProps));\n}\n/**\n * @internal\n * @hidden\n */\nvar ModelType = /** @class */ (function (_super) {\n __extends(ModelType, _super);\n function ModelType(opts) {\n var _this = _super.call(this, opts.name || defaultObjectOptions.name) || this;\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Object\n });\n /*\n * The original object definition\n */\n Object.defineProperty(_this, \"initializers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"properties\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"preProcessor\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"postProcessor\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"propertyNames\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"named\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (name) {\n return _this.cloneAndEnhance({ name: name });\n }\n });\n Object.defineProperty(_this, \"props\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (properties) {\n return _this.cloneAndEnhance({ properties: properties });\n }\n });\n Object.defineProperty(_this, \"preProcessSnapshot\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (preProcessor) {\n var currentPreprocessor = _this.preProcessor;\n if (!currentPreprocessor)\n return _this.cloneAndEnhance({ preProcessor: preProcessor });\n else\n return _this.cloneAndEnhance({\n preProcessor: function (snapshot) { return currentPreprocessor(preProcessor(snapshot)); }\n });\n }\n });\n Object.defineProperty(_this, \"postProcessSnapshot\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (postProcessor) {\n var currentPostprocessor = _this.postProcessor;\n if (!currentPostprocessor)\n return _this.cloneAndEnhance({ postProcessor: postProcessor });\n else\n return _this.cloneAndEnhance({\n postProcessor: function (snapshot) { return postProcessor(currentPostprocessor(snapshot)); }\n });\n }\n });\n Object.assign(_this, defaultObjectOptions, opts);\n // ensures that any default value gets converted to its related type\n _this.properties = toPropertiesObject(_this.properties);\n freeze(_this.properties); // make sure nobody messes with it\n _this.propertyNames = Object.keys(_this.properties);\n _this.identifierAttribute = _this._getIdentifierAttribute();\n return _this;\n }\n Object.defineProperty(ModelType.prototype, \"_getIdentifierAttribute\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var identifierAttribute = undefined;\n this.forAllProps(function (propName, propType) {\n if (propType.flags & TypeFlags.Identifier) {\n if (identifierAttribute)\n throw fail(\"Cannot define property '\" + propName + \"' as object identifier, property '\" + identifierAttribute + \"' is already defined as identifier property\");\n identifierAttribute = propName;\n }\n });\n return identifierAttribute;\n }\n });\n Object.defineProperty(ModelType.prototype, \"cloneAndEnhance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (opts) {\n return new ModelType({\n name: opts.name || this.name,\n properties: Object.assign({}, this.properties, opts.properties),\n initializers: this.initializers.concat(opts.initializers || []),\n preProcessor: opts.preProcessor || this.preProcessor,\n postProcessor: opts.postProcessor || this.postProcessor\n });\n }\n });\n Object.defineProperty(ModelType.prototype, \"actions\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n var _this = this;\n var actionInitializer = function (self) {\n _this.instantiateActions(self, fn(self));\n return self;\n };\n return this.cloneAndEnhance({ initializers: [actionInitializer] });\n }\n });\n Object.defineProperty(ModelType.prototype, \"instantiateActions\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (self, actions) {\n // check if return is correct\n if (!isPlainObject(actions))\n throw fail(\"actions initializer should return a plain object containing actions\");\n // bind actions to the object created\n Object.keys(actions).forEach(function (name) {\n // warn if preprocessor was given\n if (name === PRE_PROCESS_SNAPSHOT)\n throw fail(\"Cannot define action '\" + PRE_PROCESS_SNAPSHOT + \"', it should be defined using 'type.preProcessSnapshot(fn)' instead\");\n // warn if postprocessor was given\n if (name === POST_PROCESS_SNAPSHOT)\n throw fail(\"Cannot define action '\" + POST_PROCESS_SNAPSHOT + \"', it should be defined using 'type.postProcessSnapshot(fn)' instead\");\n var action2 = actions[name];\n // apply hook composition\n var baseAction = self[name];\n if (name in Hook && baseAction) {\n var specializedAction_1 = action2;\n action2 = function () {\n baseAction.apply(null, arguments);\n specializedAction_1.apply(null, arguments);\n };\n }\n // the goal of this is to make sure actions using \"this\" can call themselves,\n // while still allowing the middlewares to register them\n var middlewares = action2.$mst_middleware; // make sure middlewares are not lost\n var boundAction = action2.bind(actions);\n boundAction._isFlowAction = action2._isFlowAction || false;\n boundAction.$mst_middleware = middlewares;\n var actionInvoker = createActionInvoker(self, name, boundAction);\n actions[name] = actionInvoker;\n (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(self, name, actionInvoker);\n });\n }\n });\n Object.defineProperty(ModelType.prototype, \"volatile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n var _this = this;\n if (typeof fn !== \"function\") {\n throw fail(\"You passed an \" + typeof fn + \" to volatile state as an argument, when function is expected\");\n }\n var stateInitializer = function (self) {\n _this.instantiateVolatileState(self, fn(self));\n return self;\n };\n return this.cloneAndEnhance({ initializers: [stateInitializer] });\n }\n });\n Object.defineProperty(ModelType.prototype, \"instantiateVolatileState\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (self, state) {\n // check views return\n if (!isPlainObject(state))\n throw fail(\"volatile state initializer should return a plain object containing state\");\n set(self, state);\n }\n });\n Object.defineProperty(ModelType.prototype, \"extend\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n var _this = this;\n var initializer = function (self) {\n var _a = fn(self), actions = _a.actions, views = _a.views, state = _a.state, rest = __rest(_a, [\"actions\", \"views\", \"state\"]);\n for (var key in rest)\n throw fail(\"The `extend` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '\" + key + \"'\");\n if (state)\n _this.instantiateVolatileState(self, state);\n if (views)\n _this.instantiateViews(self, views);\n if (actions)\n _this.instantiateActions(self, actions);\n return self;\n };\n return this.cloneAndEnhance({ initializers: [initializer] });\n }\n });\n Object.defineProperty(ModelType.prototype, \"views\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n var _this = this;\n var viewInitializer = function (self) {\n _this.instantiateViews(self, fn(self));\n return self;\n };\n return this.cloneAndEnhance({ initializers: [viewInitializer] });\n }\n });\n Object.defineProperty(ModelType.prototype, \"instantiateViews\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (self, views) {\n // check views return\n if (!isPlainObject(views))\n throw fail(\"views initializer should return a plain object containing views\");\n Object.getOwnPropertyNames(views).forEach(function (key) {\n var _a;\n // is this a computed property?\n var descriptor = Object.getOwnPropertyDescriptor(views, key);\n if (\"get\" in descriptor) {\n defineProperty$1(self, key, descriptor);\n makeObservable(self, (_a = {}, _a[key] = computed, _a));\n }\n else if (typeof descriptor.value === \"function\") {\n (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(self, key, descriptor.value);\n }\n else {\n throw fail(\"A view member should either be a function or getter based property\");\n }\n });\n }\n });\n Object.defineProperty(ModelType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n var value = isStateTreeNode(initialValue)\n ? initialValue\n : this.applySnapshotPreProcessor(initialValue);\n return createObjectNode(this, parent, subpath, environment, value);\n // Optimization: record all prop- view- and action names after first construction, and generate an optimal base class\n // that pre-reserves all these fields for fast object-member lookups\n }\n });\n Object.defineProperty(ModelType.prototype, \"initializeChildNodes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (objNode, initialSnapshot) {\n if (initialSnapshot === void 0) { initialSnapshot = {}; }\n var type = objNode.type;\n var result = {};\n type.forAllProps(function (name, childType) {\n result[name] = childType.instantiate(objNode, name, undefined, initialSnapshot[name]);\n });\n return result;\n }\n });\n Object.defineProperty(ModelType.prototype, \"createNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNodes) {\n var options = __assign(__assign({}, mobxShallow), { name: this.name });\n return observable.object(childNodes, EMPTY_OBJECT, options);\n }\n });\n Object.defineProperty(ModelType.prototype, \"finalizeNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, instance) {\n addHiddenFinalProp(instance, \"toString\", objectTypeToString);\n this.forAllProps(function (name) {\n _interceptReads(instance, name, node.unbox);\n });\n this.initializers.reduce(function (self, fn) { return fn(self); }, instance);\n intercept(instance, this.willChange);\n observe(instance, this.didChange);\n }\n });\n Object.defineProperty(ModelType.prototype, \"willChange\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (chg) {\n // TODO: mobx typings don't seem to take into account that newValue can be set even when removing a prop\n var change = chg;\n var node = getStateTreeNode(change.object);\n var subpath = change.name;\n node.assertWritable({ subpath: subpath });\n var childType = node.type.properties[subpath];\n // only properties are typed, state are stored as-is references\n if (childType) {\n typecheckInternal(childType, change.newValue);\n change.newValue = childType.reconcile(node.getChildNode(subpath), change.newValue, node, subpath);\n }\n return change;\n }\n });\n Object.defineProperty(ModelType.prototype, \"didChange\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (chg) {\n // TODO: mobx typings don't seem to take into account that newValue can be set even when removing a prop\n var change = chg;\n var childNode = getStateTreeNode(change.object);\n var childType = childNode.type.properties[change.name];\n if (!childType) {\n // don't emit patches for volatile state\n return;\n }\n var oldChildValue = change.oldValue ? change.oldValue.snapshot : undefined;\n childNode.emitPatch({\n op: \"replace\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: oldChildValue\n }, childNode);\n }\n });\n Object.defineProperty(ModelType.prototype, \"getChildren\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n var _this = this;\n var res = [];\n this.forAllProps(function (name) {\n res.push(_this.getChildNode(node, name));\n });\n return res;\n }\n });\n Object.defineProperty(ModelType.prototype, \"getChildNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, key) {\n var _a;\n if (!(key in this.properties))\n throw fail(\"Not a value property: \" + key);\n var adm = _getAdministration(node.storedValue, key);\n var childNode = (_a = adm.raw) === null || _a === void 0 ? void 0 : _a.call(adm);\n if (!childNode)\n throw fail(\"Node not available for property \" + key);\n return childNode;\n }\n });\n Object.defineProperty(ModelType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, applyPostProcess) {\n var _this = this;\n if (applyPostProcess === void 0) { applyPostProcess = true; }\n var res = {};\n this.forAllProps(function (name, type) {\n try {\n // TODO: FIXME, make sure the observable ref is used!\n var atom = getAtom(node.storedValue, name);\n atom.reportObserved();\n }\n catch (e) {\n throw fail(name + \" property is declared twice\");\n }\n res[name] = _this.getChildNode(node, name).snapshot;\n });\n if (applyPostProcess) {\n return this.applySnapshotPostProcessor(res);\n }\n return res;\n }\n });\n Object.defineProperty(ModelType.prototype, \"processInitialSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (childNodes) {\n var processed = {};\n Object.keys(childNodes).forEach(function (key) {\n processed[key] = childNodes[key].getSnapshot();\n });\n return this.applySnapshotPostProcessor(processed);\n }\n });\n Object.defineProperty(ModelType.prototype, \"applyPatchLocally\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, subpath, patch) {\n if (!(patch.op === \"replace\" || patch.op === \"add\")) {\n throw fail(\"object does not support operation \" + patch.op);\n }\n node.storedValue[subpath] = patch.value;\n }\n });\n Object.defineProperty(ModelType.prototype, \"applySnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, snapshot) {\n typecheckInternal(this, snapshot);\n var preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot);\n this.forAllProps(function (name) {\n node.storedValue[name] = preProcessedSnapshot[name];\n });\n }\n });\n Object.defineProperty(ModelType.prototype, \"applySnapshotPreProcessor\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot) {\n var processor = this.preProcessor;\n return processor ? processor.call(null, snapshot) : snapshot;\n }\n });\n Object.defineProperty(ModelType.prototype, \"applySnapshotPostProcessor\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot) {\n var postProcessor = this.postProcessor;\n if (postProcessor)\n return postProcessor.call(null, snapshot);\n return snapshot;\n }\n });\n Object.defineProperty(ModelType.prototype, \"getChildType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (propertyName) {\n assertIsString(propertyName, 1);\n return this.properties[propertyName];\n }\n });\n Object.defineProperty(ModelType.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var _this = this;\n var snapshot = this.applySnapshotPreProcessor(value);\n if (!isPlainObject(snapshot)) {\n return typeCheckFailure(context, snapshot, \"Value is not a plain object\");\n }\n return flattenTypeErrors(this.propertyNames.map(function (key) {\n return _this.properties[key].validate(snapshot[key], getContextForPath(context, key, _this.properties[key]));\n }));\n }\n });\n Object.defineProperty(ModelType.prototype, \"forAllProps\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (fn) {\n var _this = this;\n this.propertyNames.forEach(function (key) { return fn(key, _this.properties[key]); });\n }\n });\n Object.defineProperty(ModelType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var _this = this;\n // optimization: cache\n return (\"{ \" +\n this.propertyNames.map(function (key) { return key + \": \" + _this.properties[key].describe(); }).join(\"; \") +\n \" }\");\n }\n });\n Object.defineProperty(ModelType.prototype, \"getDefaultSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return EMPTY_OBJECT;\n }\n });\n Object.defineProperty(ModelType.prototype, \"removeChild\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node, subpath) {\n node.storedValue[subpath] = undefined;\n }\n });\n return ModelType;\n}(ComplexType));\nModelType.prototype.applySnapshot = action(ModelType.prototype.applySnapshot);\n/**\n * `types.model` - Creates a new model type by providing a name, properties, volatile state and actions.\n *\n * See the [model type](/concepts/trees#creating-models) description or the [getting started](intro/getting-started.md#getting-started-1) tutorial.\n */\nfunction model() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (devMode() && typeof args[0] !== \"string\" && args[1]) {\n throw fail(\"Model creation failed. First argument must be a string when two arguments are provided\");\n }\n var name = typeof args[0] === \"string\" ? args.shift() : \"AnonymousModel\";\n var properties = args.shift() || {};\n return new ModelType({ name: name, properties: properties });\n}\n/**\n * `types.compose` - Composes a new model from one or more existing model types.\n * This method can be invoked in two forms:\n * Given 2 or more model types, the types are composed into a new Type.\n * Given first parameter as a string and 2 or more model types,\n * the types are composed into a new Type with the given name\n */\nfunction compose() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n // TODO: just join the base type names if no name is provided\n var hasTypename = typeof args[0] === \"string\";\n var typeName = hasTypename ? args[0] : \"AnonymousModel\";\n if (hasTypename) {\n args.shift();\n }\n // check all parameters\n if (devMode()) {\n args.forEach(function (type, i) {\n assertArg(type, isModelType, \"mobx-state-tree model type\", hasTypename ? i + 2 : i + 1);\n });\n }\n return args\n .reduce(function (prev, cur) {\n return prev.cloneAndEnhance({\n name: prev.name + \"_\" + cur.name,\n properties: cur.properties,\n initializers: cur.initializers,\n preProcessor: function (snapshot) {\n return cur.applySnapshotPreProcessor(prev.applySnapshotPreProcessor(snapshot));\n },\n postProcessor: function (snapshot) {\n return cur.applySnapshotPostProcessor(prev.applySnapshotPostProcessor(snapshot));\n }\n });\n })\n .named(typeName);\n}\n/**\n * Returns if a given value represents a model type.\n *\n * @param type\n * @returns\n */\nfunction isModelType(type) {\n return isType(type) && (type.flags & TypeFlags.Object) > 0;\n}\n\n// TODO: implement CoreType using types.custom ?\n/**\n * @internal\n * @hidden\n */\nvar CoreType = /** @class */ (function (_super) {\n __extends(CoreType, _super);\n function CoreType(name, flags, checker, initializer) {\n if (initializer === void 0) { initializer = identity; }\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: flags\n });\n Object.defineProperty(_this, \"checker\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: checker\n });\n Object.defineProperty(_this, \"initializer\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: initializer\n });\n _this.flags = flags;\n return _this;\n }\n Object.defineProperty(CoreType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.name;\n }\n });\n Object.defineProperty(CoreType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n return createScalarNode(this, parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(CoreType.prototype, \"createNewInstance\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (snapshot) {\n return this.initializer(snapshot);\n }\n });\n Object.defineProperty(CoreType.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n if (isPrimitive(value) && this.checker(value)) {\n return typeCheckSuccess();\n }\n var typeName = this.name === \"Date\" ? \"Date or a unix milliseconds timestamp\" : this.name;\n return typeCheckFailure(context, value, \"Value is not a \" + typeName);\n }\n });\n return CoreType;\n}(SimpleType));\n/**\n * `types.string` - Creates a type that can only contain a string value.\n * This type is used for string values by default\n *\n * Example:\n * ```ts\n * const Person = types.model({\n * firstName: types.string,\n * lastName: \"Doe\"\n * })\n * ```\n */\n// tslint:disable-next-line:variable-name\nvar string = new CoreType(\"string\", TypeFlags.String, function (v) { return typeof v === \"string\"; });\n/**\n * `types.number` - Creates a type that can only contain a numeric value.\n * This type is used for numeric values by default\n *\n * Example:\n * ```ts\n * const Vector = types.model({\n * x: types.number,\n * y: 1.5\n * })\n * ```\n */\n// tslint:disable-next-line:variable-name\nvar number = new CoreType(\"number\", TypeFlags.Number, function (v) { return typeof v === \"number\"; });\n/**\n * `types.integer` - Creates a type that can only contain an integer value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.integer,\n * height: 10\n * })\n * ```\n */\n// tslint:disable-next-line:variable-name\nvar integer = new CoreType(\"integer\", TypeFlags.Integer, function (v) { return isInteger(v); });\n/**\n * `types.float` - Creates a type that can only contain an float value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.float,\n * height: 10\n * })\n * ```\n */\n// tslint:disable-next-line:variable-name\nvar float = new CoreType(\"float\", TypeFlags.Float, function (v) { return isFloat(v); });\n/**\n * `types.finite` - Creates a type that can only contain an finite value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.finite,\n * height: 10\n * })\n * ```\n */\n// tslint:disable-next-line:variable-name\nvar finite = new CoreType(\"finite\", TypeFlags.Finite, function (v) { return isFinite(v); });\n/**\n * `types.boolean` - Creates a type that can only contain a boolean value.\n * This type is used for boolean values by default\n *\n * Example:\n * ```ts\n * const Thing = types.model({\n * isCool: types.boolean,\n * isAwesome: false\n * })\n * ```\n */\n// tslint:disable-next-line:variable-name\nvar boolean = new CoreType(\"boolean\", TypeFlags.Boolean, function (v) { return typeof v === \"boolean\"; });\n/**\n * `types.null` - The type of the value `null`\n */\nvar nullType = new CoreType(\"null\", TypeFlags.Null, function (v) { return v === null; });\n/**\n * `types.undefined` - The type of the value `undefined`\n */\nvar undefinedType = new CoreType(\"undefined\", TypeFlags.Undefined, function (v) { return v === undefined; });\nvar _DatePrimitive = new CoreType(\"Date\", TypeFlags.Date, function (v) { return typeof v === \"number\" || v instanceof Date; }, function (v) { return (v instanceof Date ? v : new Date(v)); });\n_DatePrimitive.getSnapshot = function (node) {\n return node.storedValue.getTime();\n};\n/**\n * `types.Date` - Creates a type that can only contain a javascript Date value.\n *\n * Example:\n * ```ts\n * const LogLine = types.model({\n * timestamp: types.Date,\n * })\n *\n * LogLine.create({ timestamp: new Date() })\n * ```\n */\nvar DatePrimitive = _DatePrimitive;\n/**\n * @internal\n * @hidden\n */\nfunction getPrimitiveFactoryFromValue(value) {\n switch (typeof value) {\n case \"string\":\n return string;\n case \"number\":\n return number; // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now\n case \"boolean\":\n return boolean;\n case \"object\":\n if (value instanceof Date)\n return DatePrimitive;\n }\n throw fail(\"Cannot determine primitive type from value \" + value);\n}\n/**\n * Returns if a given value represents a primitive type.\n *\n * @param type\n * @returns\n */\nfunction isPrimitiveType(type) {\n return (isType(type) &&\n (type.flags &\n (TypeFlags.String |\n TypeFlags.Number |\n TypeFlags.Integer |\n TypeFlags.Boolean |\n TypeFlags.Date)) >\n 0);\n}\n\n/**\n * @internal\n * @hidden\n */\nvar Literal = /** @class */ (function (_super) {\n __extends(Literal, _super);\n function Literal(value) {\n var _this = _super.call(this, JSON.stringify(value)) || this;\n Object.defineProperty(_this, \"value\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Literal\n });\n _this.value = value;\n return _this;\n }\n Object.defineProperty(Literal.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n return createScalarNode(this, parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(Literal.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return JSON.stringify(this.value);\n }\n });\n Object.defineProperty(Literal.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n if (isPrimitive(value) && value === this.value) {\n return typeCheckSuccess();\n }\n return typeCheckFailure(context, value, \"Value is not a literal \" + JSON.stringify(this.value));\n }\n });\n return Literal;\n}(SimpleType));\n/**\n * `types.literal` - The literal type will return a type that will match only the exact given type.\n * The given value must be a primitive, in order to be serialized to a snapshot correctly.\n * You can use literal to match exact strings for example the exact male or female string.\n *\n * Example:\n * ```ts\n * const Person = types.model({\n * name: types.string,\n * gender: types.union(types.literal('male'), types.literal('female'))\n * })\n * ```\n *\n * @param value The value to use in the strict equal check\n * @returns\n */\nfunction literal(value) {\n // check that the given value is a primitive\n assertArg(value, isPrimitive, \"primitive\", 1);\n return new Literal(value);\n}\n/**\n * Returns if a given value represents a literal type.\n *\n * @param type\n * @returns\n */\nfunction isLiteralType(type) {\n return isType(type) && (type.flags & TypeFlags.Literal) > 0;\n}\n\nvar Refinement = /** @class */ (function (_super) {\n __extends(Refinement, _super);\n function Refinement(name, _subtype, _predicate, _message) {\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"_subtype\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _subtype\n });\n Object.defineProperty(_this, \"_predicate\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _predicate\n });\n Object.defineProperty(_this, \"_message\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _message\n });\n return _this;\n }\n Object.defineProperty(Refinement.prototype, \"flags\", {\n get: function () {\n return this._subtype.flags | TypeFlags.Refinement;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Refinement.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.name;\n }\n });\n Object.defineProperty(Refinement.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n // create the child type\n return this._subtype.instantiate(parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(Refinement.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n return this._subtype.isAssignableFrom(type);\n }\n });\n Object.defineProperty(Refinement.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var subtypeErrors = this._subtype.validate(value, context);\n if (subtypeErrors.length > 0)\n return subtypeErrors;\n var snapshot = isStateTreeNode(value) ? getStateTreeNode(value).snapshot : value;\n if (!this._predicate(snapshot)) {\n return typeCheckFailure(context, value, this._message(value));\n }\n return typeCheckSuccess();\n }\n });\n Object.defineProperty(Refinement.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n return this._subtype.reconcile(current, newValue, parent, subpath);\n }\n });\n Object.defineProperty(Refinement.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._subtype;\n }\n });\n return Refinement;\n}(BaseType));\n/**\n * `types.refinement` - Creates a type that is more specific than the base type, e.g. `types.refinement(types.string, value => value.length > 5)` to create a type of strings that can only be longer then 5.\n *\n * @param name\n * @param type\n * @param predicate\n * @returns\n */\nfunction refinement() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var name = typeof args[0] === \"string\" ? args.shift() : isType(args[0]) ? args[0].name : null;\n var type = args[0];\n var predicate = args[1];\n var message = args[2] ? args[2] : function (v) { return \"Value does not respect the refinement predicate\"; };\n // ensures all parameters are correct\n assertIsType(type, [1, 2]);\n assertIsString(name, 1);\n assertIsFunction(predicate, [2, 3]);\n assertIsFunction(message, [3, 4]);\n return new Refinement(name, type, predicate, message);\n}\n/**\n * Returns if a given value is a refinement type.\n *\n * @param type\n * @returns\n */\nfunction isRefinementType(type) {\n return (type.flags & TypeFlags.Refinement) > 0;\n}\n\n/**\n * `types.enumeration` - Can be used to create an string based enumeration.\n * (note: this methods is just sugar for a union of string literals)\n *\n * Example:\n * ```ts\n * const TrafficLight = types.model({\n * color: types.enumeration(\"Color\", [\"Red\", \"Orange\", \"Green\"])\n * })\n * ```\n *\n * @param name descriptive name of the enumeration (optional)\n * @param options possible values this enumeration can have\n * @returns\n */\nfunction enumeration(name, options) {\n var realOptions = typeof name === \"string\" ? options : name;\n // check all options\n if (devMode()) {\n realOptions.forEach(function (option, i) {\n assertIsString(option, i + 1);\n });\n }\n var type = union.apply(void 0, __spread(realOptions.map(function (option) { return literal(\"\" + option); })));\n if (typeof name === \"string\")\n type.name = name;\n return type;\n}\n\n/**\n * @internal\n * @hidden\n */\nvar Union = /** @class */ (function (_super) {\n __extends(Union, _super);\n function Union(name, _types, options) {\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"_types\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _types\n });\n Object.defineProperty(_this, \"_dispatcher\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"_eager\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n options = __assign({ eager: true, dispatcher: undefined }, options);\n _this._dispatcher = options.dispatcher;\n if (!options.eager)\n _this._eager = false;\n return _this;\n }\n Object.defineProperty(Union.prototype, \"flags\", {\n get: function () {\n var result = TypeFlags.Union;\n this._types.forEach(function (type) {\n result |= type.flags;\n });\n return result;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Union.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n return this._types.some(function (subType) { return subType.isAssignableFrom(type); });\n }\n });\n Object.defineProperty(Union.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return \"(\" + this._types.map(function (factory) { return factory.describe(); }).join(\" | \") + \")\";\n }\n });\n Object.defineProperty(Union.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n var type = this.determineType(initialValue, undefined);\n if (!type)\n throw fail(\"No matching type for union \" + this.describe()); // can happen in prod builds\n return type.instantiate(parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(Union.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n var type = this.determineType(newValue, current.getReconciliationType());\n if (!type)\n throw fail(\"No matching type for union \" + this.describe()); // can happen in prod builds\n return type.reconcile(current, newValue, parent, subpath);\n }\n });\n Object.defineProperty(Union.prototype, \"determineType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, reconcileCurrentType) {\n // try the dispatcher, if defined\n if (this._dispatcher) {\n return this._dispatcher(value);\n }\n // find the most accomodating type\n // if we are using reconciliation try the current node type first (fix for #1045)\n if (reconcileCurrentType) {\n if (reconcileCurrentType.is(value)) {\n return reconcileCurrentType;\n }\n return this._types.filter(function (t) { return t !== reconcileCurrentType; }).find(function (type) { return type.is(value); });\n }\n else {\n return this._types.find(function (type) { return type.is(value); });\n }\n }\n });\n Object.defineProperty(Union.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n if (this._dispatcher) {\n return this._dispatcher(value).validate(value, context);\n }\n var allErrors = [];\n var applicableTypes = 0;\n for (var i = 0; i < this._types.length; i++) {\n var type = this._types[i];\n var errors = type.validate(value, context);\n if (errors.length === 0) {\n if (this._eager)\n return typeCheckSuccess();\n else\n applicableTypes++;\n }\n else {\n allErrors.push(errors);\n }\n }\n if (applicableTypes === 1)\n return typeCheckSuccess();\n return typeCheckFailure(context, value, \"No type is applicable for the union\").concat(flattenTypeErrors(allErrors));\n }\n });\n Object.defineProperty(Union.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._types;\n }\n });\n return Union;\n}(BaseType));\n/**\n * `types.union` - Create a union of multiple types. If the correct type cannot be inferred unambiguously from a snapshot, provide a dispatcher function of the form `(snapshot) => Type`.\n *\n * @param optionsOrType\n * @param otherTypes\n * @returns\n */\nfunction union(optionsOrType) {\n var otherTypes = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n otherTypes[_i - 1] = arguments[_i];\n }\n var options = isType(optionsOrType) ? undefined : optionsOrType;\n var types = isType(optionsOrType) ? __spread([optionsOrType], otherTypes) : otherTypes;\n var name = \"(\" + types.map(function (type) { return type.name; }).join(\" | \") + \")\";\n // check all options\n if (devMode()) {\n if (options) {\n assertArg(options, function (o) { return isPlainObject(o); }, \"object { eager?: boolean, dispatcher?: Function }\", 1);\n }\n types.forEach(function (type, i) {\n assertIsType(type, options ? i + 2 : i + 1);\n });\n }\n return new Union(name, types, options);\n}\n/**\n * Returns if a given value represents a union type.\n *\n * @param type\n * @returns\n */\nfunction isUnionType(type) {\n return (type.flags & TypeFlags.Union) > 0;\n}\n\n/**\n * @hidden\n * @internal\n */\nvar OptionalValue = /** @class */ (function (_super) {\n __extends(OptionalValue, _super);\n function OptionalValue(_subtype, _defaultValue, optionalValues) {\n var _this = _super.call(this, _subtype.name) || this;\n Object.defineProperty(_this, \"_subtype\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _subtype\n });\n Object.defineProperty(_this, \"_defaultValue\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _defaultValue\n });\n Object.defineProperty(_this, \"optionalValues\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: optionalValues\n });\n return _this;\n }\n Object.defineProperty(OptionalValue.prototype, \"flags\", {\n get: function () {\n return this._subtype.flags | TypeFlags.Optional;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(OptionalValue.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._subtype.describe() + \"?\";\n }\n });\n Object.defineProperty(OptionalValue.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n if (this.optionalValues.indexOf(initialValue) >= 0) {\n var defaultInstanceOrSnapshot = this.getDefaultInstanceOrSnapshot();\n return this._subtype.instantiate(parent, subpath, environment, defaultInstanceOrSnapshot);\n }\n return this._subtype.instantiate(parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(OptionalValue.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n return this._subtype.reconcile(current, this.optionalValues.indexOf(newValue) < 0 && this._subtype.is(newValue)\n ? newValue\n : this.getDefaultInstanceOrSnapshot(), parent, subpath);\n }\n });\n Object.defineProperty(OptionalValue.prototype, \"getDefaultInstanceOrSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var defaultInstanceOrSnapshot = typeof this._defaultValue === \"function\"\n ? this._defaultValue()\n : this._defaultValue;\n // while static values are already snapshots and checked on types.optional\n // generator functions must always be rechecked just in case\n if (typeof this._defaultValue === \"function\") {\n typecheckInternal(this, defaultInstanceOrSnapshot);\n }\n return defaultInstanceOrSnapshot;\n }\n });\n Object.defineProperty(OptionalValue.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n // defaulted values can be skipped\n if (this.optionalValues.indexOf(value) >= 0) {\n return typeCheckSuccess();\n }\n // bounce validation to the sub-type\n return this._subtype.validate(value, context);\n }\n });\n Object.defineProperty(OptionalValue.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n return this._subtype.isAssignableFrom(type);\n }\n });\n Object.defineProperty(OptionalValue.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this._subtype;\n }\n });\n return OptionalValue;\n}(BaseType));\nfunction checkOptionalPreconditions(type, defaultValueOrFunction) {\n // make sure we never pass direct instances\n if (typeof defaultValueOrFunction !== \"function\" && isStateTreeNode(defaultValueOrFunction)) {\n throw fail(\"default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead\");\n }\n assertIsType(type, 1);\n if (devMode()) {\n // we only check default values if they are passed directly\n // if they are generator functions they will be checked once they are generated\n // we don't check generator function results here to avoid generating a node just for type-checking purposes\n // which might generate side-effects\n if (typeof defaultValueOrFunction !== \"function\") {\n typecheckInternal(type, defaultValueOrFunction);\n }\n }\n}\n/**\n * `types.optional` - Can be used to create a property with a default value.\n *\n * Depending on the third argument (`optionalValues`) there are two ways of operation:\n * - If the argument is not provided, then if a value is not provided in the snapshot (`undefined` or missing),\n * it will default to the provided `defaultValue`\n * - If the argument is provided, then if the value in the snapshot matches one of the optional values inside the array then it will\n * default to the provided `defaultValue`. Additionally, if one of the optional values inside the array is `undefined` then a missing\n * property is also valid.\n *\n * Note that it is also possible to include values of the same type as the intended subtype as optional values,\n * in this case the optional value will be transformed into the `defaultValue` (e.g. `types.optional(types.string, \"unnamed\", [undefined, \"\"])`\n * will transform the snapshot values `undefined` (and therefore missing) and empty strings into the string `\"unnamed\"` when it gets\n * instantiated).\n *\n * If `defaultValue` is a function, the function will be invoked for every new instance.\n * Applying a snapshot in which the optional value is one of the optional values (or `undefined`/_not_ present if none are provided) causes the\n * value to be reset.\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * title: types.string,\n * subtitle1: types.optional(types.string, \"\", [null]),\n * subtitle2: types.optional(types.string, \"\", [null, undefined]),\n * done: types.optional(types.boolean, false),\n * created: types.optional(types.Date, () => new Date()),\n * })\n *\n * // if done is missing / undefined it will become false\n * // if created is missing / undefined it will get a freshly generated timestamp\n * // if subtitle1 is null it will default to \"\", but it cannot be missing or undefined\n * // if subtitle2 is null or undefined it will default to \"\"; since it can be undefined it can also be missing\n * const todo = Todo.create({ title: \"Get coffee\", subtitle1: null })\n * ```\n *\n * @param type\n * @param defaultValueOrFunction\n * @param optionalValues an optional array with zero or more primitive values (string, number, boolean, null or undefined)\n * that will be converted into the default. `[ undefined ]` is assumed when none is provided\n * @returns\n */\nfunction optional(type, defaultValueOrFunction, optionalValues) {\n checkOptionalPreconditions(type, defaultValueOrFunction);\n return new OptionalValue(type, defaultValueOrFunction, optionalValues ? optionalValues : undefinedAsOptionalValues);\n}\nvar undefinedAsOptionalValues = [undefined];\n/**\n * Returns if a value represents an optional type.\n *\n * @template IT\n * @param type\n * @returns\n */\nfunction isOptionalType(type) {\n return isType(type) && (type.flags & TypeFlags.Optional) > 0;\n}\n\nvar optionalUndefinedType = optional(undefinedType, undefined);\nvar optionalNullType = optional(nullType, null);\n/**\n * `types.maybe` - Maybe will make a type nullable, and also optional.\n * The value `undefined` will be used to represent nullability.\n *\n * @param type\n * @returns\n */\nfunction maybe(type) {\n assertIsType(type, 1);\n return union(type, optionalUndefinedType);\n}\n/**\n * `types.maybeNull` - Maybe will make a type nullable, and also optional.\n * The value `null` will be used to represent no value.\n *\n * @param type\n * @returns\n */\nfunction maybeNull(type) {\n assertIsType(type, 1);\n return union(type, optionalNullType);\n}\n\nvar Late = /** @class */ (function (_super) {\n __extends(Late, _super);\n function Late(name, _definition) {\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"_definition\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _definition\n });\n Object.defineProperty(_this, \"_subType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n return _this;\n }\n Object.defineProperty(Late.prototype, \"flags\", {\n get: function () {\n return (this._subType ? this._subType.flags : 0) | TypeFlags.Late;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Late.prototype, \"getSubType\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (mustSucceed) {\n if (!this._subType) {\n var t = undefined;\n try {\n t = this._definition();\n }\n catch (e) {\n if (e instanceof ReferenceError)\n // can happen in strict ES5 code when a definition is self refering\n t = undefined;\n else\n throw e;\n }\n if (mustSucceed && t === undefined)\n throw fail(\"Late type seems to be used too early, the definition (still) returns undefined\");\n if (t) {\n if (devMode() && !isType(t))\n throw fail(\"Failed to determine subtype, make sure types.late returns a type definition.\");\n this._subType = t;\n }\n }\n return this._subType;\n }\n });\n Object.defineProperty(Late.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n return this.getSubType(true).instantiate(parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(Late.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n return this.getSubType(true).reconcile(current, newValue, parent, subpath);\n }\n });\n Object.defineProperty(Late.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var t = this.getSubType(false);\n return t ? t.name : \"\";\n }\n });\n Object.defineProperty(Late.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n var t = this.getSubType(false);\n if (!t) {\n // See #916; the variable the definition closure is pointing to wasn't defined yet, so can't be evaluted yet here\n return typeCheckSuccess();\n }\n return t.validate(value, context);\n }\n });\n Object.defineProperty(Late.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n var t = this.getSubType(false);\n return t ? t.isAssignableFrom(type) : false;\n }\n });\n Object.defineProperty(Late.prototype, \"getSubTypes\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var subtype = this.getSubType(false);\n return subtype ? subtype : cannotDetermineSubtype;\n }\n });\n return Late;\n}(BaseType));\n/**\n * `types.late` - Defines a type that gets implemented later. This is useful when you have to deal with circular dependencies.\n * Please notice that when defining circular dependencies TypeScript isn't smart enough to inference them.\n *\n * Example:\n * ```ts\n * // TypeScript isn't smart enough to infer self referencing types.\n * const Node = types.model({\n * children: types.array(types.late((): IAnyModelType => Node)) // then typecast each array element to Instance\n * })\n * ```\n *\n * @param name The name to use for the type that will be returned.\n * @param type A function that returns the type that will be defined.\n * @returns\n */\nfunction late(nameOrType, maybeType) {\n var name = typeof nameOrType === \"string\" ? nameOrType : \"late(\" + nameOrType.toString() + \")\";\n var type = typeof nameOrType === \"string\" ? maybeType : nameOrType;\n // checks that the type is actually a late type\n if (devMode()) {\n if (!(typeof type === \"function\" && type.length === 0))\n throw fail(\"Invalid late type, expected a function with zero arguments that returns a type, got: \" +\n type);\n }\n return new Late(name, type);\n}\n/**\n * Returns if a given value represents a late type.\n *\n * @param type\n * @returns\n */\nfunction isLateType(type) {\n return isType(type) && (type.flags & TypeFlags.Late) > 0;\n}\n\nfunction lazy(name, options) {\n // TODO: fix this unknown casting to be stricter\n return new Lazy(name, options);\n}\n/**\n * @internal\n * @hidden\n */\nvar Lazy = /** @class */ (function (_super) {\n __extends(Lazy, _super);\n function Lazy(name, options) {\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"options\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: options\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Lazy\n });\n Object.defineProperty(_this, \"loadedType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: null\n });\n Object.defineProperty(_this, \"pendingNodeList\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: observable.array()\n });\n when(function () {\n return _this.pendingNodeList.length > 0 &&\n _this.pendingNodeList.some(function (node) {\n return node.isAlive && _this.options.shouldLoadPredicate(node.parent ? node.parent.value : null);\n });\n }, function () {\n _this.options.loadType().then(action(function (type) {\n _this.loadedType = type;\n _this.pendingNodeList.forEach(function (node) {\n if (!node.parent)\n return;\n if (!_this.loadedType)\n return;\n node.parent.applyPatches([\n {\n op: \"replace\",\n path: \"/\" + node.subpath,\n value: node.snapshot\n }\n ]);\n });\n }));\n });\n return _this;\n }\n Object.defineProperty(Lazy.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return \"\";\n }\n });\n Object.defineProperty(Lazy.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, value) {\n var _this = this;\n if (this.loadedType) {\n return this.loadedType.instantiate(parent, subpath, environment, value);\n }\n var node = createScalarNode(this, parent, subpath, environment, deepFreeze(value));\n this.pendingNodeList.push(node);\n when(function () { return !node.isAlive; }, function () { return _this.pendingNodeList.splice(_this.pendingNodeList.indexOf(node), 1); });\n return node;\n }\n });\n Object.defineProperty(Lazy.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n if (this.loadedType) {\n return this.loadedType.validate(value, context);\n }\n if (!isSerializable(value)) {\n return typeCheckFailure(context, value, \"Value is not serializable and cannot be lazy\");\n }\n return typeCheckSuccess();\n }\n });\n Object.defineProperty(Lazy.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, value, parent, subpath) {\n if (this.loadedType) {\n current.die();\n return this.loadedType.instantiate(parent, subpath, parent.environment, value);\n }\n return _super.prototype.reconcile.call(this, current, value, parent, subpath);\n }\n });\n return Lazy;\n}(SimpleType));\n\n/**\n * @internal\n * @hidden\n */\nvar Frozen = /** @class */ (function (_super) {\n __extends(Frozen, _super);\n function Frozen(subType) {\n var _this = _super.call(this, subType ? \"frozen(\" + subType.name + \")\" : \"frozen\") || this;\n Object.defineProperty(_this, \"subType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: subType\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Frozen\n });\n return _this;\n }\n Object.defineProperty(Frozen.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return \"\";\n }\n });\n Object.defineProperty(Frozen.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, value) {\n // create the node\n return createScalarNode(this, parent, subpath, environment, deepFreeze(value));\n }\n });\n Object.defineProperty(Frozen.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n if (!isSerializable(value)) {\n return typeCheckFailure(context, value, \"Value is not serializable and cannot be frozen\");\n }\n if (this.subType)\n return this.subType.validate(value, context);\n return typeCheckSuccess();\n }\n });\n return Frozen;\n}(SimpleType));\nvar untypedFrozenInstance = new Frozen();\n/**\n * `types.frozen` - Frozen can be used to store any value that is serializable in itself (that is valid JSON).\n * Frozen values need to be immutable or treated as if immutable. They need be serializable as well.\n * Values stored in frozen will snapshotted as-is by MST, and internal changes will not be tracked.\n *\n * This is useful to store complex, but immutable values like vectors etc. It can form a powerful bridge to parts of your application that should be immutable, or that assume data to be immutable.\n *\n * Note: if you want to store free-form state that is mutable, or not serializeable, consider using volatile state instead.\n *\n * Frozen properties can be defined in three different ways\n * 1. `types.frozen(SubType)` - provide a valid MST type and frozen will check if the provided data conforms the snapshot for that type\n * 2. `types.frozen({ someDefaultValue: true})` - provide a primitive value, object or array, and MST will infer the type from that object, and also make it the default value for the field\n * 3. `types.frozen()` - provide a typescript type, to help in strongly typing the field (design time only)\n *\n * Example:\n * ```ts\n * const GameCharacter = types.model({\n * name: string,\n * location: types.frozen({ x: 0, y: 0})\n * })\n *\n * const hero = GameCharacter.create({\n * name: \"Mario\",\n * location: { x: 7, y: 4 }\n * })\n *\n * hero.location = { x: 10, y: 2 } // OK\n * hero.location.x = 7 // Not ok!\n * ```\n *\n * ```ts\n * type Point = { x: number, y: number }\n * const Mouse = types.model({\n * loc: types.frozen()\n * })\n * ```\n *\n * @param defaultValueOrType\n * @returns\n */\nfunction frozen(arg) {\n if (arguments.length === 0)\n return untypedFrozenInstance;\n else if (isType(arg))\n return new Frozen(arg);\n else\n return optional(untypedFrozenInstance, arg);\n}\n/**\n * Returns if a given value represents a frozen type.\n *\n * @param type\n * @returns\n */\nfunction isFrozenType(type) {\n return isType(type) && (type.flags & TypeFlags.Frozen) > 0;\n}\n\nfunction getInvalidationCause(hook) {\n switch (hook) {\n case Hook.beforeDestroy:\n return \"destroy\";\n case Hook.beforeDetach:\n return \"detach\";\n default:\n return undefined;\n }\n}\nvar StoredReference = /** @class */ (function () {\n function StoredReference(value, targetType) {\n Object.defineProperty(this, \"targetType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: targetType\n });\n Object.defineProperty(this, \"identifier\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"node\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"resolvedReference\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (isValidIdentifier(value)) {\n this.identifier = value;\n }\n else if (isStateTreeNode(value)) {\n var targetNode = getStateTreeNode(value);\n if (!targetNode.identifierAttribute)\n throw fail(\"Can only store references with a defined identifier attribute.\");\n var id = targetNode.unnormalizedIdentifier;\n if (id === null || id === undefined) {\n throw fail(\"Can only store references to tree nodes with a defined identifier.\");\n }\n this.identifier = id;\n }\n else {\n throw fail(\"Can only store references to tree nodes or identifiers, got: '\" + value + \"'\");\n }\n }\n Object.defineProperty(StoredReference.prototype, \"updateResolvedReference\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n var normalizedId = normalizeIdentifier(this.identifier);\n var root = node.root;\n var lastCacheModification = root.identifierCache.getLastCacheModificationPerId(normalizedId);\n if (!this.resolvedReference ||\n this.resolvedReference.lastCacheModification !== lastCacheModification) {\n var targetType = this.targetType;\n // reference was initialized with the identifier of the target\n var target = root.identifierCache.resolve(targetType, normalizedId);\n if (!target) {\n throw new InvalidReferenceError(\"[mobx-state-tree] Failed to resolve reference '\" + this.identifier + \"' to type '\" + this.targetType.name + \"' (from node: \" + node.path + \")\");\n }\n this.resolvedReference = {\n node: target,\n lastCacheModification: lastCacheModification\n };\n }\n }\n });\n Object.defineProperty(StoredReference.prototype, \"resolvedValue\", {\n get: function () {\n this.updateResolvedReference(this.node);\n return this.resolvedReference.node.value;\n },\n enumerable: false,\n configurable: true\n });\n return StoredReference;\n}());\n/**\n * @internal\n * @hidden\n */\nvar InvalidReferenceError = /** @class */ (function (_super) {\n __extends(InvalidReferenceError, _super);\n function InvalidReferenceError(m) {\n var _this = _super.call(this, m) || this;\n Object.setPrototypeOf(_this, InvalidReferenceError.prototype);\n return _this;\n }\n return InvalidReferenceError;\n}(Error));\n/**\n * @internal\n * @hidden\n */\nvar BaseReferenceType = /** @class */ (function (_super) {\n __extends(BaseReferenceType, _super);\n function BaseReferenceType(targetType, onInvalidated) {\n var _this = _super.call(this, \"reference(\" + targetType.name + \")\") || this;\n Object.defineProperty(_this, \"targetType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: targetType\n });\n Object.defineProperty(_this, \"onInvalidated\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: onInvalidated\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Reference\n });\n return _this;\n }\n Object.defineProperty(BaseReferenceType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return this.name;\n }\n });\n Object.defineProperty(BaseReferenceType.prototype, \"isAssignableFrom\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (type) {\n return this.targetType.isAssignableFrom(type);\n }\n });\n Object.defineProperty(BaseReferenceType.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n return isValidIdentifier(value)\n ? typeCheckSuccess()\n : typeCheckFailure(context, value, \"Value is not a valid identifier, which is a string or a number\");\n }\n });\n Object.defineProperty(BaseReferenceType.prototype, \"fireInvalidated\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (cause, storedRefNode, referenceId, refTargetNode) {\n // to actually invalidate a reference we need an alive parent,\n // since it is a scalar value (immutable-ish) and we need to change it\n // from the parent\n var storedRefParentNode = storedRefNode.parent;\n if (!storedRefParentNode || !storedRefParentNode.isAlive) {\n return;\n }\n var storedRefParentValue = storedRefParentNode.storedValue;\n if (!storedRefParentValue) {\n return;\n }\n this.onInvalidated({\n cause: cause,\n parent: storedRefParentValue,\n invalidTarget: refTargetNode ? refTargetNode.storedValue : undefined,\n invalidId: referenceId,\n replaceRef: function (newRef) {\n applyPatch(storedRefNode.root.storedValue, {\n op: \"replace\",\n value: newRef,\n path: storedRefNode.path\n });\n },\n removeRef: function () {\n if (isModelType(storedRefParentNode.type)) {\n this.replaceRef(undefined);\n }\n else {\n applyPatch(storedRefNode.root.storedValue, {\n op: \"remove\",\n path: storedRefNode.path\n });\n }\n }\n });\n }\n });\n Object.defineProperty(BaseReferenceType.prototype, \"addTargetNodeWatcher\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (storedRefNode, referenceId) {\n var _this = this;\n // this will make sure the target node becomes created\n var refTargetValue = this.getValue(storedRefNode);\n if (!refTargetValue) {\n return undefined;\n }\n var refTargetNode = getStateTreeNode(refTargetValue);\n var hookHandler = function (_, refTargetNodeHook) {\n var cause = getInvalidationCause(refTargetNodeHook);\n if (!cause) {\n return;\n }\n _this.fireInvalidated(cause, storedRefNode, referenceId, refTargetNode);\n };\n var refTargetDetachHookDisposer = refTargetNode.registerHook(Hook.beforeDetach, hookHandler);\n var refTargetDestroyHookDisposer = refTargetNode.registerHook(Hook.beforeDestroy, hookHandler);\n return function () {\n refTargetDetachHookDisposer();\n refTargetDestroyHookDisposer();\n };\n }\n });\n Object.defineProperty(BaseReferenceType.prototype, \"watchTargetNodeForInvalidations\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (storedRefNode, identifier, customGetSet) {\n var _this = this;\n if (!this.onInvalidated) {\n return;\n }\n var onRefTargetDestroyedHookDisposer;\n // get rid of the watcher hook when the stored ref node is destroyed\n // detached is ignored since scalar nodes (where the reference resides) cannot be detached\n storedRefNode.registerHook(Hook.beforeDestroy, function () {\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer();\n }\n });\n var startWatching = function (sync) {\n // re-create hook in case the stored ref gets reattached\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer();\n }\n // make sure the target node is actually there and initialized\n var storedRefParentNode = storedRefNode.parent;\n var storedRefParentValue = storedRefParentNode && storedRefParentNode.storedValue;\n if (storedRefParentNode && storedRefParentNode.isAlive && storedRefParentValue) {\n var refTargetNodeExists = void 0;\n if (customGetSet) {\n refTargetNodeExists = !!customGetSet.get(identifier, storedRefParentValue);\n }\n else {\n refTargetNodeExists = storedRefNode.root.identifierCache.has(_this.targetType, normalizeIdentifier(identifier));\n }\n if (!refTargetNodeExists) {\n // we cannot change the reference in sync mode\n // since we are in the middle of a reconciliation/instantiation and the change would be overwritten\n // for those cases just let the wrong reference be assigned and fail upon usage\n // (like current references do)\n // this means that effectively this code will only run when it is created from a snapshot\n if (!sync) {\n _this.fireInvalidated(\"invalidSnapshotReference\", storedRefNode, identifier, null);\n }\n }\n else {\n onRefTargetDestroyedHookDisposer = _this.addTargetNodeWatcher(storedRefNode, identifier);\n }\n }\n };\n if (storedRefNode.state === NodeLifeCycle.FINALIZED) {\n // already attached, so the whole tree is ready\n startWatching(true);\n }\n else {\n if (!storedRefNode.isRoot) {\n // start watching once the whole tree is ready\n storedRefNode.root.registerHook(Hook.afterCreationFinalization, function () {\n // make sure to attach it so it can start listening\n if (storedRefNode.parent) {\n storedRefNode.parent.createObservableInstanceIfNeeded();\n }\n });\n }\n // start watching once the node is attached somewhere / parent changes\n storedRefNode.registerHook(Hook.afterAttach, function () {\n startWatching(false);\n });\n }\n }\n });\n return BaseReferenceType;\n}(SimpleType));\n/**\n * @internal\n * @hidden\n */\nvar IdentifierReferenceType = /** @class */ (function (_super) {\n __extends(IdentifierReferenceType, _super);\n function IdentifierReferenceType(targetType, onInvalidated) {\n return _super.call(this, targetType, onInvalidated) || this;\n }\n Object.defineProperty(IdentifierReferenceType.prototype, \"getValue\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (storedRefNode) {\n if (!storedRefNode.isAlive)\n return undefined;\n var storedRef = storedRefNode.storedValue;\n return storedRef.resolvedValue;\n }\n });\n Object.defineProperty(IdentifierReferenceType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (storedRefNode) {\n var ref = storedRefNode.storedValue;\n return ref.identifier;\n }\n });\n Object.defineProperty(IdentifierReferenceType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n var identifier = isStateTreeNode(initialValue) ? getIdentifier(initialValue) : initialValue;\n var storedRef = new StoredReference(initialValue, this.targetType);\n var storedRefNode = createScalarNode(this, parent, subpath, environment, storedRef);\n storedRef.node = storedRefNode;\n this.watchTargetNodeForInvalidations(storedRefNode, identifier, undefined);\n return storedRefNode;\n }\n });\n Object.defineProperty(IdentifierReferenceType.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n if (!current.isDetaching && current.type === this) {\n var compareByValue = isStateTreeNode(newValue);\n var ref = current.storedValue;\n if ((!compareByValue && ref.identifier === newValue) ||\n (compareByValue && ref.resolvedValue === newValue)) {\n current.setParent(parent, subpath);\n return current;\n }\n }\n var newNode = this.instantiate(parent, subpath, undefined, newValue);\n current.die(); // noop if detaching\n return newNode;\n }\n });\n return IdentifierReferenceType;\n}(BaseReferenceType));\n/**\n * @internal\n * @hidden\n */\nvar CustomReferenceType = /** @class */ (function (_super) {\n __extends(CustomReferenceType, _super);\n function CustomReferenceType(targetType, options, onInvalidated) {\n var _this = _super.call(this, targetType, onInvalidated) || this;\n Object.defineProperty(_this, \"options\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: options\n });\n return _this;\n }\n Object.defineProperty(CustomReferenceType.prototype, \"getValue\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (storedRefNode) {\n if (!storedRefNode.isAlive)\n return undefined;\n var referencedNode = this.options.get(storedRefNode.storedValue, storedRefNode.parent ? storedRefNode.parent.storedValue : null);\n return referencedNode;\n }\n });\n Object.defineProperty(CustomReferenceType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (storedRefNode) {\n return storedRefNode.storedValue;\n }\n });\n Object.defineProperty(CustomReferenceType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, newValue) {\n var identifier = isStateTreeNode(newValue)\n ? this.options.set(newValue, parent ? parent.storedValue : null)\n : newValue;\n var storedRefNode = createScalarNode(this, parent, subpath, environment, identifier);\n this.watchTargetNodeForInvalidations(storedRefNode, identifier, this.options);\n return storedRefNode;\n }\n });\n Object.defineProperty(CustomReferenceType.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n var newIdentifier = isStateTreeNode(newValue)\n ? this.options.set(newValue, current ? current.storedValue : null)\n : newValue;\n if (!current.isDetaching && current.type === this && current.storedValue === newIdentifier) {\n current.setParent(parent, subpath);\n return current;\n }\n var newNode = this.instantiate(parent, subpath, undefined, newIdentifier);\n current.die(); // noop if detaching\n return newNode;\n }\n });\n return CustomReferenceType;\n}(BaseReferenceType));\n/**\n * `types.reference` - Creates a reference to another type, which should have defined an identifier.\n * See also the [reference and identifiers](https://github.com/mobxjs/mobx-state-tree#references-and-identifiers) section.\n */\nfunction reference(subType, options) {\n assertIsType(subType, 1);\n if (devMode()) {\n if (arguments.length === 2 && typeof arguments[1] === \"string\") {\n // istanbul ignore next\n throw fail(\"References with base path are no longer supported. Please remove the base path.\");\n }\n }\n var getSetOptions = options ? options : undefined;\n var onInvalidated = options\n ? options.onInvalidated\n : undefined;\n if (getSetOptions && (getSetOptions.get || getSetOptions.set)) {\n if (devMode()) {\n if (!getSetOptions.get || !getSetOptions.set) {\n throw fail(\"reference options must either contain both a 'get' and a 'set' method or none of them\");\n }\n }\n return new CustomReferenceType(subType, {\n get: getSetOptions.get,\n set: getSetOptions.set\n }, onInvalidated);\n }\n else {\n return new IdentifierReferenceType(subType, onInvalidated);\n }\n}\n/**\n * Returns if a given value represents a reference type.\n *\n * @param type\n * @returns\n */\nfunction isReferenceType(type) {\n return (type.flags & TypeFlags.Reference) > 0;\n}\n/**\n * `types.safeReference` - A safe reference is like a standard reference, except that it accepts the undefined value by default\n * and automatically sets itself to undefined (when the parent is a model) / removes itself from arrays and maps\n * when the reference it is pointing to gets detached/destroyed.\n *\n * The optional options parameter object accepts a parameter named `acceptsUndefined`, which is set to true by default, so it is suitable\n * for model properties.\n * When used inside collections (arrays/maps), it is recommended to set this option to false so it can't take undefined as value,\n * which is usually the desired in those cases.\n * Additionally, the optional options parameter object accepts a parameter named `onInvalidated`, which will be called when the reference target node that the reference is pointing to is about to be detached/destroyed\n *\n * Strictly speaking it is a `types.maybe(types.reference(X))` (when `acceptsUndefined` is set to true, the default) and\n * `types.reference(X)` (when `acceptsUndefined` is set to false), both of them with a customized `onInvalidated` option.\n *\n * @param subType\n * @param options\n * @returns\n */\nfunction safeReference(subType, options) {\n var refType = reference(subType, __assign(__assign({}, options), { onInvalidated: function (ev) {\n if (options && options.onInvalidated) {\n options.onInvalidated(ev);\n }\n ev.removeRef();\n } }));\n if (options && options.acceptsUndefined === false) {\n return refType;\n }\n else {\n return maybe(refType);\n }\n}\n\nvar BaseIdentifierType = /** @class */ (function (_super) {\n __extends(BaseIdentifierType, _super);\n function BaseIdentifierType(name, validType) {\n var _this = _super.call(this, name) || this;\n Object.defineProperty(_this, \"validType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: validType\n });\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Identifier\n });\n return _this;\n }\n Object.defineProperty(BaseIdentifierType.prototype, \"instantiate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (parent, subpath, environment, initialValue) {\n if (!parent || !(parent.type instanceof ModelType))\n throw fail(\"Identifier types can only be instantiated as direct child of a model type\");\n return createScalarNode(this, parent, subpath, environment, initialValue);\n }\n });\n Object.defineProperty(BaseIdentifierType.prototype, \"reconcile\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (current, newValue, parent, subpath) {\n // we don't consider detaching here since identifier are scalar nodes, and scalar nodes cannot be detached\n if (current.storedValue !== newValue)\n throw fail(\"Tried to change identifier from '\" + current.storedValue + \"' to '\" + newValue + \"'. Changing identifiers is not allowed.\");\n current.setParent(parent, subpath);\n return current;\n }\n });\n Object.defineProperty(BaseIdentifierType.prototype, \"isValidSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (value, context) {\n if (typeof value !== this.validType) {\n return typeCheckFailure(context, value, \"Value is not a valid \" + this.describe() + \", expected a \" + this.validType);\n }\n return typeCheckSuccess();\n }\n });\n return BaseIdentifierType;\n}(SimpleType));\n/**\n * @internal\n * @hidden\n */\nvar IdentifierType = /** @class */ (function (_super) {\n __extends(IdentifierType, _super);\n function IdentifierType() {\n var _this = _super.call(this, \"identifier\", \"string\") || this;\n Object.defineProperty(_this, \"flags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: TypeFlags.Identifier\n });\n return _this;\n }\n Object.defineProperty(IdentifierType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return \"identifier\";\n }\n });\n return IdentifierType;\n}(BaseIdentifierType));\n/**\n * @internal\n * @hidden\n */\nvar IdentifierNumberType = /** @class */ (function (_super) {\n __extends(IdentifierNumberType, _super);\n function IdentifierNumberType() {\n return _super.call(this, \"identifierNumber\", \"number\") || this;\n }\n Object.defineProperty(IdentifierNumberType.prototype, \"getSnapshot\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (node) {\n return node.storedValue;\n }\n });\n Object.defineProperty(IdentifierNumberType.prototype, \"describe\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n return \"identifierNumber\";\n }\n });\n return IdentifierNumberType;\n}(BaseIdentifierType));\n/**\n * `types.identifier` - Identifiers are used to make references, lifecycle events and reconciling works.\n * Inside a state tree, for each type can exist only one instance for each given identifier.\n * For example there couldn't be 2 instances of user with id 1. If you need more, consider using references.\n * Identifier can be used only as type property of a model.\n * This type accepts as parameter the value type of the identifier field that can be either string or number.\n *\n * Example:\n * ```ts\n * const Todo = types.model(\"Todo\", {\n * id: types.identifier,\n * title: types.string\n * })\n * ```\n *\n * @returns\n */\nvar identifier = new IdentifierType();\n/**\n * `types.identifierNumber` - Similar to `types.identifier`. This one will serialize from / to a number when applying snapshots\n *\n * Example:\n * ```ts\n * const Todo = types.model(\"Todo\", {\n * id: types.identifierNumber,\n * title: types.string\n * })\n * ```\n *\n * @returns\n */\nvar identifierNumber = new IdentifierNumberType();\n/**\n * Returns if a given value represents an identifier type.\n *\n * @param type\n * @returns\n */\nfunction isIdentifierType(type) {\n return isType(type) && (type.flags & TypeFlags.Identifier) > 0;\n}\n/**\n * @internal\n * @hidden\n */\nfunction normalizeIdentifier(id) {\n return \"\" + id;\n}\n/**\n * @internal\n * @hidden\n */\nfunction isValidIdentifier(id) {\n return typeof id === \"string\" || typeof id === \"number\";\n}\n/**\n * @internal\n * @hidden\n */\nfunction assertIsValidIdentifier(id, argNumber) {\n assertArg(id, isValidIdentifier, \"string or number (identifier)\", argNumber);\n}\n\n/**\n * `types.custom` - Creates a custom type. Custom types can be used for arbitrary immutable values, that have a serializable representation. For example, to create your own Date representation, Decimal type etc.\n *\n * The signature of the options is:\n * ```ts\n * export interface CustomTypeOptions