{"version":3,"sources":["webpack:///./node_modules/mobx-state-tree/dist/mobx-state-tree.module.js"],"names":["Hook","livelinessChecking","getLivelinessChecking","extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","__assign","assign","t","s","i","n","arguments","length","call","apply","__decorate","decorators","target","key","desc","c","r","getOwnPropertyDescriptor","Reflect","decorate","defineProperty","__values","o","Symbol","iterator","m","next","value","done","TypeError","__read","e","ar","push","error","__spread","concat","getType","object","assertIsStateTreeNode","getStateTreeNode","type","onPatch","callback","assertIsFunction","applyPatch","patch","assertArg","applyPatches","asArray","getSnapshot","applyPostProcess","node","snapshot","freeze","getRoot","root","storedValue","TypeFlags","BaseNode","parent","subpath","environment","_state","NodeLifeCycle","INITIALIZING","baseSetParent","get","_subpath","enumerable","configurable","_subpathUponDeath","_pathUponDeath","getValue","set","val","wasAlive","isAlive","aliveAtom","reportChanged","fireInternalHook","name","_hookSubscribers","emit","registerHook","hook","hookHandler","EventHandlers","register","_parent","_escapedSubpath","undefined","pathAtom","getEscapedPath","reportObserved","escapeJsonPath","state","DEAD","DETACHING","baseFinalizeCreation","whenFinalized","CREATED","FINALIZED","fireHook","afterAttach","baseFinalizeDeath","clearAll","baseAboutToDie","beforeDestroy","ScalarNode","_super","simpleType","initialSnapshot","_this","createNewInstance","finalizeCreation","fail$1","setParent","newParent","parentChanged","subpathChanged","toString","path","pathUponDeath","die","aboutToDie","finalizeDeath","nextNodeId","snapshotReactionOptions","onError","ObjectNode","complexType","initialValue","nodeId","isProtectionEnabled","_autoUnbox","_isRunningAction","_hasSnapshotReaction","_observableInstanceState","_cachedInitialSnapshotCreated","unbox","bind","_initialSnapshot","identifierAttribute","identifierCache","IdentifierCache","_childNodes","initializeChildNodes","identifier","unnormalizedIdentifier","id","childNode","normalizeIdentifier","addNodeToCache","patches","createObservableInstanceIfNeeded","_applyPatches","applySnapshot","_applySnapshot","createObservableInstance","e_1","_a","parentChain","unshift","parentChain_1","parentChain_1_1","e_1_1","return","propName","preboot","finalizeNewInstance","trackAndCompute","isRoot","_addSnapshotReaction","EMPTY_OBJECT","afterCreate","clearParent","beforeDetach","previousState","newEnv","newIdCache","splitCache","removeChild","mergeCache","fn","_getActualSnapshot","_getCachedInitialSnapshot","_snapshotUponDeath","childNodes","_cachedInitialSnapshot","processInitialSnapshot","isRunningAction","assertAlive","context","_getAssertAliveError","warnError","escapedPath","actionContext","getCurrentActionContext","parentActionEvent","actionFullPath","getChildNode","getChildren","convertChildNodesToArray","getChildType","propertyName","assertWritable","isProtected","subpathUponDeath","e_2","_b","_c","e_2_1","afterCreationFinalization","detach","self","createActionInvoker","forEach","parts","splitJsonPath","resolveNodeByPathParts","slice","applyPatchLocally","addHiddenFinalProp","toJSON","_internalEventsEmit","_internalEventsClear","notifyDied","_internalEventsClearAll","onSnapshot","onChange","_internalEventsRegister","emitSnapshot","handler","emitPatch","basePatch","source","_internalEventsHasSubscribers","stripPatch","invertPatch","splitPatch","a","_i","current","extend","substr","reversePatch","hasDisposer","disposer","_internalEventsHas","addDisposer","removeDisposer","_internalEventsUnregister","removeMiddleware","middleware","middlewares","index","indexOf","splice","addMiddleWare","includeHooks","snapshotDisposer","event","_internalEvents","hasSubscribers","eventHandler","atTheBeginning","has","unregister","args","clear","BaseType","isType","typecheckInternal","instantiate","isAssignableFrom","validate","getStateTreeNodeSafe","valueType","typeCheckSuccess","typeCheckFailure","isValidSnapshot","is","thing","ComplexType","getDefaultSnapshot","tryToReconcileNode","newValue","isDetaching","isStateTreeNode","isMutable","reconcile","newNode","getSubTypes","SimpleType","res","assertIsType","argNumber","Map","RunningAction","hooks","flowsPending","running","onStart","finish","onFinish","incFlowsPending","decFlowsPending","currentActionContext","nextActionId","getNextActionId","runWithActionContext","baseIsRunningAction","previousContext","baseCall","originalFn","CollectedMiddlewares","isEmpty","result","runNextMiddleware","getNextMiddleware","call2","runMiddleWares","getParentActionContext","parentContext","parentActionContext","argsToArray","tree","rootId","parentId","allParentIds","parentEvent","_isMSTAction","arrayIndex","inArrayIndex","$mst_middleware","array","item","prettyPrintValue","JSON","stringify","safeStringify","toErrorString","fullPath","map","filter","join","pathPrefix","currentTypename","isPrimitive","isSnapshotCompatible","message","flags","String","Number","Integer","Boolean","Date","isPrimitiveType","describe","getContextForPath","EMPTY_ARRAY","flattenTypeErrors","errors","reduce","process","ENABLE_TYPE_CHECK","valueInString","substring","validationErrorsToString","typecheck","identifierCacheId","cacheId","cache","lastCacheModificationPerId","updateLastCacheModificationPerId","lcm","getLastCacheModificationPerId","modificationId","lastCacheUpdate","mobxShallow","nodes","child","remove","delete","basePath","modified","some","candidate","resolve","matches","createObjectNode","existingNode","createScalarNode","$treenode","base","pathParts","failIfResolveFails","part","joinJsonPath","keys","deep","proxy","Error","identity","_","isInteger","isFinite","Math","floor","isArray","isPlainObject","proto","getPrototypeOf","RegExp","includeDate","writable","EventHandler","handlers","f","eventHandlers","stringStartsWith","str","beginning","deprecated","msg","console","warn","typeName","assertIsString","canBeEmpty","op","oldValue","replace","unescapeJsonPath","getPathStr","split","shift","ids","SnapshotProcessor","_subtype","_processors","preProcessSnapshot","sn","preProcessor","postProcessSnapshot","postProcessor","_fixNode","nodeType","snapshotProcessorType","methods","methods_1","methods_1_1","method","proxyNodeTypeMethods","oldGetSnapshot","processedInitialValue","processedSn","MapIdentifierMode","needsIdentifierError","MSTMap","initialData","ref","enhancer","put","mapNode","mapType","identifierMode","YES","mapIdentifierAttribute","isValidIdentifier","MapType","_subType","hookInitializers","UNKNOWN","_determineIdentifierMode","modelTypes","tryCollectModelTypes","subtypes","subtypesArray","subtypesArray_1","subtypesArray_1_1","ModelType","identifierAttribute_1","NO","objNode","subType","instance","initializer","actionInvoker","willChange","didChange","change","processIdentifier","expected","processed","oldSnapshot","currentKeys","from","ArrayType","dehancer","updatedNodes","reconcileArrayChildren","index_1","removedCount","added","addedNodes","removed","addedCount","childType","oldNodes","newValues","newPaths","nothingChanged","hasNewNode","oldNode","newPath","areSame","valueAsNode","oldMatch","j","getNewNode","objectTypeToString","defaultObjectOptions","properties","initializers","toPropertiesObject","declaredProps","props","descriptor","optional","string","number","boolean","DatePrimitive","getPrimitiveFactoryFromValue","opts","named","cloneAndEnhance","currentPreprocessor","currentPostprocessor","propertyNames","_getIdentifierAttribute","forAllProps","propType","Identifier","actions","instantiateActions","action2","baseAction","specializedAction_1","boundAction","volatile","instantiateVolatileState","views","rest","getOwnPropertySymbols","propertyIsEnumerable","__rest","instantiateViews","computedValue","derivation","scope","setter","applySnapshotPreProcessor","chg","oldChildValue","applySnapshotPostProcessor","preProcessedSnapshot","processor","isModelType","CoreType","checker","v","integer","nullType","Null","undefinedType","Undefined","_DatePrimitive","getTime","Literal","literal","Refinement","_predicate","_message","subtypeErrors","Union","_types","options","_eager","eager","dispatcher","_dispatcher","factory","determineType","reconcileCurrentType","find","allErrors","applicableTypes","union","optionsOrType","otherTypes","types","OptionalValue","_defaultValue","optionalValues","Optional","defaultInstanceOrSnapshot","getDefaultInstanceOrSnapshot","defaultValueOrFunction","checkOptionalPreconditions","undefinedAsOptionalValues","optionalUndefinedType","optionalNullType","maybe","Late","_definition","getSubType","mustSucceed","ReferenceError","subtype","Frozen","isSerializable","untypedFrozenInstance","StoredReference","targetType","targetNode","updateResolvedReference","normalizedId","lastCacheModification","resolvedReference","InvalidReferenceError","BaseReferenceType","onInvalidated","Reference","fireInvalidated","cause","storedRefNode","referenceId","refTargetNode","storedRefParentNode","storedRefParentValue","invalidTarget","invalidId","replaceRef","newRef","removeRef","addTargetNodeWatcher","refTargetValue","refTargetNodeHook","getInvalidationCause","refTargetDetachHookDisposer","refTargetDestroyHookDisposer","watchTargetNodeForInvalidations","customGetSet","onRefTargetDestroyedHookDisposer","startWatching","sync","IdentifierReferenceType","resolvedValue","storedRef","compareByValue","CustomReferenceType","newIdentifier","reference","getSetOptions","BaseIdentifierType","validType","IdentifierType","IdentifierNumberType","identifierNumber","CustomType","Custom","isTargetType","typeError","getValidationMessage","toSnapshot","fromSnapshot","isSnapshot","valueToStore","enumeration","realOptions","option","model","compose","hasTypename","prev","cur","custom","safeReference","refType","ev","acceptsUndefined","maybeNull","refinement","predicate","frozen","arg","late","nameOrType","maybeType","null","snapshotProcessor","processors"],"mappings":"2HAAA,uFA2CIA,EA3CJ,YACIC,EAAqB,OAmBzB,SAASC,IACP,OAAOD,GAwBT,SAAWD,GACTA,EAAkB,YAAI,cACtBA,EAAkB,YAAI,cACtBA,EAAgC,0BAAI,4BACpCA,EAAmB,aAAI,eACvBA,EAAoB,cAAI,gBAL1B,CAMGA,IAASA,EAAO,KAmBnB,IAAIG,EAAgB,SAAUC,EAAGC,GAS/B,OARAF,EAAgBG,OAAOC,gBAAkB,CACvCC,UAAW,cACAC,OAAS,SAAUL,EAAGC,GACjCD,EAAEI,UAAYH,IACX,SAAUD,EAAGC,GAChB,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MAGhCN,EAAGC,IAG1B,SAASO,EAAUR,EAAGC,GAGpB,SAASQ,IACPC,KAAKC,YAAcX,EAHrBD,EAAcC,EAAGC,GAMjBD,EAAEY,UAAkB,OAANX,EAAaC,OAAOW,OAAOZ,IAAMQ,EAAGG,UAAYX,EAAEW,UAAW,IAAIH,GAGjF,IAAIK,EAAW,WAWb,OAVAA,EAAWZ,OAAOa,QAAU,SAAkBC,GAC5C,IAAK,IAAIC,EAAGC,EAAI,EAAGC,EAAIC,UAAUC,OAAQH,EAAIC,EAAGD,IAG9C,IAAK,IAAIZ,KAFTW,EAAIG,UAAUF,GAEOhB,OAAOU,UAAUL,eAAee,KAAKL,EAAGX,KAAIU,EAAEV,GAAKW,EAAEX,IAG5E,OAAOU,IAGOO,MAAMb,KAAMU,YAc9B,SAASI,EAAWC,EAAYC,EAAQC,EAAKC,GAC3C,IAEI5B,EAFA6B,EAAIT,UAAUC,OACdS,EAAID,EAAI,EAAIH,EAAkB,OAATE,EAAgBA,EAAO1B,OAAO6B,yBAAy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AQA,GACR0C,QAASA,GACTzN,KAAMiL,GACN9L,IAvlFF,SAAaqR,GACX,OAAO,IAAItJ,GAAQ,eAAiBsJ,EAAQ5hB,KAAO,IAAK4hB,IAulFxD7R,MA/0EF,SAAe6R,GAEb,OADArU,EAAaqU,EAAS,GACf,IAAI1H,GAAU0H,EAAQ5hB,KAAO,KAAM4hB,IA80E1C4E,OAlvBF,SAAgBC,GACd,OAAyB,IAArBprB,UAAUC,OAAqBymB,GAA+BhW,EAAO0a,GAAa,IAAI5E,GAAO4E,GAAiBxK,GAAS8F,GAAuB0E,IAkvBlJtiB,WAAYA,GACZ2gB,iBAAkBA,GAClB4B,KA51BF,SAAcC,EAAYC,GACxB,IAAI5mB,EAA6B,iBAAf2mB,EAA0BA,EAAa,QAAUA,EAAWnkB,WAAa,IACvFhF,EAA6B,iBAAfmpB,EAA0BC,EAAYD,EAMxD,OAAO,IAAIpF,GAAKvhB,EAAMxC,IAq1BtBkD,UAAWse,GACX6H,KAAM/H,GACNgI,kBAxhGF,SAA2BtpB,EAAMupB,EAAY/mB,GAe3C,OAdAuN,EAAa/P,EAAM,GAcZ,IAAI8Y,GAAkB9Y,EAAMupB,EAAY/mB,O","file":"4c4ba9aa-26ae688162c62546c2a7.js","sourcesContent":["import { isComputedProp, isObservableProp, createAtom, action, _allowStateChangesInsideComputed, reaction, computed, runInAction, observable, values, entries, isObservableArray, $mobx, getAtom, ObservableMap, _interceptReads, intercept, observe, _getAdministration, set } from 'mobx';\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 */\n\nfunction setLivelinessChecking(mode) {\n livelinessChecking = mode;\n}\n/**\n * Returns the current liveliness checking mode.\n *\n * @returns `\"warn\"`, `\"error\"` or `\"ignore\"`\n */\n\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 */\n\n\nfunction setLivelynessChecking(mode) {\n setLivelinessChecking(mode);\n}\n/**\n * @hidden\n */\n\n\nvar Hook;\n\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/*! *****************************************************************************\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***************************************************************************** */\n\n/* global Reflect, Promise */\n\n\nvar extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf || {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n };\n\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n extendStatics(d, b);\n\n function __() {\n this.constructor = d;\n }\n\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nvar __assign = function () {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n\n return t;\n };\n\n return __assign.apply(this, arguments);\n};\n\nfunction __rest(s, e) {\n var t = {};\n\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];\n\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nfunction __decorate(decorators, target, key, desc) {\n var c = arguments.length,\n r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,\n d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nfunction __generator(thisArg, body) {\n var _ = {\n label: 0,\n sent: function () {\n if (t[0] & 1) throw t[1];\n return t[1];\n },\n trys: [],\n ops: []\n },\n f,\n y,\n t,\n g;\n return g = {\n next: verb(0),\n \"throw\": verb(1),\n \"return\": verb(2)\n }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function () {\n return this;\n }), g;\n\n function verb(n) {\n return function (v) {\n return step([n, v]);\n };\n }\n\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n\n while (_) try {\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;\n if (y = 0, t) op = [op[0] & 2, t.value];\n\n switch (op[0]) {\n case 0:\n case 1:\n t = op;\n break;\n\n case 4:\n _.label++;\n return {\n value: op[1],\n done: false\n };\n\n case 5:\n _.label++;\n y = op[1];\n op = [0];\n continue;\n\n case 7:\n op = _.ops.pop();\n\n _.trys.pop();\n\n continue;\n\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {\n _ = 0;\n continue;\n }\n\n if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {\n _.label = op[1];\n break;\n }\n\n if (op[0] === 6 && _.label < t[1]) {\n _.label = t[1];\n t = op;\n break;\n }\n\n if (t && _.label < t[2]) {\n _.label = t[2];\n\n _.ops.push(op);\n\n break;\n }\n\n if (t[2]) _.ops.pop();\n\n _.trys.pop();\n\n continue;\n }\n\n op = body.call(thisArg, _);\n } catch (e) {\n op = [6, e];\n y = 0;\n } finally {\n f = t = 0;\n }\n\n if (op[0] & 5) throw op[1];\n return {\n value: op[0] ? op[1] : void 0,\n done: true\n };\n }\n}\n\nfunction __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator,\n m = s && o[s],\n i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return {\n value: o && o[i++],\n done: !o\n };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nfunction __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o),\n r,\n ar = [],\n e;\n\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n } catch (error) {\n e = {\n error: error\n };\n } finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n } finally {\n if (e) throw e.error;\n }\n }\n\n return ar;\n}\n\nfunction __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n\n return ar;\n}\n/**\n * Returns the _actual_ type of the given tree node. (Or throws)\n *\n * @param object\n * @returns\n */\n\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 */\n\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 deep 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 */\n\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 */\n\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 */\n\n\nfunction applyPatch(target, patch) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertArg(patch, function (p) {\n return typeof p === \"object\";\n }, \"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 an 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 */\n\n\nfunction recordPatches(subject, filter) {\n // check all arguments\n assertIsStateTreeNode(subject, 1);\n var data = {\n patches: [],\n reversedInversePatches: []\n }; // we will generate the immutable copy of patches on demand for public consumption\n\n var publicData = {};\n var disposer;\n var recorder = {\n get recording() {\n return !!disposer;\n },\n\n get patches() {\n if (!publicData.patches) {\n publicData.patches = data.patches.slice();\n }\n\n return publicData.patches;\n },\n\n get reversedInversePatches() {\n if (!publicData.reversedInversePatches) {\n publicData.reversedInversePatches = data.reversedInversePatches.slice();\n }\n\n return publicData.reversedInversePatches;\n },\n\n get inversePatches() {\n if (!publicData.inversePatches) {\n publicData.inversePatches = data.reversedInversePatches.slice().reverse();\n }\n\n return publicData.inversePatches;\n },\n\n stop: function () {\n if (disposer) {\n disposer();\n disposer = undefined;\n }\n },\n resume: function () {\n if (disposer) 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\n data.patches.push(patch);\n data.reversedInversePatches.unshift(inversePatch); // mark immutable public patches as dirty\n\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.reversedInversePatches);\n }\n };\n recorder.resume();\n return recorder;\n}\n/**\n * The inverse of `unprotect`.\n *\n * @param target\n */\n\n\nfunction protect(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (!node.isRoot) throw fail$1(\"`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 */\n\n\nfunction unprotect(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (!node.isRoot) throw fail$1(\"`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 */\n\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 */\n\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 */\n\n\nfunction getSnapshot(target, applyPostProcess) {\n if (applyPostProcess === void 0) {\n applyPostProcess = true;\n } // check all arguments\n\n\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (applyPostProcess) 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 */\n\n\nfunction hasParent(target, depth) {\n if (depth === void 0) {\n depth = 1;\n } // check all arguments\n\n\n assertIsStateTreeNode(target, 1);\n assertIsNumber(depth, 2, 0);\n var parent = getStateTreeNode(target).parent;\n\n while (parent) {\n if (--depth === 0) return true;\n parent = parent.parent;\n }\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 */\n\n\nfunction getParent(target, depth) {\n if (depth === void 0) {\n depth = 1;\n } // check all arguments\n\n\n assertIsStateTreeNode(target, 1);\n assertIsNumber(depth, 2, 0);\n var d = depth;\n var parent = getStateTreeNode(target).parent;\n\n while (parent) {\n if (--d === 0) return parent.storedValue;\n parent = parent.parent;\n }\n\n throw fail$1(\"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 */\n\n\nfunction hasParentOfType(target, type) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsType(type, 2);\n var parent = getStateTreeNode(target).parent;\n\n while (parent) {\n if (type.is(parent.storedValue)) return true;\n parent = parent.parent;\n }\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 */\n\n\nfunction getParentOfType(target, type) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsType(type, 2);\n var parent = getStateTreeNode(target).parent;\n\n while (parent) {\n if (type.is(parent.storedValue)) return parent.storedValue;\n parent = parent.parent;\n }\n\n throw fail$1(\"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 */\n\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 */\n\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 */\n\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 */\n\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 */\n\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 */\n\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 ? node.value : undefined;\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 */\n\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 it 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 */\n\n\nfunction tryReference(getter, checkIfAlive) {\n if (checkIfAlive === void 0) {\n checkIfAlive = true;\n }\n\n try {\n var node = getter();\n\n if (node === undefined || node === null) {\n return undefined;\n } else if (isStateTreeNode(node)) {\n if (!checkIfAlive) {\n return node;\n } else {\n return isAlive(node) ? node : undefined;\n }\n } else {\n throw fail$1(\"The reference to be checked is not one of node, null or undefined\");\n }\n } catch (e) {\n if (e instanceof InvalidReferenceError) {\n return undefined;\n }\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 */\n\n\nfunction isValidReference(getter, checkIfAlive) {\n if (checkIfAlive === void 0) {\n checkIfAlive = true;\n }\n\n try {\n var node = getter();\n\n if (node === undefined || node === null) {\n return false;\n } else if (isStateTreeNode(node)) {\n return checkIfAlive ? isAlive(node) : true;\n } else {\n throw fail$1(\"The reference to be checked is not one of node, null or undefined\");\n }\n } catch (e) {\n if (e instanceof InvalidReferenceError) {\n return false;\n }\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 */\n\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) return undefined;\n\n try {\n return node.value;\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 */\n\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 * Short hand 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 */\n\n\nfunction clone(source, keepEnvironment) {\n if (keepEnvironment === void 0) {\n keepEnvironment = true;\n } // check all arguments\n\n\n assertIsStateTreeNode(source, 1);\n var node = getStateTreeNode(source);\n return node.type.create(node.snapshot, keepEnvironment === true ? node.root.environment : keepEnvironment === false ? undefined : 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 */\n\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 */\n\n\nfunction destroy(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n var node = getStateTreeNode(target);\n if (node.isRoot) node.die();else 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 */\n\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 */\n\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 */\n\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) return EMPTY_OBJECT;\n return env;\n}\n/**\n * Performs a depth first walk through a tree.\n */\n\n\nfunction walk(target, processor) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertIsFunction(processor, 2);\n var node = getStateTreeNode(target); // tslint:disable-next-line:no_unused-variable\n\n node.getChildren().forEach(function (child) {\n if (isStateTreeNode(child.storedValue)) 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 */\n\n\nfunction getPropertyMembers(typeOrNode) {\n var type;\n\n if (isStateTreeNode(typeOrNode)) {\n type = getType(typeOrNode);\n } else {\n type = typeOrNode;\n }\n\n assertArg(type, function (t) {\n return isModelType(t);\n }, \"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 and actions.\n *\n * @param target\n * @returns\n */\n\n\nfunction getMembers(target) {\n var type = getStateTreeNode(target).type;\n\n var reflected = __assign(__assign({}, getPropertyMembers(type)), {\n actions: [],\n volatile: [],\n views: []\n });\n\n var props = Object.getOwnPropertyNames(target);\n props.forEach(function (key) {\n if (key in reflected.properties) return;\n var descriptor = Object.getOwnPropertyDescriptor(target, key);\n\n if (descriptor.get) {\n if (isComputedProp(target, key)) reflected.views.push(key);else reflected.volatile.push(key);\n return;\n }\n\n if (descriptor.value._isMSTAction === true) reflected.actions.push(key);else if (isObservableProp(target, key)) reflected.volatile.push(key);else reflected.views.push(key);\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 casted as an instance\n */\n\n\nfunction cast(snapshotOrInstance) {\n return snapshotOrInstance;\n}\n/**\n * Casts a node instance type to an 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 casted as an input (creation) snapshot\n */\n\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 refernence 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 refererence 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: castToReference(a)})\n * ```\n *\n * @param instance Instance\n * @returns The same object casted as an reference snapshot (string or number)\n */\n\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 */\n\n\nfunction getNodeId(target) {\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).nodeId;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar BaseNode =\n/** @class */\nfunction () {\n function BaseNode(type, parent, subpath, environment) {\n this.type = type;\n this.environment = environment;\n this._state = NodeLifeCycle.INITIALIZING;\n this.environment = environment;\n this.baseSetParent(parent, subpath);\n }\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\n if (this.aliveAtom && wasAlive !== isAlive) {\n this.aliveAtom.reportChanged();\n }\n },\n enumerable: false,\n configurable: true\n });\n\n BaseNode.prototype.fireInternalHook = function (name) {\n if (this._hookSubscribers) {\n this._hookSubscribers.emit(name, this, name);\n }\n };\n\n BaseNode.prototype.registerHook = function (hook, hookHandler) {\n if (!this._hookSubscribers) {\n this._hookSubscribers = new EventHandlers();\n }\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\n BaseNode.prototype.baseSetParent = function (parent, subpath) {\n this._parent = parent;\n this._subpath = subpath;\n this._escapedSubpath = undefined; // regenerate when needed\n\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\n BaseNode.prototype.getEscapedPath = function (reportObserved) {\n if (reportObserved) {\n if (!this.pathAtom) {\n this.pathAtom = createAtom(\"path\");\n }\n\n this.pathAtom.reportObserved();\n }\n\n if (!this.parent) return \"\"; // regenerate escaped subpath if needed\n\n if (this._escapedSubpath === undefined) {\n this._escapedSubpath = !this._subpath ? \"\" : escapeJsonPath(this._subpath);\n }\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\n this.aliveAtom.reportObserved();\n return this.isAlive;\n },\n enumerable: false,\n configurable: true\n });\n\n BaseNode.prototype.baseFinalizeCreation = 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 } // goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already\n\n\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\n this.fireHook(Hook.afterAttach);\n }\n\n this.state = NodeLifeCycle.FINALIZED;\n\n if (whenFinalized) {\n whenFinalized();\n }\n }\n };\n\n BaseNode.prototype.baseFinalizeDeath = function () {\n if (this._hookSubscribers) {\n this._hookSubscribers.clearAll();\n }\n\n this._subpathUponDeath = this._subpath;\n this._pathUponDeath = this.getEscapedPath(false);\n this.baseSetParent(null, \"\");\n this.state = NodeLifeCycle.DEAD;\n };\n\n BaseNode.prototype.baseAboutToDie = function () {\n this.fireHook(Hook.beforeDestroy);\n };\n\n return BaseNode;\n}();\n/**\n * @internal\n * @hidden\n */\n\n\nvar ScalarNode =\n/** @class */\nfunction (_super) {\n __extends(ScalarNode, _super);\n\n function ScalarNode(simpleType, parent, subpath, environment, initialSnapshot) {\n var _this = _super.call(this, simpleType, parent, subpath, environment) || this;\n\n try {\n _this.storedValue = simpleType.createNewInstance(initialSnapshot);\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\n _this.state = NodeLifeCycle.CREATED; // 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\n _this.finalizeCreation();\n\n return _this;\n }\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) throw fail$1(\"This scalar node is not part of a tree\");\n return this.parent.root;\n },\n enumerable: false,\n configurable: true\n });\n\n ScalarNode.prototype.setParent = function (newParent, subpath) {\n var parentChanged = this.parent !== newParent;\n var subpathChanged = this.subpath !== subpath;\n\n if (!parentChanged && !subpathChanged) {\n return;\n }\n\n if (devMode()) {\n if (!subpath) {\n // istanbul ignore next\n throw fail$1(\"assertion failed: subpath expected\");\n }\n\n if (!newParent) {\n // istanbul ignore next\n throw fail$1(\"assertion failed: parent expected\");\n }\n\n if (parentChanged) {\n // istanbul ignore next\n throw fail$1(\"assertion failed: scalar nodes cannot change their parent\");\n }\n }\n\n this.environment = undefined; // use parent's\n\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\n ScalarNode.prototype.getSnapshot = function () {\n return this.type.getSnapshot(this);\n };\n\n ScalarNode.prototype.toString = function () {\n var path = (this.isAlive ? this.path : this.pathUponDeath) || \"\";\n return this.type.name + \"@\" + path + (this.isAlive ? \"\" : \" [dead]\");\n };\n\n ScalarNode.prototype.die = function () {\n if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) return;\n this.aboutToDie();\n this.finalizeDeath();\n };\n\n ScalarNode.prototype.finalizeCreation = function () {\n this.baseFinalizeCreation();\n };\n\n ScalarNode.prototype.aboutToDie = function () {\n this.baseAboutToDie();\n };\n\n ScalarNode.prototype.finalizeDeath = function () {\n this.baseFinalizeDeath();\n };\n\n ScalarNode.prototype.fireHook = function (name) {\n this.fireInternalHook(name);\n };\n\n __decorate([action], ScalarNode.prototype, \"die\", null);\n\n return ScalarNode;\n}(BaseNode);\n\nvar nextNodeId = 1;\nvar snapshotReactionOptions = {\n onError: function (e) {\n throw e;\n }\n};\n/**\n * @internal\n * @hidden\n */\n\nvar ObjectNode =\n/** @class */\nfunction (_super) {\n __extends(ObjectNode, _super);\n\n function ObjectNode(complexType, parent, subpath, environment, initialValue) {\n var _this = _super.call(this, complexType, parent, subpath, environment) || this;\n\n _this.nodeId = ++nextNodeId;\n _this.isProtectionEnabled = true;\n _this._autoUnbox = true; // unboxing is disabled when reading child nodes\n\n _this._isRunningAction = false; // only relevant for root\n\n _this._hasSnapshotReaction = false;\n _this._observableInstanceState = 0\n /* UNINITIALIZED */\n ;\n _this._cachedInitialSnapshotCreated = false;\n _this.unbox = _this.unbox.bind(_this);\n _this._initialSnapshot = freeze(initialValue);\n _this.identifierAttribute = complexType.identifierAttribute;\n\n if (!parent) {\n _this.identifierCache = new IdentifierCache();\n }\n\n _this._childNodes = complexType.initializeChildNodes(_this, _this._initialSnapshot); // identifier can not be changed during lifecycle of a node\n // so we safely can read it from initial snapshot\n\n _this.identifier = null;\n _this.unnormalizedIdentifier = null;\n\n if (_this.identifierAttribute && _this._initialSnapshot) {\n var id = _this._initialSnapshot[_this.identifierAttribute];\n\n if (id === undefined) {\n // try with the actual node if not (for optional identifiers)\n var childNode = _this._childNodes[_this.identifierAttribute];\n\n if (childNode) {\n id = childNode.value;\n }\n }\n\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw fail$1(\"Instance identifier '\" + _this.identifierAttribute + \"' for type '\" + _this.type.name + \"' must be a string or a number\");\n } // normalize internal identifier to string\n\n\n _this.identifier = normalizeIdentifier(id);\n _this.unnormalizedIdentifier = id;\n }\n\n if (!parent) {\n _this.identifierCache.addNodeToCache(_this);\n } else {\n parent.root.identifierCache.addNodeToCache(_this);\n }\n\n return _this;\n }\n\n ObjectNode.prototype.applyPatches = function (patches) {\n this.createObservableInstanceIfNeeded();\n\n this._applyPatches(patches);\n };\n\n ObjectNode.prototype.applySnapshot = function (snapshot) {\n this.createObservableInstanceIfNeeded();\n\n this._applySnapshot(snapshot);\n };\n\n ObjectNode.prototype.createObservableInstanceIfNeeded = function () {\n if (this._observableInstanceState === 0\n /* UNINITIALIZED */\n ) {\n this.createObservableInstance();\n }\n };\n\n ObjectNode.prototype.createObservableInstance = function () {\n var e_1, _a;\n\n if (devMode()) {\n if (this.state !== NodeLifeCycle.INITIALIZING) {\n // istanbul ignore next\n throw fail$1(\"assertion failed: the creation of the observable instance must be done on the initializing phase\");\n }\n }\n\n this._observableInstanceState = 1\n /* CREATING */\n ; // make sure the parent chain is created as well\n // array with parent chain from parent to child\n\n var parentChain = [];\n var parent = this.parent; // 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\n while (parent && parent._observableInstanceState === 0\n /* UNINITIALIZED */\n ) {\n parentChain.unshift(parent);\n parent = parent.parent;\n }\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 p.createObservableInstanceIfNeeded();\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (parentChain_1_1 && !parentChain_1_1.done && (_a = parentChain_1.return)) _a.call(parentChain_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n var type = this.type;\n\n try {\n this.storedValue = type.createNewInstance(this._childNodes);\n this.preboot();\n this._isRunningAction = true;\n type.finalizeNewInstance(this, this.storedValue);\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 } finally {\n this._isRunningAction = false;\n }\n\n this._observableInstanceState = 2\n /* CREATED */\n ; // NOTE: we need to touch snapshot, because non-observable\n // \"_observableInstanceState\" field was touched\n\n invalidateComputed(this, \"snapshot\");\n if (this.isRoot) this._addSnapshotReaction();\n this._childNodes = EMPTY_OBJECT;\n this.state = NodeLifeCycle.CREATED;\n this.fireHook(Hook.afterCreate);\n this.finalizeCreation();\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\n ObjectNode.prototype.clearParent = function () {\n if (!this.parent) return; // detach if attached\n\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\n try {\n this.parent.removeChild(this.subpath);\n this.baseSetParent(null, \"\");\n this.environment = newEnv;\n this.identifierCache = newIdCache;\n } finally {\n this.state = previousState;\n }\n };\n\n ObjectNode.prototype.setParent = function (newParent, subpath) {\n var parentChanged = newParent !== this.parent;\n var subpathChanged = subpath !== this.subpath;\n\n if (!parentChanged && !subpathChanged) {\n return;\n }\n\n if (devMode()) {\n if (!subpath) {\n // istanbul ignore next\n throw fail$1(\"assertion failed: subpath expected\");\n }\n\n if (!newParent) {\n // istanbul ignore next\n throw fail$1(\"assertion failed: new parent expected\");\n }\n\n if (this.parent && parentChanged) {\n throw fail$1(\"A node cannot exists twice in the state tree. Failed to add \" + this + \" to path '\" + newParent.path + \"/\" + subpath + \"'.\");\n }\n\n if (!this.parent && newParent.root === this) {\n throw fail$1(\"A state tree is not allowed to contain itself. Cannot assign \" + this + \" to path '\" + newParent.path + \"/\" + subpath + \"'\");\n }\n\n if (!this.parent && !!this.environment && this.environment !== newParent.root.environment) {\n throw fail$1(\"A state tree cannot be made part of another state tree as long as their environments are different.\");\n }\n }\n\n if (parentChanged) {\n // attach to new parent\n this.environment = undefined; // will use root's\n\n newParent.root.identifierCache.mergeCache(this);\n this.baseSetParent(newParent, subpath);\n this.fireHook(Hook.afterAttach);\n } else if (subpathChanged) {\n // moving to a new subpath on the same parent\n this.baseSetParent(this.parent, subpath);\n }\n };\n\n ObjectNode.prototype.fireHook = function (name) {\n var _this = this;\n\n this.fireInternalHook(name);\n var fn = this.storedValue && typeof this.storedValue === \"object\" && this.storedValue[name];\n\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 } 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 return freeze(this.getSnapshot());\n },\n enumerable: false,\n configurable: true\n }); // NOTE: we use this method to get snapshot without creating @computed overhead\n\n ObjectNode.prototype.getSnapshot = function () {\n if (!this.isAlive) return this._snapshotUponDeath;\n return this._observableInstanceState === 2\n /* CREATED */\n ? this._getActualSnapshot() : this._getCachedInitialSnapshot();\n };\n\n ObjectNode.prototype._getActualSnapshot = function () {\n return this.type.getSnapshot(this);\n };\n\n ObjectNode.prototype._getCachedInitialSnapshot = 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\n return this._cachedInitialSnapshot;\n };\n\n ObjectNode.prototype.isRunningAction = function () {\n if (this._isRunningAction) return true;\n if (this.isRoot) return false;\n return this.parent.isRunningAction();\n };\n\n ObjectNode.prototype.assertAlive = function (context) {\n var livelinessChecking = getLivelinessChecking();\n\n if (!this.isAlive && livelinessChecking !== \"ignore\") {\n var error = this._getAssertAliveError(context);\n\n switch (livelinessChecking) {\n case \"error\":\n throw fail$1(error);\n\n case \"warn\":\n warnError(error);\n }\n }\n };\n\n ObjectNode.prototype._getAssertAliveError = function (context) {\n var escapedPath = this.getEscapedPath(false) || this.pathUponDeath || \"\";\n var subpath = context.subpath && escapeJsonPath(context.subpath) || \"\";\n var actionContext = context.actionContext || getCurrentActionContext(); // try to use a real action context if possible since it includes the action name\n\n if (actionContext && actionContext.type !== \"action\" && actionContext.parentActionEvent) {\n actionContext = actionContext.parentActionEvent;\n }\n\n var actionFullPath = \"\";\n\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\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 ObjectNode.prototype.getChildNode = function (subpath) {\n this.assertAlive({\n subpath: subpath\n });\n this._autoUnbox = false;\n\n try {\n return this._observableInstanceState === 2\n /* CREATED */\n ? this.type.getChildNode(this, subpath) : this._childNodes[subpath];\n } finally {\n this._autoUnbox = true;\n }\n };\n\n ObjectNode.prototype.getChildren = function () {\n this.assertAlive(EMPTY_OBJECT);\n this._autoUnbox = false;\n\n try {\n return this._observableInstanceState === 2\n /* CREATED */\n ? this.type.getChildren(this) : convertChildNodesToArray(this._childNodes);\n } finally {\n this._autoUnbox = true;\n }\n };\n\n ObjectNode.prototype.getChildType = 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\n ObjectNode.prototype.assertWritable = function (context) {\n this.assertAlive(context);\n\n if (!this.isRunningAction() && this.isProtected) {\n throw fail$1(\"Cannot modify '\" + this + \"', the object is protected and can only be modified by using an action.\");\n }\n };\n\n ObjectNode.prototype.removeChild = function (subpath) {\n this.type.removeChild(this, subpath);\n }; // bound on the constructor\n\n\n ObjectNode.prototype.unbox = function (childNode) {\n if (!childNode) return childNode;\n this.assertAlive({\n subpath: childNode.subpath || childNode.subpathUponDeath\n });\n return this._autoUnbox ? childNode.value : childNode;\n };\n\n ObjectNode.prototype.toString = 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 ObjectNode.prototype.finalizeCreation = function () {\n var _this = this;\n\n this.baseFinalizeCreation(function () {\n var e_2, _a;\n\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 } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n _this.fireInternalHook(Hook.afterCreationFinalization);\n });\n };\n\n ObjectNode.prototype.detach = function () {\n if (!this.isAlive) throw fail$1(\"Error while detaching, node is not alive.\");\n this.clearParent();\n };\n\n ObjectNode.prototype.preboot = function () {\n var self = this;\n this._applyPatches = createActionInvoker(this.storedValue, \"@APPLY_PATCHES\", function (patches) {\n patches.forEach(function (patch) {\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) return; // else, apply it by calling the type logic\n\n return self.type.applySnapshot(self, snapshot);\n });\n addHiddenFinalProp(this.storedValue, \"$treenode\", this);\n addHiddenFinalProp(this.storedValue, \"toJSON\", toJSON);\n };\n\n ObjectNode.prototype.die = function () {\n if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) return;\n this.aboutToDie();\n this.finalizeDeath();\n };\n\n ObjectNode.prototype.aboutToDie = function () {\n if (this._observableInstanceState === 0\n /* UNINITIALIZED */\n ) {\n return;\n }\n\n this.getChildren().forEach(function (node) {\n node.aboutToDie();\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\n this.baseAboutToDie();\n\n this._internalEventsEmit(\"dispose\"\n /* Dispose */\n );\n\n this._internalEventsClear(\"dispose\"\n /* Dispose */\n );\n };\n\n ObjectNode.prototype.finalizeDeath = 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); // \"kill\" the computed prop and just store the last snapshot\n\n var snapshot = this.snapshot;\n this._snapshotUponDeath = snapshot;\n\n this._internalEventsClearAll();\n\n this.baseFinalizeDeath();\n };\n\n ObjectNode.prototype.onSnapshot = function (onChange) {\n this._addSnapshotReaction();\n\n return this._internalEventsRegister(\"snapshot\"\n /* Snapshot */\n , onChange);\n };\n\n ObjectNode.prototype.emitSnapshot = function (snapshot) {\n this._internalEventsEmit(\"snapshot\"\n /* Snapshot */\n , snapshot);\n };\n\n ObjectNode.prototype.onPatch = function (handler) {\n return this._internalEventsRegister(\"patch\"\n /* Patch */\n , handler);\n };\n\n ObjectNode.prototype.emitPatch = function (basePatch, source) {\n if (this._internalEventsHasSubscribers(\"patch\"\n /* Patch */\n )) {\n var localizedPatch = extend({}, basePatch, {\n path: source.path.substr(this.path.length) + \"/\" + basePatch.path // calculate the relative path of the patch\n\n });\n\n var _a = __read(splitPatch(localizedPatch), 2),\n patch = _a[0],\n reversePatch = _a[1];\n\n this._internalEventsEmit(\"patch\"\n /* Patch */\n , patch, reversePatch);\n }\n\n if (this.parent) this.parent.emitPatch(basePatch, source);\n };\n\n ObjectNode.prototype.hasDisposer = function (disposer) {\n return this._internalEventsHas(\"dispose\"\n /* Dispose */\n , disposer);\n };\n\n ObjectNode.prototype.addDisposer = function (disposer) {\n if (!this.hasDisposer(disposer)) {\n this._internalEventsRegister(\"dispose\"\n /* Dispose */\n , disposer, true);\n\n return;\n }\n\n throw fail$1(\"cannot add a disposer when it is already registered for execution\");\n };\n\n ObjectNode.prototype.removeDisposer = function (disposer) {\n if (!this._internalEventsHas(\"dispose\"\n /* Dispose */\n , disposer)) {\n throw fail$1(\"cannot remove a disposer which was never registered for execution\");\n }\n\n this._internalEventsUnregister(\"dispose\"\n /* Dispose */\n , disposer);\n };\n\n ObjectNode.prototype.removeMiddleware = function (middleware) {\n if (this.middlewares) {\n var index = this.middlewares.indexOf(middleware);\n\n if (index >= 0) {\n this.middlewares.splice(index, 1);\n }\n }\n };\n\n ObjectNode.prototype.addMiddleWare = function (handler, includeHooks) {\n var _this = this;\n\n if (includeHooks === void 0) {\n includeHooks = true;\n }\n\n var middleware = {\n handler: handler,\n includeHooks: includeHooks\n };\n if (!this.middlewares) this.middlewares = [middleware];else this.middlewares.push(middleware);\n return function () {\n _this.removeMiddleware(middleware);\n };\n };\n\n ObjectNode.prototype.applyPatchLocally = function (subpath, patch) {\n this.assertWritable({\n subpath: subpath\n });\n this.createObservableInstanceIfNeeded();\n this.type.applyPatchLocally(this, subpath, patch);\n };\n\n ObjectNode.prototype._addSnapshotReaction = function () {\n var _this = this;\n\n if (!this._hasSnapshotReaction) {\n var snapshotDisposer = reaction(function () {\n return _this.snapshot;\n }, function (snapshot) {\n return _this.emitSnapshot(snapshot);\n }, snapshotReactionOptions);\n this.addDisposer(snapshotDisposer);\n this._hasSnapshotReaction = true;\n }\n }; // we proxy the methods to avoid creating an EventHandlers instance when it is not needed\n\n\n ObjectNode.prototype._internalEventsHasSubscribers = function (event) {\n return !!this._internalEvents && this._internalEvents.hasSubscribers(event);\n };\n\n ObjectNode.prototype._internalEventsRegister = function (event, eventHandler, atTheBeginning) {\n if (atTheBeginning === void 0) {\n atTheBeginning = false;\n }\n\n if (!this._internalEvents) {\n this._internalEvents = new EventHandlers();\n }\n\n return this._internalEvents.register(event, eventHandler, atTheBeginning);\n };\n\n ObjectNode.prototype._internalEventsHas = function (event, eventHandler) {\n return !!this._internalEvents && this._internalEvents.has(event, eventHandler);\n };\n\n ObjectNode.prototype._internalEventsUnregister = function (event, eventHandler) {\n if (this._internalEvents) {\n this._internalEvents.unregister(event, eventHandler);\n }\n };\n\n ObjectNode.prototype._internalEventsEmit = function (event) {\n var _a;\n\n var args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n\n if (this._internalEvents) {\n (_a = this._internalEvents).emit.apply(_a, __spread([event], args));\n }\n };\n\n ObjectNode.prototype._internalEventsClear = function (event) {\n if (this._internalEvents) {\n this._internalEvents.clear(event);\n }\n };\n\n ObjectNode.prototype._internalEventsClearAll = function () {\n if (this._internalEvents) {\n this._internalEvents.clearAll();\n }\n };\n\n __decorate([action], ObjectNode.prototype, \"createObservableInstance\", null);\n\n __decorate([computed], ObjectNode.prototype, \"snapshot\", null);\n\n __decorate([action], ObjectNode.prototype, \"detach\", null);\n\n __decorate([action], ObjectNode.prototype, \"die\", null);\n\n return ObjectNode;\n}(BaseNode);\n/**\n * @internal\n * @hidden\n */\n\n\nvar TypeFlags;\n\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 = {}));\n/**\n * @internal\n * @hidden\n */\n\n\nvar cannotDetermineSubtype = \"cannotDetermine\";\n/**\n * A base type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\n\nvar BaseType =\n/** @class */\nfunction () {\n function BaseType(name) {\n this.isType = true;\n this.name = name;\n }\n\n BaseType.prototype.create = function (snapshot, environment) {\n typecheckInternal(this, snapshot);\n return this.instantiate(null, \"\", environment, snapshot).value;\n };\n\n BaseType.prototype.getSnapshot = function (node, applyPostProcess) {\n // istanbul ignore next\n throw fail$1(\"unimplemented method\");\n };\n\n BaseType.prototype.isAssignableFrom = function (type) {\n return type === this;\n };\n\n BaseType.prototype.validate = function (value, context) {\n var node = getStateTreeNodeSafe(value);\n\n if (node) {\n var valueType = getType(value);\n return this.isAssignableFrom(valueType) ? typeCheckSuccess() : typeCheckFailure(context, value); // it is tempting to compare snapshots, but in that case we should always clone on assignments...\n }\n\n return this.isValidSnapshot(value, context);\n };\n\n BaseType.prototype.is = function (thing) {\n return this.validate(thing, [{\n path: \"\",\n type: this\n }]).length === 0;\n };\n\n Object.defineProperty(BaseType.prototype, \"Type\", {\n get: function () {\n // istanbul ignore next\n throw fail$1(\"Factory.Type should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.Type`\");\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseType.prototype, \"TypeWithoutSTN\", {\n get: function () {\n // istanbul ignore next\n throw fail$1(\"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$1(\"Factory.SnapshotType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.SnapshotType`\");\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(BaseType.prototype, \"CreationType\", {\n get: function () {\n // istanbul ignore next\n throw fail$1(\"Factory.CreationType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.CreationType`\");\n },\n enumerable: false,\n configurable: true\n });\n\n __decorate([action], BaseType.prototype, \"create\", null);\n\n return BaseType;\n}();\n/**\n * A complex type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\n\n\nvar ComplexType =\n/** @class */\nfunction (_super) {\n __extends(ComplexType, _super);\n\n function ComplexType(name) {\n return _super.call(this, name) || this;\n }\n\n ComplexType.prototype.create = function (snapshot, environment) {\n if (snapshot === void 0) {\n snapshot = this.getDefaultSnapshot();\n }\n\n return _super.prototype.create.call(this, snapshot, environment);\n };\n\n ComplexType.prototype.getValue = function (node) {\n node.createObservableInstanceIfNeeded();\n return node.storedValue;\n };\n\n ComplexType.prototype.tryToReconcileNode = function (current, newValue) {\n if (current.isDetaching) return false;\n\n if (current.snapshot === newValue) {\n // newValue is the current snapshot of the node, noop\n return true;\n }\n\n if (isStateTreeNode(newValue) && getStateTreeNode(newValue) === current) {\n // the current node is the same as the new one\n return true;\n }\n\n if (current.type === this && isMutable(newValue) && !isStateTreeNode(newValue) && (!current.identifierAttribute || current.identifier === normalizeIdentifier(newValue[current.identifierAttribute]))) {\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\n return false;\n };\n\n ComplexType.prototype.reconcile = function (current, newValue, parent, subpath) {\n var nodeReconciled = this.tryToReconcileNode(current, newValue);\n\n if (nodeReconciled) {\n current.setParent(parent, subpath);\n return current;\n } // current node cannot be recycled in any way\n\n\n current.die(); // noop if detaching\n // attempt to reuse the new one\n\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 } // nothing to do, we have to create a new node\n\n\n return this.instantiate(parent, subpath, undefined, newValue);\n };\n\n ComplexType.prototype.getSubTypes = function () {\n return null;\n };\n\n __decorate([action], ComplexType.prototype, \"create\", null);\n\n return ComplexType;\n}(BaseType);\n/**\n * @internal\n * @hidden\n */\n\n\nvar SimpleType =\n/** @class */\nfunction (_super) {\n __extends(SimpleType, _super);\n\n function SimpleType() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n\n SimpleType.prototype.createNewInstance = function (snapshot) {\n return snapshot;\n };\n\n SimpleType.prototype.getValue = 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 SimpleType.prototype.getSnapshot = function (node) {\n return node.storedValue;\n };\n\n SimpleType.prototype.reconcile = 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\n var res = this.instantiate(parent, subpath, undefined, newValue);\n current.die(); // noop if detaching\n\n return res;\n };\n\n SimpleType.prototype.getSubTypes = 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 */\n\n\nfunction isType(value) {\n return typeof value === \"object\" && value && value.isType === true;\n}\n/**\n * @internal\n * @hidden\n */\n\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 */\n\nfunction createActionTrackingMiddleware(hooks) {\n return function actionTrackingMiddleware(call, next, abort) {\n switch (call.type) {\n case \"action\":\n {\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\n try {\n var res = next(call);\n hooks.onSuspend(call, context);\n\n if (runningActions.get(call.id).async === false) {\n runningActions.delete(call.id);\n hooks.onSuccess(call, context, res);\n }\n\n return res;\n } catch (e) {\n runningActions.delete(call.id);\n hooks.onFail(call, context, e);\n throw e;\n }\n } else {\n return next(call);\n }\n }\n\n case \"flow_spawn\":\n {\n var root = runningActions.get(call.rootId);\n root.async = true;\n return next(call);\n }\n\n case \"flow_resume\":\n case \"flow_resume_error\":\n {\n var root = runningActions.get(call.rootId);\n hooks.onResume(call, root.context);\n\n try {\n return next(call);\n } finally {\n hooks.onSuspend(call, root.context);\n }\n }\n\n case \"flow_throw\":\n {\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\n case \"flow_return\":\n {\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 =\n/** @class */\nfunction () {\n function RunningAction(hooks, call) {\n this.hooks = hooks;\n this.call = call;\n this.flowsPending = 0;\n this.running = true;\n\n if (hooks) {\n hooks.onStart(call);\n }\n }\n\n RunningAction.prototype.finish = function (error) {\n if (this.running) {\n this.running = false;\n\n if (this.hooks) {\n this.hooks.onFinish(this.call, error);\n }\n }\n };\n\n RunningAction.prototype.incFlowsPending = function () {\n this.flowsPending++;\n };\n\n RunningAction.prototype.decFlowsPending = 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 */\n\n\nfunction createActionTrackingMiddleware2(middlewareHooks) {\n var runningActions = new WeakMap();\n return function actionTrackingMiddleware(call, next) {\n // find parentRunningAction\n var parentRunningAction = call.parentActionEvent ? runningActions.get(call.parentActionEvent) : undefined;\n\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,\n parentCall: parentRunningAction && parentRunningAction.call\n });\n\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, runningAction);\n var res = void 0;\n\n try {\n res = next(call);\n } catch (e) {\n runningAction.finish(e);\n throw e;\n }\n\n if (!runningAction.hasFlowsPending) {\n // sync action finished\n runningAction.finish();\n }\n\n return res;\n } else {\n if (!parentRunningAction) {\n return next(call);\n }\n\n switch (call.type) {\n case \"flow_spawn\":\n {\n parentRunningAction.incFlowsPending();\n return next(call);\n }\n\n case \"flow_resume\":\n case \"flow_resume_error\":\n {\n return next(call);\n }\n\n case \"flow_throw\":\n {\n var error = call.args[0];\n\n try {\n return next(call);\n } finally {\n parentRunningAction.decFlowsPending();\n\n if (!parentRunningAction.hasFlowsPending) {\n parentRunningAction.finish(error);\n }\n }\n }\n\n case \"flow_return\":\n {\n try {\n return next(call);\n } finally {\n parentRunningAction.decFlowsPending();\n\n if (!parentRunningAction.hasFlowsPending) {\n parentRunningAction.finish();\n }\n }\n }\n }\n }\n };\n}\n\nfunction serializeArgument(node, actionName, index, arg) {\n if (arg instanceof Date) return {\n $MST_DATE: arg.getTime()\n };\n if (isPrimitive(arg)) return arg; // 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\n if (isStateTreeNode(arg)) return serializeTheUnserializable(\"[MSTNode: \" + getType(arg).name + \"]\");\n if (typeof arg === \"function\") return serializeTheUnserializable(\"[function]\");\n if (typeof arg === \"object\" && !isPlainObject(arg) && !isArray(arg)) return serializeTheUnserializable(\"[object \" + (arg && arg.constructor && arg.constructor.name || \"Complex Object\") + \"]\");\n\n try {\n // Check if serializable, cycle free etc...\n // MWE: there must be a better way....\n JSON.stringify(arg); // or throws\n\n return arg;\n } catch (e) {\n return serializeTheUnserializable(\"\" + e);\n }\n}\n\nfunction deserializeArgument(adm, value) {\n if (value && typeof value === \"object\" && \"$MST_DATE\" in value) return new Date(value[\"$MST_DATE\"]);\n return value;\n}\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 */\n\n\nfunction applyAction(target, actions) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n assertArg(actions, function (a) {\n return typeof a === \"object\";\n }, \"object or array\", 2);\n runInAction(function () {\n asArray(actions).forEach(function (action) {\n return baseApplyAction(target, action);\n });\n });\n}\n\nfunction baseApplyAction(target, action) {\n var resolvedTarget = tryResolve(target, action.path || \"\");\n if (!resolvedTarget) throw fail$1(\"Invalid action path: \" + (action.path || \"\"));\n var node = getStateTreeNode(resolvedTarget); // Reserved functions\n\n if (action.name === \"@APPLY_PATCHES\") {\n return applyPatch.call(null, resolvedTarget, action.args[0]);\n }\n\n if (action.name === \"@APPLY_SNAPSHOT\") {\n return applySnapshot.call(null, resolvedTarget, action.args[0]);\n }\n\n if (!(typeof resolvedTarget[action.name] === \"function\")) throw fail$1(\"Action '\" + action.name + \"' does not exist in '\" + node.path + \"'\");\n return resolvedTarget[action.name].apply(resolvedTarget, action.args ? action.args.map(function (v) {\n return deserializeArgument(node, v);\n }) : []);\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 */\n\n\nfunction recordActions(subject, filter) {\n // check all arguments\n assertIsStateTreeNode(subject, 1);\n var actions = [];\n\n var listener = function (call) {\n var recordThis = filter ? filter(call, getRunningActionContext()) : true;\n\n if (recordThis) {\n actions.push(call);\n }\n };\n\n var disposer;\n var recorder = {\n actions: actions,\n\n get recording() {\n return !!disposer;\n },\n\n stop: function () {\n if (disposer) {\n disposer();\n disposer = undefined;\n }\n },\n resume: function () {\n if (disposer) 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 */\n\n\nfunction onAction(target, listener, attachAfter) {\n if (attachAfter === void 0) {\n attachAfter = false;\n } // check all arguments\n\n\n assertIsStateTreeNode(target, 1);\n\n if (devMode()) {\n if (!isRoot(target)) 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)) warnError(\"Warning: Attaching onAction listeners to non protected nodes is dangerous: No events will be emitted for direct modifications without action.\");\n }\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\n if (attachAfter) {\n var res = next(rawCall);\n listener(info);\n return res;\n } else {\n listener(info);\n return next(rawCall);\n }\n } else {\n return next(rawCall);\n }\n });\n}\n\nvar nextActionId = 1;\nvar currentActionContext;\n/**\n * @internal\n * @hidden\n */\n\nfunction getCurrentActionContext() {\n return currentActionContext;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction getNextActionId() {\n return nextActionId++;\n} // TODO: optimize away entire action context if there is no middleware in tree?\n\n/**\n * @internal\n * @hidden\n */\n\n\nfunction runWithActionContext(context, fn) {\n var node = getStateTreeNode(context.context);\n\n if (context.type === \"action\") {\n node.assertAlive({\n actionContext: context\n });\n }\n\n var baseIsRunningAction = node._isRunningAction;\n node._isRunningAction = true;\n var previousContext = currentActionContext;\n currentActionContext = context;\n\n try {\n return runMiddleWares(node, context, fn);\n } finally {\n currentActionContext = previousContext;\n node._isRunningAction = baseIsRunningAction;\n }\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction getParentActionContext(parentContext) {\n if (!parentContext) return undefined;\n if (parentContext.type === \"action\") return parentContext;\n return parentContext.parentActionEvent;\n}\n/**\n * @internal\n * @hidden\n */\n\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\n res._isMSTAction = true;\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 */\n\n\nfunction addMiddleware(target, handler, includeHooks) {\n if (includeHooks === void 0) {\n includeHooks = true;\n }\n\n var node = getStateTreeNode(target);\n\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\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 */\n\n\nfunction decorate(handler, fn, includeHooks) {\n if (includeHooks === void 0) {\n includeHooks = true;\n }\n\n var middleware = {\n handler: handler,\n includeHooks: includeHooks\n };\n fn.$mst_middleware = fn.$mst_middleware || [];\n fn.$mst_middleware.push(middleware);\n return fn;\n}\n\nvar CollectedMiddlewares =\n/** @class */\nfunction () {\n function CollectedMiddlewares(node, fn) {\n this.arrayIndex = 0;\n this.inArrayIndex = 0;\n this.middlewares = []; // we just push middleware arrays into an array of arrays to avoid making copies\n\n if (fn.$mst_middleware) {\n this.middlewares.push(fn.$mst_middleware);\n }\n\n var n = node; // Find all middlewares. Optimization: cache this?\n\n while (n) {\n if (n.middlewares) this.middlewares.push(n.middlewares);\n n = n.parent;\n }\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\n CollectedMiddlewares.prototype.getNextMiddleware = function () {\n var array = this.middlewares[this.arrayIndex];\n if (!array) return undefined;\n var item = array[this.inArrayIndex++];\n\n if (!item) {\n this.arrayIndex++;\n this.inArrayIndex = 0;\n return this.getNextMiddleware();\n }\n\n return item;\n };\n\n return CollectedMiddlewares;\n}();\n\nfunction runMiddleWares(node, baseCall, originalFn) {\n var middlewares = new CollectedMiddlewares(node, originalFn); // Short circuit\n\n if (middlewares.isEmpty) return action(originalFn).apply(null, baseCall.args);\n var result = null;\n\n function runNextMiddleware(call) {\n var middleware = middlewares.getNextMiddleware();\n var handler = middleware && middleware.handler;\n\n if (!handler) {\n return action(originalFn).apply(null, call.args);\n } // skip hooks if asked to\n\n\n if (!middleware.includeHooks && Hook[call.name]) {\n return runNextMiddleware(call);\n }\n\n var nextInvoked = false;\n\n function next(call2, callback) {\n nextInvoked = true; // 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\n result = runNextMiddleware(call2);\n\n if (callback) {\n result = callback(result);\n }\n }\n\n var abortInvoked = false;\n\n function abort(value) {\n abortInvoked = true; // overwrite the result\n // can be manipulated through middlewares earlier in the queue using the callback fn\n\n result = value;\n }\n\n handler(call, next, abort);\n\n if (devMode()) {\n if (!nextInvoked && !abortInvoked) {\n var node2 = getStateTreeNode(call.tree);\n throw fail$1(\"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 } else if (nextInvoked && abortInvoked) {\n var node2 = getStateTreeNode(call.tree);\n throw fail$1(\"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\n return result;\n }\n\n return runNextMiddleware(baseCall);\n}\n/**\n * Returns the currently executing MST action context, or undefined if none.\n */\n\n\nfunction getRunningActionContext() {\n var current = getCurrentActionContext();\n\n while (current && current.type !== \"action\") {\n current = current.parentActionEvent;\n }\n\n return current;\n}\n\nfunction _isActionContextThisOrChildOf(actionContext, sameOrParent, includeSame) {\n var parentId = typeof sameOrParent === \"number\" ? sameOrParent : sameOrParent.id;\n var current = includeSame ? actionContext : actionContext.parentActionEvent;\n\n while (current) {\n if (current.id === parentId) {\n return true;\n }\n\n current = current.parentActionEvent;\n }\n\n return false;\n}\n/**\n * Returns if the given action context is a parent of this action context.\n */\n\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 */\n\n\nfunction isActionContextThisOrChildOf(actionContext, parentOrThis) {\n return _isActionContextThisOrChildOf(actionContext, parentOrThis, true);\n}\n\nfunction safeStringify(value) {\n try {\n return JSON.stringify(value);\n } catch (e) {\n // istanbul ignore next\n return \"\";\n }\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction prettyPrintValue(value) {\n return typeof value === \"function\" ? \"\" : isStateTreeNode(value) ? \"<\" + value + \">\" : \"`\" + safeStringify(value) + \"`\";\n}\n\nfunction shortenPrintValue(valueInString) {\n return valueInString.length < 280 ? valueInString : valueInString.substring(0, 272) + \"......\" + valueInString.substring(valueInString.length - 8);\n}\n\nfunction toErrorString(error) {\n var value = error.value;\n var type = error.context[error.context.length - 1].type;\n var fullPath = error.context.map(function (_a) {\n var path = _a.path;\n return path;\n }).filter(function (path) {\n return path.length > 0;\n }).join(\"/\");\n var pathPrefix = fullPath.length > 0 ? \"at path \\\"/\" + fullPath + \"\\\" \" : \"\";\n var currentTypename = isStateTreeNode(value) ? \"value of type \" + getStateTreeNode(value).type.name + \":\" : isPrimitive(value) ? \"value\" : \"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 + \"`\" : \"\") + (error.message ? \" (\" + error.message + \")\" : \"\") + (type ? isPrimitiveType(type) || isPrimitive(value) ? \".\" : \", expected an instance of `\" + type.name + \"` or a snapshot like `\" + type.describe() + \"` instead.\" + (isSnapshotCompatible ? \" (Note that a snapshot of the provided value is compatible with the targeted type)\" : \"\") : \".\");\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction getContextForPath(context, path, type) {\n return context.concat([{\n path: path,\n type: type\n }]);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction typeCheckSuccess() {\n return EMPTY_ARRAY;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction typeCheckFailure(context, value, message) {\n return [{\n context: context,\n value: value,\n message: message\n }];\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction flattenTypeErrors(errors) {\n return errors.reduce(function (a, i) {\n 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/**\n * @internal\n * @hidden\n */\n\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 */\n\n\nfunction typecheck(type, value) {\n var errors = type.validate(value, [{\n path: \"\",\n type: type\n }]);\n\n if (errors.length > 0) {\n throw fail$1(validationErrorsToString(type, value, errors));\n }\n}\n\nfunction validationErrorsToString(type, value, errors) {\n if (errors.length === 0) {\n return undefined;\n }\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 */\n\nvar IdentifierCache =\n/** @class */\nfunction () {\n function IdentifierCache() {\n this.cacheId = identifierCacheId++; // n.b. in cache all identifiers are normalized to strings\n\n this.cache = observable.map(); // 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\n this.lastCacheModificationPerId = observable.map();\n }\n\n IdentifierCache.prototype.updateLastCacheModificationPerId = function (identifier) {\n var lcm = this.lastCacheModificationPerId.get(identifier); // we start at 1 since 0 means no update since cache creation\n\n this.lastCacheModificationPerId.set(identifier, lcm === undefined ? 1 : lcm + 1);\n };\n\n IdentifierCache.prototype.getLastCacheModificationPerId = function (identifier) {\n var modificationId = this.lastCacheModificationPerId.get(identifier) || 0;\n return this.cacheId + \"-\" + modificationId;\n };\n\n IdentifierCache.prototype.addNodeToCache = function (node, lastCacheUpdate) {\n if (lastCacheUpdate === void 0) {\n lastCacheUpdate = true;\n }\n\n if (node.identifierAttribute) {\n var identifier = node.identifier;\n\n if (!this.cache.has(identifier)) {\n this.cache.set(identifier, observable.array([], mobxShallow));\n }\n\n var set = this.cache.get(identifier);\n if (set.indexOf(node) !== -1) throw fail$1(\"Already registered\");\n set.push(node);\n\n if (lastCacheUpdate) {\n this.updateLastCacheModificationPerId(identifier);\n }\n }\n };\n\n IdentifierCache.prototype.mergeCache = function (node) {\n var _this = this;\n\n values(node.identifierCache.cache).forEach(function (nodes) {\n return nodes.forEach(function (child) {\n _this.addNodeToCache(child);\n });\n });\n };\n\n IdentifierCache.prototype.notifyDied = function (node) {\n if (node.identifierAttribute) {\n var id = node.identifier;\n var set = this.cache.get(id);\n\n if (set) {\n set.remove(node); // remove empty sets from cache\n\n if (!set.length) {\n this.cache.delete(id);\n }\n\n this.updateLastCacheModificationPerId(node.identifier);\n }\n }\n };\n\n IdentifierCache.prototype.splitCache = function (node) {\n var _this = this;\n\n var res = new IdentifierCache();\n var basePath = node.path;\n entries(this.cache).forEach(function (_a) {\n var _b = __read(_a, 2),\n id = _b[0],\n nodes = _b[1];\n\n var modified = false;\n\n for (var i = nodes.length - 1; i >= 0; i--) {\n if (nodes[i].path.indexOf(basePath) === 0) {\n res.addNodeToCache(nodes[i], false); // no need to update lastUpdated since it is a whole new cache\n\n nodes.splice(i, 1);\n modified = true;\n }\n }\n\n if (modified) {\n _this.updateLastCacheModificationPerId(id);\n }\n });\n return res;\n };\n\n IdentifierCache.prototype.has = function (type, identifier) {\n var set = this.cache.get(identifier);\n if (!set) return false;\n return set.some(function (candidate) {\n return type.isAssignableFrom(candidate.type);\n });\n };\n\n IdentifierCache.prototype.resolve = function (type, identifier) {\n var set = this.cache.get(identifier);\n if (!set) return null;\n var matches = set.filter(function (candidate) {\n return type.isAssignableFrom(candidate.type);\n });\n\n switch (matches.length) {\n case 0:\n return null;\n\n case 1:\n return matches[0];\n\n default:\n throw fail$1(\"Cannot resolve a reference to type '\" + type.name + \"' with id: '\" + identifier + \"' unambigously, there are multiple candidates: \" + matches.map(function (n) {\n return n.path;\n }).join(\", \"));\n }\n };\n\n return IdentifierCache;\n}();\n/**\n * @internal\n * @hidden\n */\n\n\nfunction createObjectNode(type, parent, subpath, environment, initialValue) {\n var existingNode = getStateTreeNodeSafe(initialValue);\n\n if (existingNode) {\n if (existingNode.parent) {\n // istanbul ignore next\n throw fail$1(\"Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '\" + (parent ? parent.path : \"\") + \"/\" + subpath + \"', but it lives already at '\" + existingNode.path + \"'\");\n }\n\n if (parent) {\n existingNode.setParent(parent, subpath);\n } // else it already has no parent since it is a pre-requisite\n\n\n return existingNode;\n } // not a node, a snapshot\n\n\n return new ObjectNode(type, parent, subpath, environment, initialValue);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction createScalarNode(type, parent, subpath, environment, initialValue) {\n return new ScalarNode(type, parent, subpath, environment, initialValue);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isNode(value) {\n return value instanceof ScalarNode || value instanceof ObjectNode;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar NodeLifeCycle;\n\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 */\n\n\nfunction isStateTreeNode(value) {\n return !!(value && value.$treenode);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction assertIsStateTreeNode(value, argNumber) {\n assertArg(value, isStateTreeNode, \"mobx-state-tree node\", argNumber);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction getStateTreeNode(value) {\n if (!isStateTreeNode(value)) {\n // istanbul ignore next\n throw fail$1(\"Value \" + value + \" is no MST Node\");\n }\n\n return value.$treenode;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction getStateTreeNodeSafe(value) {\n return value && value.$treenode || null;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction toJSON() {\n return getStateTreeNode(this).snapshot;\n}\n\nvar doubleDot = function (_) {\n return \"..\";\n};\n/**\n * @internal\n * @hidden\n */\n\n\nfunction getRelativePathBetweenNodes(base, target) {\n // PRE condition target is (a child of) base!\n if (base.root !== target.root) {\n throw fail$1(\"Cannot calculate relative path: objects '\" + base + \"' and '\" + target + \"' are not part of the same object tree\");\n }\n\n var baseParts = splitJsonPath(base.path);\n var targetParts = splitJsonPath(target.path);\n var common = 0;\n\n for (; common < baseParts.length; common++) {\n if (baseParts[common] !== targetParts[common]) break;\n } // TODO: assert that no targetParts paths are \"..\", \".\" or \"\"!\n\n\n return baseParts.slice(common).map(doubleDot).join(\"/\") + joinJsonPath(targetParts.slice(common));\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction resolveNodeByPath(base, path, failIfResolveFails) {\n if (failIfResolveFails === void 0) {\n failIfResolveFails = true;\n }\n\n return resolveNodeByPathParts(base, splitJsonPath(path), failIfResolveFails);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction resolveNodeByPathParts(base, pathParts, failIfResolveFails) {\n if (failIfResolveFails === void 0) {\n failIfResolveFails = true;\n }\n\n var current = base;\n\n for (var i = 0; i < pathParts.length; i++) {\n var part = pathParts[i];\n\n if (part === \"..\") {\n current = current.parent;\n if (current) continue; // not everything has a parent\n } else if (part === \".\") {\n continue;\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 try {\n var value = current.value;\n\n if (isStateTreeNode(value)) {\n current = getStateTreeNode(value); // fall through\n }\n } catch (e) {\n if (!failIfResolveFails) {\n return undefined;\n }\n\n throw e;\n }\n }\n\n if (current instanceof ObjectNode) {\n var subType = current.getChildType(part);\n\n if (subType) {\n current = current.getChildNode(part);\n if (current) continue;\n }\n }\n }\n\n if (failIfResolveFails) throw fail$1(\"Could not resolve '\" + part + \"' in path '\" + (joinJsonPath(pathParts.slice(0, i)) || \"/\") + \"' while resolving '\" + joinJsonPath(pathParts) + \"'\");else return undefined;\n }\n\n return current;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction convertChildNodesToArray(childNodes) {\n if (!childNodes) return EMPTY_ARRAY;\n var keys = Object.keys(childNodes);\n if (!keys.length) 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} // based on: https://github.com/mobxjs/mobx-utils/blob/master/src/async-action.ts\n\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*/\n\n\nvar DEPRECATION_MESSAGE = \"See https://github.com/mobxjs/mobx-state-tree/issues/399 for more information. \" + \"Note that the middleware event types starting with `process` now start with `flow`.\";\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 */\n\nfunction process$1(asyncAction) {\n deprecated(\"process\", \"`process()` has been renamed to `flow()`. \" + DEPRECATION_MESSAGE);\n return flow(asyncAction);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar EMPTY_ARRAY = Object.freeze([]);\n/**\n * @internal\n * @hidden\n */\n\nvar EMPTY_OBJECT = Object.freeze({});\n/**\n * @internal\n * @hidden\n */\n\nvar mobxShallow = typeof $mobx === \"string\" ? {\n deep: false\n} : {\n deep: false,\n proxy: false\n};\nObject.freeze(mobxShallow);\n/**\n * @internal\n * @hidden\n */\n\nfunction fail$1(message) {\n if (message === void 0) {\n message = \"Illegal state\";\n }\n\n return new Error(\"[mobx-state-tree] \" + message);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction identity(_) {\n return _;\n}\n/**\n * pollyfill (for IE) suggested in MDN:\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger\n * @internal\n * @hidden\n */\n\n\nvar isInteger = Number.isInteger || function (value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isArray(val) {\n return Array.isArray(val) || isObservableArray(val);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction asArray(val) {\n if (!val) return EMPTY_ARRAY;\n if (isArray(val)) return val;\n return [val];\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction extend(a) {\n var b = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n b[_i - 1] = arguments[_i];\n }\n\n for (var i = 0; i < b.length; i++) {\n var current = b[i];\n\n for (var key in current) a[key] = current[key];\n }\n\n return a;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isPlainObject(value) {\n if (value === null || typeof value !== \"object\") return false;\n var proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isMutable(value) {\n return value !== null && typeof value === \"object\" && !(value instanceof Date) && !(value instanceof RegExp);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isPrimitive(value, includeDate) {\n if (includeDate === void 0) {\n includeDate = true;\n }\n\n if (value === null || value === undefined) return true;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || includeDate && value instanceof Date) return true;\n return false;\n}\n/**\n * @internal\n * @hidden\n * Freeze a value and return it (if not in production)\n */\n\n\nfunction freeze(value) {\n if (!devMode()) 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 */\n\n\nfunction deepFreeze(value) {\n if (!devMode()) return value;\n freeze(value);\n\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\n return value;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isSerializable(value) {\n return typeof value !== \"function\";\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction addHiddenFinalProp(object, propName, value) {\n Object.defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction addHiddenWritableProp(object, propName, value) {\n Object.defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar EventHandler =\n/** @class */\nfunction () {\n function EventHandler() {\n this.handlers = [];\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\n EventHandler.prototype.register = function (fn, atTheBeginning) {\n var _this = this;\n\n if (atTheBeginning === void 0) {\n atTheBeginning = false;\n }\n\n if (atTheBeginning) {\n this.handlers.unshift(fn);\n } else {\n this.handlers.push(fn);\n }\n\n return function () {\n _this.unregister(fn);\n };\n };\n\n EventHandler.prototype.has = function (fn) {\n return this.handlers.indexOf(fn) >= 0;\n };\n\n EventHandler.prototype.unregister = function (fn) {\n var index = this.handlers.indexOf(fn);\n\n if (index >= 0) {\n this.handlers.splice(index, 1);\n }\n };\n\n EventHandler.prototype.clear = function () {\n this.handlers.length = 0;\n };\n\n EventHandler.prototype.emit = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n } // make a copy just in case it changes\n\n\n var handlers = this.handlers.slice();\n handlers.forEach(function (f) {\n return f.apply(void 0, __spread(args));\n });\n };\n\n return EventHandler;\n}();\n/**\n * @internal\n * @hidden\n */\n\n\nvar EventHandlers =\n/** @class */\nfunction () {\n function EventHandlers() {}\n\n EventHandlers.prototype.hasSubscribers = function (event) {\n var handler = this.eventHandlers && this.eventHandlers[event];\n return !!handler && handler.hasSubscribers;\n };\n\n EventHandlers.prototype.register = function (event, fn, atTheBeginning) {\n if (atTheBeginning === void 0) {\n atTheBeginning = false;\n }\n\n if (!this.eventHandlers) {\n this.eventHandlers = {};\n }\n\n var handler = this.eventHandlers[event];\n\n if (!handler) {\n handler = this.eventHandlers[event] = new EventHandler();\n }\n\n return handler.register(fn, atTheBeginning);\n };\n\n EventHandlers.prototype.has = function (event, fn) {\n var handler = this.eventHandlers && this.eventHandlers[event];\n return !!handler && handler.has(fn);\n };\n\n EventHandlers.prototype.unregister = function (event, fn) {\n var handler = this.eventHandlers && this.eventHandlers[event];\n\n if (handler) {\n handler.unregister(fn);\n }\n };\n\n EventHandlers.prototype.clear = function (event) {\n if (this.eventHandlers) {\n delete this.eventHandlers[event];\n }\n };\n\n EventHandlers.prototype.clearAll = function () {\n this.eventHandlers = undefined;\n };\n\n EventHandlers.prototype.emit = function (event) {\n var _a;\n\n var args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n\n var handler = this.eventHandlers && this.eventHandlers[event];\n\n if (handler) {\n (_a = handler).emit.apply(_a, __spread(args));\n }\n };\n\n return EventHandlers;\n}();\n/**\n * @internal\n * @hidden\n */\n\n\nfunction argsToArray(args) {\n var res = new Array(args.length);\n\n for (var i = 0; i < args.length; i++) res[i] = args[i];\n\n return res;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction invalidateComputed(target, propName) {\n var atom = getAtom(target, propName);\n atom.trackAndCompute();\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction stringStartsWith(str, beginning) {\n return str.indexOf(beginning) === 0;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar deprecated = function (id, message) {\n // skip if running production\n if (!devMode()) return; // warn if hasn't been warned before\n\n if (deprecated.ids && !deprecated.ids.hasOwnProperty(id)) {\n warnError(\"Deprecation warning: \" + message);\n } // mark as warned to avoid duplicate warn message\n\n\n if (deprecated.ids) deprecated.ids[id] = true;\n};\n\ndeprecated.ids = {};\n/**\n * @internal\n * @hidden\n */\n\nfunction warnError(msg) {\n console.warn(new Error(\"[mobx-state-tree] \" + msg));\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isTypeCheckingEnabled() {\n return devMode() || typeof process !== \"undefined\" && process.env && process.env.ENABLE_TYPE_CHECK === \"true\";\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction devMode() {\n return process.env.NODE_ENV !== \"production\";\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction assertArg(value, fn, typeName, argNumber) {\n if (devMode()) {\n if (!fn(value)) {\n // istanbul ignore next\n throw fail$1(\"expected \" + typeName + \" as argument \" + asArray(argNumber).join(\" or \") + \", got \" + value + \" instead\");\n }\n }\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction assertIsFunction(value, argNumber) {\n assertArg(value, function (fn) {\n return typeof fn === \"function\";\n }, \"function\", argNumber);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction assertIsNumber(value, argNumber, min, max) {\n assertArg(value, function (n) {\n return typeof n === \"number\";\n }, \"number\", argNumber);\n\n if (min !== undefined) {\n assertArg(value, function (n) {\n return n >= min;\n }, \"number greater than \" + min, argNumber);\n }\n\n if (max !== undefined) {\n assertArg(value, function (n) {\n return n <= max;\n }, \"number lesser than \" + max, argNumber);\n }\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction assertIsString(value, argNumber, canBeEmpty) {\n if (canBeEmpty === void 0) {\n canBeEmpty = true;\n }\n\n assertArg(value, function (s) {\n return typeof s === \"string\";\n }, \"string\", argNumber);\n\n if (!canBeEmpty) {\n assertArg(value, function (s) {\n return s !== \"\";\n }, \"not empty string\", argNumber);\n }\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction setImmediateWithFallback(fn) {\n if (typeof queueMicrotask === \"function\") {\n queueMicrotask(fn);\n } else if (typeof setImmediate === \"function\") {\n setImmediate(fn);\n } else {\n setTimeout(fn, 1);\n }\n}\n/**\n * See [asynchronous actions](concepts/async-actions.md).\n *\n * @returns The flow as a promise.\n */\n\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 */\n\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 */\n\n\nfunction toGeneratorFunction(p) {\n return function () {\n var _i;\n\n var args = [];\n\n for (_i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , p.apply(void 0, __spread(args))];\n\n case 1:\n return [2\n /*return*/\n , _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 */\n\n\nfunction toGenerator(p) {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , p];\n\n case 1:\n return [2\n /*return*/\n , _a.sent()];\n }\n });\n}\n/**\n * @internal\n * @hidden\n */\n\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\n if (!parentContext) {\n throw fail$1(\"a mst flow must always have a parent context\");\n }\n\n var parentActionContext = getParentActionContext(parentContext);\n\n if (!parentActionContext) {\n throw fail$1(\"a mst flow must always have a parent action context\");\n }\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\n function wrap(fn, type, arg) {\n fn.$mst_middleware = spawner.$mst_middleware; // pick up any middleware attached to the flow\n\n runWithActionContext(__assign(__assign({}, contextBase), {\n type: type,\n args: [arg]\n }), fn);\n }\n\n return new Promise(function (resolve, reject) {\n var gen;\n\n var init = function asyncActionInit() {\n gen = generator.apply(null, arguments);\n onFulfilled(undefined); // kick off the flow\n };\n\n init.$mst_middleware = spawner.$mst_middleware;\n runWithActionContext(__assign(__assign({}, contextBase), {\n type: \"flow_spawn\",\n args: argsToArray(args)\n }), init);\n\n function onFulfilled(res) {\n var ret;\n\n try {\n // prettier-ignore\n wrap(function (r) {\n ret = gen.next(r);\n }, \"flow_resume\", res);\n } catch (e) {\n // prettier-ignore\n setImmediateWithFallback(function () {\n wrap(function (r) {\n reject(e);\n }, \"flow_throw\", e);\n });\n return;\n }\n\n next(ret);\n return;\n }\n\n function onRejected(err) {\n var ret;\n\n try {\n // prettier-ignore\n wrap(function (r) {\n ret = gen.throw(r);\n }, \"flow_resume_error\", err); // or yieldError?\n } catch (e) {\n // prettier-ignore\n setImmediateWithFallback(function () {\n wrap(function (r) {\n reject(e);\n }, \"flow_throw\", e);\n });\n return;\n }\n\n next(ret);\n }\n\n function next(ret) {\n if (ret.done) {\n // prettier-ignore\n setImmediateWithFallback(function () {\n wrap(function (r) {\n resolve(r);\n }, \"flow_return\", ret.value);\n });\n return;\n } // TODO: support more type of values? See https://github.com/tj/co/blob/249bbdc72da24ae44076afd716349d2089b31c4c/index.js#L100\n\n\n if (!ret.value || typeof ret.value.then !== \"function\") {\n // istanbul ignore next\n throw fail$1(\"Only promises can be yielded to `async`, got: \" + ret);\n }\n\n return ret.value.then(onFulfilled, onRejected);\n }\n });\n };\n\n return spawner;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction splitPatch(patch) {\n if (!(\"oldValue\" in patch)) throw fail$1(\"Patches without `oldValue` field cannot be inversed\");\n return [stripPatch(patch), invertPatch(patch)];\n}\n/**\n * @internal\n * @hidden\n */\n\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 {\n op: \"add\",\n path: patch.path,\n value: patch.value\n };\n\n case \"remove\":\n return {\n op: \"remove\",\n path: patch.path\n };\n\n case \"replace\":\n return {\n op: \"replace\",\n path: patch.path,\n value: patch.value\n };\n }\n}\n\nfunction invertPatch(patch) {\n switch (patch.op) {\n case \"add\":\n return {\n op: \"remove\",\n path: patch.path\n };\n\n case \"remove\":\n return {\n op: \"add\",\n path: patch.path,\n value: patch.oldValue\n };\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 */\n\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 */\n\n\nfunction escapeJsonPath(path) {\n if (isNumber(path) === true) {\n return \"\" + path;\n }\n\n if (path.indexOf(\"/\") === -1 && path.indexOf(\"~\") === -1) return path;\n return path.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n/**\n * Unescape slashes and backslashes.\n */\n\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 */\n\n\nfunction joinJsonPath(path) {\n // `/` refers to property with an empty name, while `` refers to root itself!\n if (path.length === 0) return \"\";\n\n var getPathStr = function (p) {\n return p.map(escapeJsonPath).join(\"/\");\n };\n\n if (path[0] === \".\" || path[0] === \"..\") {\n // relative\n return getPathStr(path);\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 */\n\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 === \"\" || path === \".\" || path === \"..\" || stringStartsWith(path, \"/\") || stringStartsWith(path, \"./\") || stringStartsWith(path, \"../\");\n\n if (!valid) {\n throw fail$1(\"a json path must be either rooted, empty or relative, but got '\" + path + \"'\");\n } // '/a/b/c' -> [\"a\", \"b\", \"c\"]\n // '../../b/c' -> [\"..\", \"..\", \"b\", \"c\"]\n // '' -> []\n // '/' -> ['']\n // './a' -> [\".\", \"a\"]\n // /./a' -> [\".\", \"a\"] equivalent to './a'\n\n\n if (parts[0] === \"\") {\n parts.shift();\n }\n\n return parts;\n}\n\nvar SnapshotProcessor =\n/** @class */\nfunction (_super) {\n __extends(SnapshotProcessor, _super);\n\n function SnapshotProcessor(_subtype, _processors, name) {\n var _this = _super.call(this, name || _subtype.name) || this;\n\n _this._subtype = _subtype;\n _this._processors = _processors;\n return _this;\n }\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\n SnapshotProcessor.prototype.describe = function () {\n return \"snapshotProcessor(\" + this._subtype.describe() + \")\";\n };\n\n SnapshotProcessor.prototype.preProcessSnapshot = function (sn) {\n if (this._processors.preProcessor) {\n return this._processors.preProcessor.call(null, sn);\n }\n\n return sn;\n };\n\n SnapshotProcessor.prototype.postProcessSnapshot = function (sn) {\n if (this._processors.postProcessor) {\n return this._processors.postProcessor.call(null, sn);\n }\n\n return sn;\n };\n\n SnapshotProcessor.prototype._fixNode = function (node) {\n var _this = this; // the node has to use these methods rather than the original type ones\n\n\n proxyNodeTypeMethods(node.type, this, \"isAssignableFrom\", \"create\");\n var oldGetSnapshot = node.getSnapshot;\n\n node.getSnapshot = function () {\n return _this.postProcessSnapshot(oldGetSnapshot.call(node));\n };\n };\n\n SnapshotProcessor.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n var processedInitialValue = isStateTreeNode(initialValue) ? initialValue : this.preProcessSnapshot(initialValue);\n\n var node = this._subtype.instantiate(parent, subpath, environment, processedInitialValue);\n\n this._fixNode(node);\n\n return node;\n };\n\n SnapshotProcessor.prototype.reconcile = function (current, newValue, parent, subpath) {\n var node = this._subtype.reconcile(current, isStateTreeNode(newValue) ? newValue : this.preProcessSnapshot(newValue), parent, subpath);\n\n if (node !== current) {\n this._fixNode(node);\n }\n\n return node;\n };\n\n SnapshotProcessor.prototype.getSnapshot = function (node, applyPostProcess) {\n if (applyPostProcess === void 0) {\n applyPostProcess = true;\n }\n\n var sn = this._subtype.getSnapshot(node);\n\n return applyPostProcess ? this.postProcessSnapshot(sn) : sn;\n };\n\n SnapshotProcessor.prototype.isValidSnapshot = function (value, context) {\n var processedSn = this.preProcessSnapshot(value);\n return this._subtype.validate(processedSn, context);\n };\n\n SnapshotProcessor.prototype.getSubTypes = function () {\n return this._subtype;\n };\n\n SnapshotProcessor.prototype.is = function (thing) {\n var value = isType(thing) ? this._subtype : isStateTreeNode(thing) ? getSnapshot(thing, false) : this.preProcessSnapshot(thing);\n return this._subtype.validate(value, [{\n path: \"\",\n type: this._subtype\n }]).length === 0;\n };\n\n return SnapshotProcessor;\n}(BaseType);\n\nfunction proxyNodeTypeMethods(nodeType, snapshotProcessorType) {\n var e_1, _a;\n\n var methods = [];\n\n for (var _i = 2; _i < arguments.length; _i++) {\n methods[_i - 2] = arguments[_i];\n }\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 } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (methods_1_1 && !methods_1_1.done && (_a = methods_1.return)) _a.call(methods_1);\n } finally {\n if (e_1) throw e_1.error;\n }\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 * const Todo2 = types.snapshotProcessor(Todo1, {\n * // from snapshot to instance\n * preProcessor(sn: BackendTodo) {\n * return {\n * text: sn.text || \"\";\n * }\n * },\n * // from instance to snapshot\n * postProcessor(sn): 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 */\n\n\nfunction snapshotProcessor(type, processors, name) {\n assertIsType(type, 1);\n\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\n if (processors.preProcessor && typeof processors.preProcessor !== \"function\") {\n // istanbul ignore next\n throw fail(\"preSnapshotProcessor must be a function\");\n }\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\";\n\nfunction tryCollectModelTypes(type, modelTypes) {\n var e_1, _a;\n\n var subtypes = type.getSubTypes();\n\n if (subtypes === cannotDetermineSubtype) {\n return false;\n }\n\n if (subtypes) {\n var subtypesArray = asArray(subtypes);\n\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)) return false;\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (subtypesArray_1_1 && !subtypesArray_1_1.done && (_a = subtypesArray_1.return)) _a.call(subtypesArray_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n }\n\n if (type instanceof ModelType) {\n modelTypes.push(type);\n }\n\n return true;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar MapIdentifierMode;\n\n(function (MapIdentifierMode) {\n MapIdentifierMode[MapIdentifierMode[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n MapIdentifierMode[MapIdentifierMode[\"YES\"] = 1] = \"YES\";\n MapIdentifierMode[MapIdentifierMode[\"NO\"] = 2] = \"NO\";\n})(MapIdentifierMode || (MapIdentifierMode = {}));\n\nvar MSTMap =\n/** @class */\nfunction (_super) {\n __extends(MSTMap, _super);\n\n function MSTMap(initialData) {\n return _super.call(this, initialData, observable.ref.enhancer) || this;\n }\n\n MSTMap.prototype.get = function (key) {\n // maybe this is over-enthousiastic? normalize numeric keys to strings\n return _super.prototype.get.call(this, \"\" + key);\n };\n\n MSTMap.prototype.has = function (key) {\n return _super.prototype.has.call(this, \"\" + key);\n };\n\n MSTMap.prototype.delete = function (key) {\n return _super.prototype.delete.call(this, \"\" + key);\n };\n\n MSTMap.prototype.set = function (key, value) {\n return _super.prototype.set.call(this, \"\" + key, value);\n };\n\n MSTMap.prototype.put = function (value) {\n if (!value) throw fail$1(\"Map.put cannot be used to set empty values\");\n\n if (isStateTreeNode(value)) {\n var node = getStateTreeNode(value);\n\n if (devMode()) {\n if (!node.identifierAttribute) {\n throw fail$1(needsIdentifierError);\n }\n }\n\n if (node.identifier === null) {\n throw fail$1(needsIdentifierError);\n }\n\n this.set(node.identifier, value);\n return value;\n } else if (!isMutable(value)) {\n throw fail$1(\"Map.put can only be used to store complex values\");\n } else {\n var mapNode = getStateTreeNode(this);\n var mapType = mapNode.type;\n\n if (mapType.identifierMode !== MapIdentifierMode.YES) {\n throw fail$1(needsIdentifierError);\n }\n\n var idAttr = mapType.mapIdentifierAttribute;\n var id = value[idAttr];\n\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\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 */\n\n\nvar MapType =\n/** @class */\nfunction (_super) {\n __extends(MapType, _super);\n\n function MapType(name, _subType, hookInitializers) {\n if (hookInitializers === void 0) {\n hookInitializers = [];\n }\n\n var _this = _super.call(this, name) || this;\n\n _this._subType = _subType;\n _this.identifierMode = MapIdentifierMode.UNKNOWN;\n _this.mapIdentifierAttribute = undefined;\n _this.flags = TypeFlags.Map;\n _this.hookInitializers = [];\n\n _this._determineIdentifierMode();\n\n _this.hookInitializers = hookInitializers;\n return _this;\n }\n\n MapType.prototype.hooks = 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 MapType.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n this._determineIdentifierMode();\n\n return createObjectNode(this, parent, subpath, environment, initialValue);\n };\n\n MapType.prototype._determineIdentifierMode = function () {\n if (this.identifierMode !== MapIdentifierMode.UNKNOWN) {\n return;\n }\n\n var modelTypes = [];\n\n if (tryCollectModelTypes(this._subType, modelTypes)) {\n var identifierAttribute_1 = undefined;\n modelTypes.forEach(function (type) {\n if (type.identifierAttribute) {\n if (identifierAttribute_1 && identifierAttribute_1 !== type.identifierAttribute) {\n throw fail$1(\"The objects in a map should all have the same identifier attribute, expected '\" + identifierAttribute_1 + \"', but child of type '\" + type.name + \"' declared attribute '\" + type.identifierAttribute + \"' as identifier\");\n }\n\n identifierAttribute_1 = type.identifierAttribute;\n }\n });\n\n if (identifierAttribute_1) {\n this.identifierMode = MapIdentifierMode.YES;\n this.mapIdentifierAttribute = identifierAttribute_1;\n } else {\n this.identifierMode = MapIdentifierMode.NO;\n }\n }\n };\n\n MapType.prototype.initializeChildNodes = function (objNode, initialSnapshot) {\n if (initialSnapshot === void 0) {\n initialSnapshot = {};\n }\n\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 MapType.prototype.createNewInstance = function (childNodes) {\n return new MSTMap(childNodes);\n };\n\n MapType.prototype.finalizeNewInstance = function (node, instance) {\n _interceptReads(instance, node.unbox);\n\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 MapType.prototype.describe = function () {\n return \"Map\";\n };\n\n MapType.prototype.getChildren = function (node) {\n // return (node.storedValue as ObservableMap).values()\n return values(node.storedValue);\n };\n\n MapType.prototype.getChildNode = function (node, key) {\n var childNode = node.storedValue.get(\"\" + key);\n if (!childNode) throw fail$1(\"Not a child \" + key);\n return childNode;\n };\n\n MapType.prototype.willChange = function (change) {\n var node = getStateTreeNode(change.object);\n var key = change.name;\n node.assertWritable({\n subpath: key\n });\n var mapType = node.type;\n var subType = mapType._subType;\n\n switch (change.type) {\n case \"update\":\n {\n var newValue = change.newValue;\n var oldValue = change.object.get(key);\n if (newValue === oldValue) 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\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\n return change;\n };\n\n MapType.prototype.processIdentifier = function (expected, node) {\n if (this.identifierMode === MapIdentifierMode.YES && node instanceof ObjectNode) {\n var identifier = node.identifier;\n if (identifier !== expected) throw fail$1(\"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 MapType.prototype.getSnapshot = function (node) {\n var res = {};\n node.getChildren().forEach(function (childNode) {\n res[childNode.subpath] = childNode.snapshot;\n });\n return res;\n };\n\n MapType.prototype.processInitialSnapshot = 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 MapType.prototype.didChange = function (change) {\n var node = getStateTreeNode(change.object);\n\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\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\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(); // emit the patch\n\n return void node.emitPatch({\n op: \"remove\",\n path: escapeJsonPath(change.name),\n oldValue: oldSnapshot\n }, node);\n }\n };\n\n MapType.prototype.applyPatchLocally = function (node, subpath, patch) {\n var target = node.storedValue;\n\n switch (patch.op) {\n case \"add\":\n case \"replace\":\n target.set(subpath, patch.value);\n break;\n\n case \"remove\":\n target.delete(subpath);\n break;\n }\n };\n\n MapType.prototype.applySnapshot = 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\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\n Object.keys(currentKeys).forEach(function (key) {\n if (currentKeys[key] === false) target.delete(key);\n });\n };\n\n MapType.prototype.getChildType = function () {\n return this._subType;\n };\n\n MapType.prototype.isValidSnapshot = function (value, context) {\n var _this = this;\n\n if (!isPlainObject(value)) {\n return typeCheckFailure(context, value, \"Value is not a plain object\");\n }\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 MapType.prototype.getDefaultSnapshot = function () {\n return EMPTY_OBJECT;\n };\n\n MapType.prototype.removeChild = function (node, subpath) {\n node.storedValue.delete(subpath);\n };\n\n __decorate([action], MapType.prototype, \"applySnapshot\", null);\n\n return MapType;\n}(ComplexType);\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/refguide/map.html)\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 */\n\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 */\n\n\nfunction isMapType(type) {\n return isType(type) && (type.flags & TypeFlags.Map) > 0;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar ArrayType =\n/** @class */\nfunction (_super) {\n __extends(ArrayType, _super);\n\n function ArrayType(name, _subType, hookInitializers) {\n if (hookInitializers === void 0) {\n hookInitializers = [];\n }\n\n var _this = _super.call(this, name) || this;\n\n _this._subType = _subType;\n _this.flags = TypeFlags.Array;\n _this.hookInitializers = [];\n _this.hookInitializers = hookInitializers;\n return _this;\n }\n\n ArrayType.prototype.hooks = 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 ArrayType.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n return createObjectNode(this, parent, subpath, environment, initialValue);\n };\n\n ArrayType.prototype.initializeChildNodes = function (objNode, snapshot) {\n if (snapshot === void 0) {\n snapshot = [];\n }\n\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 ArrayType.prototype.createNewInstance = function (childNodes) {\n return observable.array(convertChildNodesToArray(childNodes), mobxShallow);\n };\n\n ArrayType.prototype.finalizeNewInstance = 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 ArrayType.prototype.describe = function () {\n return this._subType.describe() + \"[]\";\n };\n\n ArrayType.prototype.getChildren = function (node) {\n return node.storedValue.slice();\n };\n\n ArrayType.prototype.getChildNode = function (node, key) {\n var index = Number(key);\n if (index < node.storedValue.length) return node.storedValue[index];\n throw fail$1(\"Not a child: \" + key);\n };\n\n ArrayType.prototype.willChange = function (change) {\n var node = getStateTreeNode(change.object);\n node.assertWritable({\n subpath: \"\" + change.index\n });\n var subType = node.type._subType;\n var childNodes = node.getChildren();\n\n switch (change.type) {\n case \"update\":\n {\n if (change.newValue === change.object[change.index]) return null;\n var updatedNodes = reconcileArrayChildren(node, subType, [childNodes[change.index]], [change.newValue], [change.index]);\n\n if (!updatedNodes) {\n return null;\n }\n\n change.newValue = updatedNodes[0];\n }\n break;\n\n case \"splice\":\n {\n var index_1 = change.index,\n removedCount = change.removedCount,\n added = change.added;\n var addedNodes = reconcileArrayChildren(node, subType, childNodes.slice(index_1, index_1 + removedCount), added, added.map(function (_, i) {\n return index_1 + i;\n }));\n\n if (!addedNodes) {\n return null;\n }\n\n change.added = addedNodes; // update paths of remaining items\n\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\n return change;\n };\n\n ArrayType.prototype.getSnapshot = function (node) {\n return node.getChildren().map(function (childNode) {\n return childNode.snapshot;\n });\n };\n\n ArrayType.prototype.processInitialSnapshot = 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 ArrayType.prototype.didChange = function (change) {\n var node = getStateTreeNode(change.object);\n\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\n case \"splice\":\n for (var i = change.removedCount - 1; i >= 0; i--) node.emitPatch({\n op: \"remove\",\n path: \"\" + (change.index + i),\n oldValue: change.removed[i].snapshot\n }, node);\n\n for (var i = 0; i < change.addedCount; i++) node.emitPatch({\n op: \"add\",\n path: \"\" + (change.index + i),\n value: node.getChildNode(\"\" + (change.index + i)).snapshot,\n oldValue: undefined\n }, node);\n\n return;\n }\n };\n\n ArrayType.prototype.applyPatchLocally = function (node, subpath, patch) {\n var target = node.storedValue;\n var index = subpath === \"-\" ? target.length : Number(subpath);\n\n switch (patch.op) {\n case \"replace\":\n target[index] = patch.value;\n break;\n\n case \"add\":\n target.splice(index, 0, patch.value);\n break;\n\n case \"remove\":\n target.splice(index, 1);\n break;\n }\n };\n\n ArrayType.prototype.applySnapshot = function (node, snapshot) {\n typecheckInternal(this, snapshot);\n var target = node.storedValue;\n target.replace(snapshot);\n };\n\n ArrayType.prototype.getChildType = function () {\n return this._subType;\n };\n\n ArrayType.prototype.isValidSnapshot = function (value, context) {\n var _this = this;\n\n if (!isArray(value)) {\n return typeCheckFailure(context, value, \"Value is not an array\");\n }\n\n return flattenTypeErrors(value.map(function (item, index) {\n return _this._subType.validate(item, getContextForPath(context, \"\" + index, _this._subType));\n }));\n };\n\n ArrayType.prototype.getDefaultSnapshot = function () {\n return EMPTY_ARRAY;\n };\n\n ArrayType.prototype.removeChild = function (node, subpath) {\n node.storedValue.splice(Number(subpath), 1);\n };\n\n __decorate([action], ArrayType.prototype, \"applySnapshot\", null);\n\n return ArrayType;\n}(ComplexType);\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/refguide/array.html)\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 */\n\n\nfunction array(subtype) {\n assertIsType(subtype, 1);\n return new ArrayType(subtype.name + \"[]\", subtype);\n}\n\nfunction reconcileArrayChildren(parent, childType, oldNodes, newValues, newPaths) {\n var nothingChanged = true;\n\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]; // 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\n if (isNode(newValue)) newValue = newValue.storedValue;\n\n if (!oldNode && !hasNewNode) {\n // both are empty, end\n break;\n } else if (!hasNewNode) {\n // new one does not exists\n nothingChanged = false;\n oldNodes.splice(i, 1);\n\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\n oldNode.die();\n i--;\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$1(\"Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '\" + parent.path + \"/\" + newPath + \"', but it lives already at '\" + getStateTreeNode(newValue).path + \"'\");\n }\n\n nothingChanged = false;\n var newNode = valueAsNode(childType, parent, newPath, newValue);\n oldNodes.splice(i, 0, newNode);\n } else if (areSame(oldNode, newValue)) {\n // both are the same, reconcile\n oldNodes[i] = valueAsNode(childType, parent, newPath, newValue, oldNode);\n } else {\n // nothing to do, try to reorder\n var oldMatch = undefined; // find a possible candidate to reuse\n\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\n nothingChanged = false;\n var newNode = valueAsNode(childType, parent, newPath, newValue, oldMatch);\n oldNodes.splice(i, 0, newNode);\n }\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 */\n\n\nfunction valueAsNode(childType, parent, subpath, newValue, oldNode) {\n // ensure the value is valid-ish\n typecheckInternal(childType, newValue);\n\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); // the node lives here\n\n if (childNode.parent !== null && childNode.parent === parent) {\n childNode.setParent(parent, subpath);\n return childNode;\n }\n } // there is old node and new one is a value/snapshot\n\n\n if (oldNode) {\n return childType.reconcile(oldNode, newValue, parent, subpath);\n } // nothing to do, create from scratch\n\n\n return childType.instantiate(parent, subpath, undefined, newValue);\n }\n\n var newNode = getNewNode();\n\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\n oldNode.die();\n }\n\n return newNode;\n}\n/**\n * Check if a node holds a value.\n */\n\n\nfunction areSame(oldNode, newValue) {\n // never consider dead old nodes for reconciliation\n if (!oldNode.isAlive) {\n return false;\n } // the new value has the same node\n\n\n if (isStateTreeNode(newValue)) {\n var newNode = getStateTreeNode(newValue);\n return newNode.isAlive && newNode === oldNode;\n } // the provided value is the snapshot of the old node\n\n\n if (oldNode.snapshot === newValue) {\n return true;\n } // new value is a snapshot with the correct identifier\n\n\n return oldNode instanceof ObjectNode && oldNode.identifier !== null && oldNode.identifierAttribute && isPlainObject(newValue) && oldNode.identifier === normalizeIdentifier(newValue[oldNode.identifierAttribute]) && oldNode.type.is(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 */\n\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\";\n\nfunction objectTypeToString() {\n return getStateTreeNode(this).toString();\n}\n\nvar defaultObjectOptions = {\n name: \"AnonymousModel\",\n properties: {},\n initializers: EMPTY_ARRAY\n};\n\nfunction toPropertiesObject(declaredProps) {\n // loop through properties and ensures that all items are types\n return Object.keys(declaredProps).reduce(function (props, key) {\n var _a, _b, _c; // warn if user intended a HOOK\n\n\n if (key in Hook) throw fail$1(\"Hook '\" + key + \"' was defined as property. Hooks should be defined as part of the actions\"); // the user intended to use a view\n\n var descriptor = Object.getOwnPropertyDescriptor(props, key);\n\n if (\"get\" in descriptor) {\n throw fail$1(\"Getters are not supported as properties. Please use views instead\");\n } // undefined and null are not valid\n\n\n var value = descriptor.value;\n\n if (value === null || value === undefined) {\n throw fail$1(\"The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?\"); // its a primitive, convert to its type\n } else if (isPrimitive(value)) {\n return Object.assign({}, props, (_a = {}, _a[key] = optional(getPrimitiveFactoryFromValue(value), value), _a)); // map defaults to empty object automatically for models\n } else if (value instanceof MapType) {\n return Object.assign({}, props, (_b = {}, _b[key] = optional(value, {}), _b));\n } else if (value instanceof ArrayType) {\n return Object.assign({}, props, (_c = {}, _c[key] = optional(value, []), _c)); // its already a type\n } else if (isType(value)) {\n return props; // its a function, maybe the user wanted a view?\n } else if (devMode() && typeof value === \"function\") {\n throw fail$1(\"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?\"); // no other complex values\n } else if (devMode() && typeof value === \"object\") {\n throw fail$1(\"Invalid type definition for property '\" + key + \"', it looks like you passed an object. Try passing another model type or a types.frozen.\"); // WTF did you pass in mate?\n } else {\n throw fail$1(\"Invalid type definition for property '\" + key + \"', cannot infer a type from a value like '\" + value + \"' (\" + typeof value + \")\");\n }\n }, declaredProps);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar ModelType =\n/** @class */\nfunction (_super) {\n __extends(ModelType, _super);\n\n function ModelType(opts) {\n var _this = _super.call(this, opts.name || defaultObjectOptions.name) || this;\n\n _this.flags = TypeFlags.Object;\n\n _this.named = function (name) {\n return _this.cloneAndEnhance({\n name: name\n });\n };\n\n _this.props = function (properties) {\n return _this.cloneAndEnhance({\n properties: properties\n });\n };\n\n _this.preProcessSnapshot = function (preProcessor) {\n var currentPreprocessor = _this.preProcessor;\n if (!currentPreprocessor) return _this.cloneAndEnhance({\n preProcessor: preProcessor\n });else return _this.cloneAndEnhance({\n preProcessor: function (snapshot) {\n return currentPreprocessor(preProcessor(snapshot));\n }\n });\n };\n\n _this.postProcessSnapshot = function (postProcessor) {\n var currentPostprocessor = _this.postProcessor;\n if (!currentPostprocessor) return _this.cloneAndEnhance({\n postProcessor: postProcessor\n });else return _this.cloneAndEnhance({\n postProcessor: function (snapshot) {\n return postProcessor(currentPostprocessor(snapshot));\n }\n });\n };\n\n Object.assign(_this, defaultObjectOptions, opts); // ensures that any default value gets converted to its related type\n\n _this.properties = toPropertiesObject(_this.properties);\n freeze(_this.properties); // make sure nobody messes with it\n\n _this.propertyNames = Object.keys(_this.properties);\n _this.identifierAttribute = _this._getIdentifierAttribute();\n return _this;\n }\n\n ModelType.prototype._getIdentifierAttribute = function () {\n var identifierAttribute = undefined;\n this.forAllProps(function (propName, propType) {\n if (propType.flags & TypeFlags.Identifier) {\n if (identifierAttribute) throw fail$1(\"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 ModelType.prototype.cloneAndEnhance = 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 ModelType.prototype.actions = function (fn) {\n var _this = this;\n\n var actionInitializer = function (self) {\n _this.instantiateActions(self, fn(self));\n\n return self;\n };\n\n return this.cloneAndEnhance({\n initializers: [actionInitializer]\n });\n };\n\n ModelType.prototype.instantiateActions = function (self, actions) {\n // check if return is correct\n if (!isPlainObject(actions)) throw fail$1(\"actions initializer should return a plain object containing actions\"); // bind actions to the object created\n\n Object.keys(actions).forEach(function (name) {\n // warn if preprocessor was given\n if (name === PRE_PROCESS_SNAPSHOT) throw fail$1(\"Cannot define action '\" + PRE_PROCESS_SNAPSHOT + \"', it should be defined using 'type.preProcessSnapshot(fn)' instead\"); // warn if postprocessor was given\n\n if (name === POST_PROCESS_SNAPSHOT) throw fail$1(\"Cannot define action '\" + POST_PROCESS_SNAPSHOT + \"', it should be defined using 'type.postProcessSnapshot(fn)' instead\");\n var action2 = actions[name]; // apply hook composition\n\n var baseAction = self[name];\n\n if (name in Hook && baseAction) {\n var specializedAction_1 = action2;\n\n action2 = function () {\n baseAction.apply(null, arguments);\n specializedAction_1.apply(null, arguments);\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\n\n var middlewares = action2.$mst_middleware; // make sure middlewares are not lost\n\n var boundAction = action2.bind(actions);\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 ModelType.prototype.volatile = function (fn) {\n var _this = this;\n\n if (typeof fn !== \"function\") {\n throw fail$1(\"You passed an \" + typeof fn + \" to volatile state as an argument, when function is expected\");\n }\n\n var stateInitializer = function (self) {\n _this.instantiateVolatileState(self, fn(self));\n\n return self;\n };\n\n return this.cloneAndEnhance({\n initializers: [stateInitializer]\n });\n };\n\n ModelType.prototype.instantiateVolatileState = function (self, state) {\n // check views return\n if (!isPlainObject(state)) throw fail$1(\"volatile state initializer should return a plain object containing state\");\n set(self, state);\n };\n\n ModelType.prototype.extend = function (fn) {\n var _this = this;\n\n var initializer = function (self) {\n var _a = fn(self),\n actions = _a.actions,\n views = _a.views,\n state = _a.state,\n rest = __rest(_a, [\"actions\", \"views\", \"state\"]);\n\n for (var key in rest) throw fail$1(\"The `extend` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '\" + key + \"'\");\n\n if (state) _this.instantiateVolatileState(self, state);\n if (views) _this.instantiateViews(self, views);\n if (actions) _this.instantiateActions(self, actions);\n return self;\n };\n\n return this.cloneAndEnhance({\n initializers: [initializer]\n });\n };\n\n ModelType.prototype.views = function (fn) {\n var _this = this;\n\n var viewInitializer = function (self) {\n _this.instantiateViews(self, fn(self));\n\n return self;\n };\n\n return this.cloneAndEnhance({\n initializers: [viewInitializer]\n });\n };\n\n ModelType.prototype.instantiateViews = function (self, views) {\n // check views return\n if (!isPlainObject(views)) throw fail$1(\"views initializer should return a plain object containing views\");\n Object.keys(views).forEach(function (key) {\n // is this a computed property?\n var descriptor = Object.getOwnPropertyDescriptor(views, key);\n\n if (\"get\" in descriptor) {\n if (isComputedProp(self, key)) {\n var computedValue = _getAdministration(self, key); // TODO: mobx currently does not allow redefining computes yet, pending #1121\n // FIXME: this binds to the internals of mobx!\n\n\n computedValue.derivation = descriptor.get;\n computedValue.scope = self;\n if (descriptor.set) computedValue.setter = action(computedValue.name + \"-setter\", descriptor.set);\n } else {\n computed(self, key, descriptor, true);\n }\n } else if (typeof descriptor.value === \"function\") {\n (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(self, key, descriptor.value);\n } else {\n throw fail$1(\"A view member should either be a function or getter based property\");\n }\n });\n };\n\n ModelType.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n var value = isStateTreeNode(initialValue) ? initialValue : this.applySnapshotPreProcessor(initialValue);\n return createObjectNode(this, parent, subpath, environment, value); // 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 ModelType.prototype.initializeChildNodes = function (objNode, initialSnapshot) {\n if (initialSnapshot === void 0) {\n initialSnapshot = {};\n }\n\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 ModelType.prototype.createNewInstance = function (childNodes) {\n return observable.object(childNodes, EMPTY_OBJECT, mobxShallow);\n };\n\n ModelType.prototype.finalizeNewInstance = 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) {\n return fn(self);\n }, instance);\n intercept(instance, this.willChange);\n observe(instance, this.didChange);\n };\n\n ModelType.prototype.willChange = 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({\n subpath: subpath\n });\n var childType = node.type.properties[subpath]; // only properties are typed, state are stored as-is references\n\n if (childType) {\n typecheckInternal(childType, change.newValue);\n change.newValue = childType.reconcile(node.getChildNode(subpath), change.newValue, node, subpath);\n }\n\n return change;\n };\n\n ModelType.prototype.didChange = 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\n if (!childType) {\n // don't emit patches for volatile state\n return;\n }\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 ModelType.prototype.getChildren = function (node) {\n var _this = this;\n\n var res = [];\n this.forAllProps(function (name) {\n res.push(_this.getChildNode(node, name));\n });\n return res;\n };\n\n ModelType.prototype.getChildNode = function (node, key) {\n if (!(key in this.properties)) throw fail$1(\"Not a value property: \" + key);\n\n var childNode = _getAdministration(node.storedValue, key).value; // TODO: blegh!\n\n\n if (!childNode) throw fail$1(\"Node not available for property \" + key);\n return childNode;\n };\n\n ModelType.prototype.getSnapshot = function (node, applyPostProcess) {\n var _this = this;\n\n if (applyPostProcess === void 0) {\n applyPostProcess = true;\n }\n\n var res = {};\n this.forAllProps(function (name, type) {\n getAtom(node.storedValue, name).reportObserved();\n res[name] = _this.getChildNode(node, name).snapshot;\n });\n\n if (applyPostProcess) {\n return this.applySnapshotPostProcessor(res);\n }\n\n return res;\n };\n\n ModelType.prototype.processInitialSnapshot = 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 ModelType.prototype.applyPatchLocally = function (node, subpath, patch) {\n if (!(patch.op === \"replace\" || patch.op === \"add\")) {\n throw fail$1(\"object does not support operation \" + patch.op);\n }\n\n node.storedValue[subpath] = patch.value;\n };\n\n ModelType.prototype.applySnapshot = function (node, snapshot) {\n var preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot);\n typecheckInternal(this, preProcessedSnapshot);\n this.forAllProps(function (name) {\n node.storedValue[name] = preProcessedSnapshot[name];\n });\n };\n\n ModelType.prototype.applySnapshotPreProcessor = function (snapshot) {\n var processor = this.preProcessor;\n return processor ? processor.call(null, snapshot) : snapshot;\n };\n\n ModelType.prototype.applySnapshotPostProcessor = function (snapshot) {\n var postProcessor = this.postProcessor;\n if (postProcessor) return postProcessor.call(null, snapshot);\n return snapshot;\n };\n\n ModelType.prototype.getChildType = function (propertyName) {\n assertIsString(propertyName, 1);\n return this.properties[propertyName];\n };\n\n ModelType.prototype.isValidSnapshot = function (value, context) {\n var _this = this;\n\n var snapshot = this.applySnapshotPreProcessor(value);\n\n if (!isPlainObject(snapshot)) {\n return typeCheckFailure(context, snapshot, \"Value is not a plain object\");\n }\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 ModelType.prototype.forAllProps = function (fn) {\n var _this = this;\n\n this.propertyNames.forEach(function (key) {\n return fn(key, _this.properties[key]);\n });\n };\n\n ModelType.prototype.describe = function () {\n var _this = this; // optimization: cache\n\n\n return \"{ \" + this.propertyNames.map(function (key) {\n return key + \": \" + _this.properties[key].describe();\n }).join(\"; \") + \" }\";\n };\n\n ModelType.prototype.getDefaultSnapshot = function () {\n return EMPTY_OBJECT;\n };\n\n ModelType.prototype.removeChild = function (node, subpath) {\n node.storedValue[subpath] = undefined;\n };\n\n __decorate([action], ModelType.prototype, \"applySnapshot\", null);\n\n return ModelType;\n}(ComplexType);\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 */\n\n\nfunction model() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var name = typeof args[0] === \"string\" ? args.shift() : \"AnonymousModel\";\n var properties = args.shift() || {};\n return new ModelType({\n name: name,\n properties: properties\n });\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 */\n\n\nfunction compose() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n } // TODO: just join the base type names if no name is provided\n\n\n var hasTypename = typeof args[0] === \"string\";\n var typeName = hasTypename ? args[0] : \"AnonymousModel\";\n\n if (hasTypename) {\n args.shift();\n } // check all parameters\n\n\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\n return args.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 }).named(typeName);\n}\n/**\n * Returns if a given value represents a model type.\n *\n * @param type\n * @returns\n */\n\n\nfunction isModelType(type) {\n return isType(type) && (type.flags & TypeFlags.Object) > 0;\n} // TODO: implement CoreType using types.custom ?\n\n/**\n * @internal\n * @hidden\n */\n\n\nvar CoreType =\n/** @class */\nfunction (_super) {\n __extends(CoreType, _super);\n\n function CoreType(name, flags, checker, initializer) {\n if (initializer === void 0) {\n initializer = identity;\n }\n\n var _this = _super.call(this, name) || this;\n\n _this.flags = flags;\n _this.checker = checker;\n _this.initializer = initializer;\n _this.flags = flags;\n return _this;\n }\n\n CoreType.prototype.describe = function () {\n return this.name;\n };\n\n CoreType.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n return createScalarNode(this, parent, subpath, environment, initialValue);\n };\n\n CoreType.prototype.createNewInstance = function (snapshot) {\n return this.initializer(snapshot);\n };\n\n CoreType.prototype.isValidSnapshot = function (value, context) {\n if (isPrimitive(value) && this.checker(value)) {\n return typeCheckSuccess();\n }\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\n\n\nvar string = new CoreType(\"string\", TypeFlags.String, function (v) {\n return typeof v === \"string\";\n});\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\n\nvar number = new CoreType(\"number\", TypeFlags.Number, function (v) {\n return typeof v === \"number\";\n});\n/**\n * `types.integer` - Creates a type that can only contain an integer value.\n * This type is used for integer values by default\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\n\nvar integer = new CoreType(\"integer\", TypeFlags.Integer, function (v) {\n return isInteger(v);\n});\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\n\nvar boolean = new CoreType(\"boolean\", TypeFlags.Boolean, function (v) {\n return typeof v === \"boolean\";\n});\n/**\n * `types.null` - The type of the value `null`\n */\n\nvar nullType = new CoreType(\"null\", TypeFlags.Null, function (v) {\n return v === null;\n});\n/**\n * `types.undefined` - The type of the value `undefined`\n */\n\nvar undefinedType = new CoreType(\"undefined\", TypeFlags.Undefined, function (v) {\n return v === undefined;\n});\n\nvar _DatePrimitive = new CoreType(\"Date\", TypeFlags.Date, function (v) {\n return typeof v === \"number\" || v instanceof Date;\n}, function (v) {\n return v instanceof Date ? v : new Date(v);\n});\n\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 */\n\n\nvar DatePrimitive = _DatePrimitive;\n/**\n * @internal\n * @hidden\n */\n\nfunction getPrimitiveFactoryFromValue(value) {\n switch (typeof value) {\n case \"string\":\n return string;\n\n case \"number\":\n return number;\n // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now\n\n case \"boolean\":\n return boolean;\n\n case \"object\":\n if (value instanceof Date) return DatePrimitive;\n }\n\n throw fail$1(\"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 */\n\n\nfunction isPrimitiveType(type) {\n return isType(type) && (type.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.Integer | TypeFlags.Boolean | TypeFlags.Date)) > 0;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar Literal =\n/** @class */\nfunction (_super) {\n __extends(Literal, _super);\n\n function Literal(value) {\n var _this = _super.call(this, JSON.stringify(value)) || this;\n\n _this.flags = TypeFlags.Literal;\n _this.value = value;\n return _this;\n }\n\n Literal.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n return createScalarNode(this, parent, subpath, environment, initialValue);\n };\n\n Literal.prototype.describe = function () {\n return JSON.stringify(this.value);\n };\n\n Literal.prototype.isValidSnapshot = function (value, context) {\n if (isPrimitive(value) && value === this.value) {\n return typeCheckSuccess();\n }\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 */\n\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 */\n\n\nfunction isLiteralType(type) {\n return isType(type) && (type.flags & TypeFlags.Literal) > 0;\n}\n\nvar Refinement =\n/** @class */\nfunction (_super) {\n __extends(Refinement, _super);\n\n function Refinement(name, _subtype, _predicate, _message) {\n var _this = _super.call(this, name) || this;\n\n _this._subtype = _subtype;\n _this._predicate = _predicate;\n _this._message = _message;\n return _this;\n }\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\n Refinement.prototype.describe = function () {\n return this.name;\n };\n\n Refinement.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n // create the child type\n return this._subtype.instantiate(parent, subpath, environment, initialValue);\n };\n\n Refinement.prototype.isAssignableFrom = function (type) {\n return this._subtype.isAssignableFrom(type);\n };\n\n Refinement.prototype.isValidSnapshot = function (value, context) {\n var subtypeErrors = this._subtype.validate(value, context);\n\n if (subtypeErrors.length > 0) return subtypeErrors;\n var snapshot = isStateTreeNode(value) ? getStateTreeNode(value).snapshot : value;\n\n if (!this._predicate(snapshot)) {\n return typeCheckFailure(context, value, this._message(value));\n }\n\n return typeCheckSuccess();\n };\n\n Refinement.prototype.reconcile = function (current, newValue, parent, subpath) {\n return this._subtype.reconcile(current, newValue, parent, subpath);\n };\n\n Refinement.prototype.getSubTypes = 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 */\n\n\nfunction refinement() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\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) {\n return \"Value does not respect the refinement predicate\";\n }; // ensures all parameters are correct\n\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 */\n\n\nfunction isRefinementType(type) {\n return (type.flags & TypeFlags.Refinement) > 0;\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 */\n\n\nfunction enumeration(name, options) {\n var realOptions = typeof name === \"string\" ? options : name; // check all options\n\n if (devMode()) {\n realOptions.forEach(function (option, i) {\n assertIsString(option, i + 1);\n });\n }\n\n var type = union.apply(void 0, __spread(realOptions.map(function (option) {\n return literal(\"\" + option);\n })));\n if (typeof name === \"string\") type.name = name;\n return type;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar Union =\n/** @class */\nfunction (_super) {\n __extends(Union, _super);\n\n function Union(name, _types, options) {\n var _this = _super.call(this, name) || this;\n\n _this._types = _types;\n _this._eager = true;\n options = __assign({\n eager: true,\n dispatcher: undefined\n }, options);\n _this._dispatcher = options.dispatcher;\n if (!options.eager) _this._eager = false;\n return _this;\n }\n\n Object.defineProperty(Union.prototype, \"flags\", {\n get: function () {\n var result = TypeFlags.Union;\n\n this._types.forEach(function (type) {\n result |= type.flags;\n });\n\n return result;\n },\n enumerable: false,\n configurable: true\n });\n\n Union.prototype.isAssignableFrom = function (type) {\n return this._types.some(function (subType) {\n return subType.isAssignableFrom(type);\n });\n };\n\n Union.prototype.describe = function () {\n return \"(\" + this._types.map(function (factory) {\n return factory.describe();\n }).join(\" | \") + \")\";\n };\n\n Union.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n var type = this.determineType(initialValue, undefined);\n if (!type) throw fail$1(\"No matching type for union \" + this.describe()); // can happen in prod builds\n\n return type.instantiate(parent, subpath, environment, initialValue);\n };\n\n Union.prototype.reconcile = function (current, newValue, parent, subpath) {\n var type = this.determineType(newValue, current.type);\n if (!type) throw fail$1(\"No matching type for union \" + this.describe()); // can happen in prod builds\n\n return type.reconcile(current, newValue, parent, subpath);\n };\n\n Union.prototype.determineType = function (value, reconcileCurrentType) {\n // try the dispatcher, if defined\n if (this._dispatcher) {\n return this._dispatcher(value);\n } // find the most accomodating type\n // if we are using reconciliation try the current node type first (fix for #1045)\n\n\n if (reconcileCurrentType) {\n if (reconcileCurrentType.is(value)) {\n return reconcileCurrentType;\n }\n\n return this._types.filter(function (t) {\n return t !== reconcileCurrentType;\n }).find(function (type) {\n return type.is(value);\n });\n } else {\n return this._types.find(function (type) {\n return type.is(value);\n });\n }\n };\n\n Union.prototype.isValidSnapshot = function (value, context) {\n if (this._dispatcher) {\n return this._dispatcher(value).validate(value, context);\n }\n\n var allErrors = [];\n var applicableTypes = 0;\n\n for (var i = 0; i < this._types.length; i++) {\n var type = this._types[i];\n var errors = type.validate(value, context);\n\n if (errors.length === 0) {\n if (this._eager) return typeCheckSuccess();else applicableTypes++;\n } else {\n allErrors.push(errors);\n }\n }\n\n if (applicableTypes === 1) return typeCheckSuccess();\n return typeCheckFailure(context, value, \"No type is applicable for the union\").concat(flattenTypeErrors(allErrors));\n };\n\n Union.prototype.getSubTypes = 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 */\n\n\nfunction union(optionsOrType) {\n var otherTypes = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n otherTypes[_i - 1] = arguments[_i];\n }\n\n var options = isType(optionsOrType) ? undefined : optionsOrType;\n var types = isType(optionsOrType) ? __spread([optionsOrType], otherTypes) : otherTypes;\n var name = \"(\" + types.map(function (type) {\n return type.name;\n }).join(\" | \") + \")\"; // check all options\n\n if (devMode()) {\n if (options) {\n assertArg(options, function (o) {\n return isPlainObject(o);\n }, \"object { eager?: boolean, dispatcher?: Function }\", 1);\n }\n\n types.forEach(function (type, i) {\n assertIsType(type, options ? i + 2 : i + 1);\n });\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 */\n\n\nfunction isUnionType(type) {\n return (type.flags & TypeFlags.Union) > 0;\n}\n/**\n * @hidden\n * @internal\n */\n\n\nvar OptionalValue =\n/** @class */\nfunction (_super) {\n __extends(OptionalValue, _super);\n\n function OptionalValue(_subtype, _defaultValue, optionalValues) {\n var _this = _super.call(this, _subtype.name) || this;\n\n _this._subtype = _subtype;\n _this._defaultValue = _defaultValue;\n _this.optionalValues = optionalValues;\n return _this;\n }\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\n OptionalValue.prototype.describe = function () {\n return this._subtype.describe() + \"?\";\n };\n\n OptionalValue.prototype.instantiate = 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\n return this._subtype.instantiate(parent, subpath, environment, initialValue);\n };\n\n OptionalValue.prototype.reconcile = function (current, newValue, parent, subpath) {\n return this._subtype.reconcile(current, this.optionalValues.indexOf(newValue) < 0 && this._subtype.is(newValue) ? newValue : this.getDefaultInstanceOrSnapshot(), parent, subpath);\n };\n\n OptionalValue.prototype.getDefaultInstanceOrSnapshot = function () {\n var defaultInstanceOrSnapshot = typeof this._defaultValue === \"function\" ? this._defaultValue() : this._defaultValue; // while static values are already snapshots and checked on types.optional\n // generator functions must always be rechecked just in case\n\n if (typeof this._defaultValue === \"function\") {\n typecheckInternal(this, defaultInstanceOrSnapshot);\n }\n\n return defaultInstanceOrSnapshot;\n };\n\n OptionalValue.prototype.isValidSnapshot = function (value, context) {\n // defaulted values can be skipped\n if (this.optionalValues.indexOf(value) >= 0) {\n return typeCheckSuccess();\n } // bounce validation to the sub-type\n\n\n return this._subtype.validate(value, context);\n };\n\n OptionalValue.prototype.isAssignableFrom = function (type) {\n return this._subtype.isAssignableFrom(type);\n };\n\n OptionalValue.prototype.getSubTypes = function () {\n return this._subtype;\n };\n\n return OptionalValue;\n}(BaseType);\n\nfunction checkOptionalPreconditions(type, defaultValueOrFunction) {\n // make sure we never pass direct instances\n if (typeof defaultValueOrFunction !== \"function\" && isStateTreeNode(defaultValueOrFunction)) {\n throw fail$1(\"default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead\");\n }\n\n assertIsType(type, 1);\n\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 */\n\n\nfunction optional(type, defaultValueOrFunction, optionalValues) {\n checkOptionalPreconditions(type, defaultValueOrFunction);\n return new OptionalValue(type, defaultValueOrFunction, optionalValues ? optionalValues : undefinedAsOptionalValues);\n}\n\nvar undefinedAsOptionalValues = [undefined];\n/**\n * Returns if a value represents an optional type.\n *\n * @template IT\n * @param type\n * @returns\n */\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 */\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 */\n\n\nfunction maybeNull(type) {\n assertIsType(type, 1);\n return union(type, optionalNullType);\n}\n\nvar Late =\n/** @class */\nfunction (_super) {\n __extends(Late, _super);\n\n function Late(name, _definition) {\n var _this = _super.call(this, name) || this;\n\n _this._definition = _definition;\n return _this;\n }\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\n Late.prototype.getSubType = function (mustSucceed) {\n if (!this._subType) {\n var t = undefined;\n\n try {\n t = this._definition();\n } catch (e) {\n if (e instanceof ReferenceError) // can happen in strict ES5 code when a definition is self refering\n t = undefined;else throw e;\n }\n\n if (mustSucceed && t === undefined) throw fail$1(\"Late type seems to be used too early, the definition (still) returns undefined\");\n\n if (t) {\n if (devMode() && !isType(t)) throw fail$1(\"Failed to determine subtype, make sure types.late returns a type definition.\");\n this._subType = t;\n }\n }\n\n return this._subType;\n };\n\n Late.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n return this.getSubType(true).instantiate(parent, subpath, environment, initialValue);\n };\n\n Late.prototype.reconcile = function (current, newValue, parent, subpath) {\n return this.getSubType(true).reconcile(current, newValue, parent, subpath);\n };\n\n Late.prototype.describe = function () {\n var t = this.getSubType(false);\n return t ? t.name : \"\";\n };\n\n Late.prototype.isValidSnapshot = function (value, context) {\n var t = this.getSubType(false);\n\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\n return t.validate(value, context);\n };\n\n Late.prototype.isAssignableFrom = function (type) {\n var t = this.getSubType(false);\n return t ? t.isAssignableFrom(type) : false;\n };\n\n Late.prototype.getSubTypes = 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 */\n\n\nfunction late(nameOrType, maybeType) {\n var name = typeof nameOrType === \"string\" ? nameOrType : \"late(\" + nameOrType.toString() + \")\";\n var type = typeof nameOrType === \"string\" ? maybeType : nameOrType; // checks that the type is actually a late type\n\n if (devMode()) {\n if (!(typeof type === \"function\" && type.length === 0)) throw fail$1(\"Invalid late type, expected a function with zero arguments that returns a type, got: \" + type);\n }\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 */\n\n\nfunction isLateType(type) {\n return isType(type) && (type.flags & TypeFlags.Late) > 0;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar Frozen =\n/** @class */\nfunction (_super) {\n __extends(Frozen, _super);\n\n function Frozen(subType) {\n var _this = _super.call(this, subType ? \"frozen(\" + subType.name + \")\" : \"frozen\") || this;\n\n _this.subType = subType;\n _this.flags = TypeFlags.Frozen;\n return _this;\n }\n\n Frozen.prototype.describe = function () {\n return \"\";\n };\n\n Frozen.prototype.instantiate = function (parent, subpath, environment, value) {\n // create the node\n return createScalarNode(this, parent, subpath, environment, deepFreeze(value));\n };\n\n Frozen.prototype.isValidSnapshot = function (value, context) {\n if (!isSerializable(value)) {\n return typeCheckFailure(context, value, \"Value is not serializable and cannot be frozen\");\n }\n\n if (this.subType) return this.subType.validate(value, context);\n return typeCheckSuccess();\n };\n\n return Frozen;\n}(SimpleType);\n\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 */\n\nfunction frozen(arg) {\n if (arguments.length === 0) return untypedFrozenInstance;else if (isType(arg)) return new Frozen(arg);else return optional(untypedFrozenInstance, arg);\n}\n/**\n * Returns if a given value represents a frozen type.\n *\n * @param type\n * @returns\n */\n\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\n case Hook.beforeDetach:\n return \"detach\";\n\n default:\n return undefined;\n }\n}\n\nvar StoredReference =\n/** @class */\nfunction () {\n function StoredReference(value, targetType) {\n this.targetType = targetType;\n\n if (isValidIdentifier(value)) {\n this.identifier = value;\n } else if (isStateTreeNode(value)) {\n var targetNode = getStateTreeNode(value);\n if (!targetNode.identifierAttribute) throw fail$1(\"Can only store references with a defined identifier attribute.\");\n var id = targetNode.unnormalizedIdentifier;\n\n if (id === null || id === undefined) {\n throw fail$1(\"Can only store references to tree nodes with a defined identifier.\");\n }\n\n this.identifier = id;\n } else {\n throw fail$1(\"Can only store references to tree nodes or identifiers, got: '\" + value + \"'\");\n }\n }\n\n StoredReference.prototype.updateResolvedReference = function (node) {\n var normalizedId = normalizeIdentifier(this.identifier);\n var root = node.root;\n var lastCacheModification = root.identifierCache.getLastCacheModificationPerId(normalizedId);\n\n if (!this.resolvedReference || this.resolvedReference.lastCacheModification !== lastCacheModification) {\n var targetType = this.targetType; // reference was initialized with the identifier of the target\n\n var target = root.identifierCache.resolve(targetType, normalizedId);\n\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\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 */\n\n\nvar InvalidReferenceError =\n/** @class */\nfunction (_super) {\n __extends(InvalidReferenceError, _super);\n\n function InvalidReferenceError(m) {\n var _this = _super.call(this, m) || this;\n\n Object.setPrototypeOf(_this, InvalidReferenceError.prototype);\n return _this;\n }\n\n return InvalidReferenceError;\n}(Error);\n/**\n * @internal\n * @hidden\n */\n\n\nvar BaseReferenceType =\n/** @class */\nfunction (_super) {\n __extends(BaseReferenceType, _super);\n\n function BaseReferenceType(targetType, onInvalidated) {\n var _this = _super.call(this, \"reference(\" + targetType.name + \")\") || this;\n\n _this.targetType = targetType;\n _this.onInvalidated = onInvalidated;\n _this.flags = TypeFlags.Reference;\n return _this;\n }\n\n BaseReferenceType.prototype.describe = function () {\n return this.name;\n };\n\n BaseReferenceType.prototype.isAssignableFrom = function (type) {\n return this.targetType.isAssignableFrom(type);\n };\n\n BaseReferenceType.prototype.isValidSnapshot = function (value, context) {\n return isValidIdentifier(value) ? typeCheckSuccess() : typeCheckFailure(context, value, \"Value is not a valid identifier, which is a string or a number\");\n };\n\n BaseReferenceType.prototype.fireInvalidated = 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\n if (!storedRefParentNode || !storedRefParentNode.isAlive) {\n return;\n }\n\n var storedRefParentValue = storedRefParentNode.storedValue;\n\n if (!storedRefParentValue) {\n return;\n }\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 } else {\n applyPatch(storedRefNode.root.storedValue, {\n op: \"remove\",\n path: storedRefNode.path\n });\n }\n }\n });\n };\n\n BaseReferenceType.prototype.addTargetNodeWatcher = function (storedRefNode, referenceId) {\n var _this = this; // this will make sure the target node becomes created\n\n\n var refTargetValue = this.getValue(storedRefNode);\n\n if (!refTargetValue) {\n return undefined;\n }\n\n var refTargetNode = getStateTreeNode(refTargetValue);\n\n var hookHandler = function (_, refTargetNodeHook) {\n var cause = getInvalidationCause(refTargetNodeHook);\n\n if (!cause) {\n return;\n }\n\n _this.fireInvalidated(cause, storedRefNode, referenceId, refTargetNode);\n };\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 BaseReferenceType.prototype.watchTargetNodeForInvalidations = function (storedRefNode, identifier, customGetSet) {\n var _this = this;\n\n if (!this.onInvalidated) {\n return;\n }\n\n var onRefTargetDestroyedHookDisposer; // 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\n storedRefNode.registerHook(Hook.beforeDestroy, function () {\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer();\n }\n });\n\n var startWatching = function (sync) {\n // re-create hook in case the stored ref gets reattached\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer();\n } // make sure the target node is actually there and initialized\n\n\n var storedRefParentNode = storedRefNode.parent;\n var storedRefParentValue = storedRefParentNode && storedRefParentNode.storedValue;\n\n if (storedRefParentNode && storedRefParentNode.isAlive && storedRefParentValue) {\n var refTargetNodeExists = void 0;\n\n if (customGetSet) {\n refTargetNodeExists = !!customGetSet.get(identifier, storedRefParentValue);\n } else {\n refTargetNodeExists = storedRefNode.root.identifierCache.has(_this.targetType, normalizeIdentifier(identifier));\n }\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 } else {\n onRefTargetDestroyedHookDisposer = _this.addTargetNodeWatcher(storedRefNode, identifier);\n }\n }\n };\n\n if (storedRefNode.state === NodeLifeCycle.FINALIZED) {\n // already attached, so the whole tree is ready\n startWatching(true);\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 } // start watching once the node is attached somewhere / parent changes\n\n\n storedRefNode.registerHook(Hook.afterAttach, function () {\n startWatching(false);\n });\n }\n };\n\n return BaseReferenceType;\n}(SimpleType);\n/**\n * @internal\n * @hidden\n */\n\n\nvar IdentifierReferenceType =\n/** @class */\nfunction (_super) {\n __extends(IdentifierReferenceType, _super);\n\n function IdentifierReferenceType(targetType, onInvalidated) {\n return _super.call(this, targetType, onInvalidated) || this;\n }\n\n IdentifierReferenceType.prototype.getValue = function (storedRefNode) {\n if (!storedRefNode.isAlive) return undefined;\n var storedRef = storedRefNode.storedValue;\n return storedRef.resolvedValue;\n };\n\n IdentifierReferenceType.prototype.getSnapshot = function (storedRefNode) {\n var ref = storedRefNode.storedValue;\n return ref.identifier;\n };\n\n IdentifierReferenceType.prototype.instantiate = 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 IdentifierReferenceType.prototype.reconcile = function (current, newValue, parent, subpath) {\n if (!current.isDetaching && current.type === this) {\n var compareByValue = isStateTreeNode(newValue);\n var ref = current.storedValue;\n\n if (!compareByValue && ref.identifier === newValue || compareByValue && ref.resolvedValue === newValue) {\n current.setParent(parent, subpath);\n return current;\n }\n }\n\n var newNode = this.instantiate(parent, subpath, undefined, newValue);\n current.die(); // noop if detaching\n\n return newNode;\n };\n\n return IdentifierReferenceType;\n}(BaseReferenceType);\n/**\n * @internal\n * @hidden\n */\n\n\nvar CustomReferenceType =\n/** @class */\nfunction (_super) {\n __extends(CustomReferenceType, _super);\n\n function CustomReferenceType(targetType, options, onInvalidated) {\n var _this = _super.call(this, targetType, onInvalidated) || this;\n\n _this.options = options;\n return _this;\n }\n\n CustomReferenceType.prototype.getValue = function (storedRefNode) {\n if (!storedRefNode.isAlive) return undefined;\n var referencedNode = this.options.get(storedRefNode.storedValue, storedRefNode.parent ? storedRefNode.parent.storedValue : null);\n return referencedNode;\n };\n\n CustomReferenceType.prototype.getSnapshot = function (storedRefNode) {\n return storedRefNode.storedValue;\n };\n\n CustomReferenceType.prototype.instantiate = function (parent, subpath, environment, newValue) {\n var identifier = isStateTreeNode(newValue) ? this.options.set(newValue, parent ? parent.storedValue : null) : newValue;\n var storedRefNode = createScalarNode(this, parent, subpath, environment, identifier);\n this.watchTargetNodeForInvalidations(storedRefNode, identifier, this.options);\n return storedRefNode;\n };\n\n CustomReferenceType.prototype.reconcile = function (current, newValue, parent, subpath) {\n var newIdentifier = isStateTreeNode(newValue) ? this.options.set(newValue, current ? current.storedValue : null) : newValue;\n\n if (!current.isDetaching && current.type === this && current.storedValue === newIdentifier) {\n current.setParent(parent, subpath);\n return current;\n }\n\n var newNode = this.instantiate(parent, subpath, undefined, newIdentifier);\n current.die(); // noop if detaching\n\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 */\n\n\nfunction reference(subType, options) {\n assertIsType(subType, 1);\n\n if (devMode()) {\n if (arguments.length === 2 && typeof arguments[1] === \"string\") {\n // istanbul ignore next\n throw fail$1(\"References with base path are no longer supported. Please remove the base path.\");\n }\n }\n\n var getSetOptions = options ? options : undefined;\n var onInvalidated = options ? options.onInvalidated : undefined;\n\n if (getSetOptions && (getSetOptions.get || getSetOptions.set)) {\n if (devMode()) {\n if (!getSetOptions.get || !getSetOptions.set) {\n throw fail$1(\"reference options must either contain both a 'get' and a 'set' method or none of them\");\n }\n }\n\n return new CustomReferenceType(subType, {\n get: getSetOptions.get,\n set: getSetOptions.set\n }, onInvalidated);\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 */\n\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 *\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 */\n\n\nfunction safeReference(subType, options) {\n var refType = reference(subType, __assign(__assign({}, options), {\n onInvalidated: function (ev) {\n ev.removeRef();\n }\n }));\n\n if (options && options.acceptsUndefined === false) {\n return refType;\n } else {\n return maybe(refType);\n }\n}\n\nvar BaseIdentifierType =\n/** @class */\nfunction (_super) {\n __extends(BaseIdentifierType, _super);\n\n function BaseIdentifierType(name, validType) {\n var _this = _super.call(this, name) || this;\n\n _this.validType = validType;\n _this.flags = TypeFlags.Identifier;\n return _this;\n }\n\n BaseIdentifierType.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n if (!parent || !(parent.type instanceof ModelType)) throw fail$1(\"Identifier types can only be instantiated as direct child of a model type\");\n return createScalarNode(this, parent, subpath, environment, initialValue);\n };\n\n BaseIdentifierType.prototype.reconcile = 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) throw fail$1(\"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 BaseIdentifierType.prototype.isValidSnapshot = 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\n return typeCheckSuccess();\n };\n\n return BaseIdentifierType;\n}(SimpleType);\n/**\n * @internal\n * @hidden\n */\n\n\nvar IdentifierType =\n/** @class */\nfunction (_super) {\n __extends(IdentifierType, _super);\n\n function IdentifierType() {\n var _this = _super.call(this, \"identifier\", \"string\") || this;\n\n _this.flags = TypeFlags.Identifier;\n return _this;\n }\n\n IdentifierType.prototype.describe = function () {\n return \"identifier\";\n };\n\n return IdentifierType;\n}(BaseIdentifierType);\n/**\n * @internal\n * @hidden\n */\n\n\nvar IdentifierNumberType =\n/** @class */\nfunction (_super) {\n __extends(IdentifierNumberType, _super);\n\n function IdentifierNumberType() {\n return _super.call(this, \"identifierNumber\", \"number\") || this;\n }\n\n IdentifierNumberType.prototype.getSnapshot = function (node) {\n return node.storedValue;\n };\n\n IdentifierNumberType.prototype.describe = 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 */\n\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 */\n\nvar identifierNumber = new IdentifierNumberType();\n/**\n * Returns if a given value represents an identifier type.\n *\n * @param type\n * @returns\n */\n\nfunction isIdentifierType(type) {\n return isType(type) && (type.flags & TypeFlags.Identifier) > 0;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction normalizeIdentifier(id) {\n return \"\" + id;\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction isValidIdentifier(id) {\n return typeof id === \"string\" || typeof id === \"number\";\n}\n/**\n * @internal\n * @hidden\n */\n\n\nfunction assertIsValidIdentifier(id, argNumber) {\n assertArg(id, isValidIdentifier, \"string or number (identifier)\", argNumber);\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 {\n * // Friendly name\n * name: string\n * // given a serialized value and environment, how to turn it into the target type\n * fromSnapshot(snapshot: S, env: any): T\n * // return the serialization of the current value\n * toSnapshot(value: T): S\n * // if true, this is a converted value, if false, it's a snapshot\n * isTargetType(value: T | S): value is T\n * // a non empty string is assumed to be a validation error\n * getValidationMessage?(snapshot: S): string\n * }\n * ```\n *\n * Example:\n * ```ts\n * const DecimalPrimitive = types.custom({\n * name: \"Decimal\",\n * fromSnapshot(value: string) {\n * return new Decimal(value)\n * },\n * toSnapshot(value: Decimal) {\n * return value.toString()\n * },\n * isTargetType(value: string | Decimal): boolean {\n * return value instanceof Decimal\n * },\n * getValidationMessage(value: string): string {\n * if (/^-?\\d+\\.\\d+$/.test(value)) return \"\" // OK\n * return `'${value}' doesn't look like a valid decimal number`\n * }\n * })\n *\n * const Wallet = types.model({\n * balance: DecimalPrimitive\n * })\n * ```\n *\n * @param options\n * @returns\n */\n\n\nfunction custom(options) {\n return new CustomType(options);\n}\n/**\n * @internal\n * @hidden\n */\n\n\nvar CustomType =\n/** @class */\nfunction (_super) {\n __extends(CustomType, _super);\n\n function CustomType(options) {\n var _this = _super.call(this, options.name) || this;\n\n _this.options = options;\n _this.flags = TypeFlags.Custom;\n return _this;\n }\n\n CustomType.prototype.describe = function () {\n return this.name;\n };\n\n CustomType.prototype.isValidSnapshot = function (value, context) {\n if (this.options.isTargetType(value)) return typeCheckSuccess();\n var typeError = this.options.getValidationMessage(value);\n\n if (typeError) {\n return typeCheckFailure(context, value, \"Invalid value for type '\" + this.name + \"': \" + typeError);\n }\n\n return typeCheckSuccess();\n };\n\n CustomType.prototype.getSnapshot = function (node) {\n return this.options.toSnapshot(node.storedValue);\n };\n\n CustomType.prototype.instantiate = function (parent, subpath, environment, initialValue) {\n var valueToStore = this.options.isTargetType(initialValue) ? initialValue : this.options.fromSnapshot(initialValue, parent && parent.root.environment);\n return createScalarNode(this, parent, subpath, environment, valueToStore);\n };\n\n CustomType.prototype.reconcile = function (current, value, parent, subpath) {\n var isSnapshot = !this.options.isTargetType(value); // in theory customs use scalar nodes which cannot be detached, but still...\n\n if (!current.isDetaching) {\n var unchanged = current.type === this && (isSnapshot ? value === current.snapshot : value === current.storedValue);\n\n if (unchanged) {\n current.setParent(parent, subpath);\n return current;\n }\n }\n\n var valueToStore = isSnapshot ? this.options.fromSnapshot(value, parent.root.environment) : value;\n var newNode = this.instantiate(parent, subpath, undefined, valueToStore);\n current.die(); // noop if detaching\n\n return newNode;\n };\n\n return CustomType;\n}(SimpleType); // we import the types to re-export them inside types.\n\n\nvar types = {\n enumeration: enumeration,\n model: model,\n compose: compose,\n custom: custom,\n reference: reference,\n safeReference: safeReference,\n union: union,\n optional: optional,\n literal: literal,\n maybe: maybe,\n maybeNull: maybeNull,\n refinement: refinement,\n string: string,\n boolean: boolean,\n number: number,\n integer: integer,\n Date: DatePrimitive,\n map: map,\n array: array,\n frozen: frozen,\n identifier: identifier,\n identifierNumber: identifierNumber,\n late: late,\n undefined: undefinedType,\n null: nullType,\n snapshotProcessor: snapshotProcessor\n};\nexport { addDisposer, addMiddleware, applyAction, applyPatch, applySnapshot, cast, castFlowReturn, castToReferenceSnapshot, castToSnapshot, clone, createActionTrackingMiddleware, createActionTrackingMiddleware2, decorate, destroy, detach, escapeJsonPath, flow, getChildType, getEnv, getIdentifier, getLivelinessChecking, getMembers, getNodeId, getParent, getParentOfType, getPath, getPathParts, getPropertyMembers, getRelativePath, getRoot, getRunningActionContext, getSnapshot, getType, hasParent, hasParentOfType, isActionContextChildOf, isActionContextThisOrChildOf, isAlive, isArrayType, isFrozenType, isIdentifierType, isLateType, isLiteralType, isMapType, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isRefinementType, isRoot, isStateTreeNode, isType, isUnionType, isValidReference, joinJsonPath, onAction, onPatch, onSnapshot, process$1 as process, protect, recordActions, recordPatches, resolveIdentifier, resolvePath, setLivelinessChecking, setLivelynessChecking, splitJsonPath, toGenerator, toGeneratorFunction, tryReference, tryResolve, typecheck, types, unescapeJsonPath, unprotect, walk };"],"sourceRoot":""}